<template>
  <!-- TODO 图片 -->
  <view
    :class="[
      'pl-20',
      'pr-20',
      'pb-40',
      `container-${dialogVisible ? 'hidden' : ''}`,
    ]"
  >
    <view class="banner flex-column" v-if="canUseCount >= 0">
      <view class="fs-40 fw-600 color-000">{{ title }}</view>
      <view class="flex-align-center mt-10 height-48 relative flex-shrink">
        <image
          src="/pages-charge/static/machines-banner-address.png"
          mode="widthFix"
          style="width: 16px; display: block; flex-shrink: 0"
        />
        <view class="ml-12 fs-26 color-666">{{ location.address }}</view>
        <view class="flex-center ml-auto nav" @click="openAddress">
          <image
            src="/pages-charge/static/machines-banner-nav.png"
            mode="widthFix"
          />
          <view class="fs-26" style="color: #347dff">导航</view>
        </view>
      </view>
      <view class="foot mt-30 flex-align-center flex-shrink" @click="openDesc">
        <view class="fs-28 color-666">可用充电桩：</view>
        <view class="fs-36 fw-500 color-primary">{{ canUseCount }}</view>
        <view class="fs-28 color-primary ml-6">个</view>
        <view class="fs-28 color-666 ml-auto">{{ canUseTime }}</view>
      </view>
    </view>
    <view class="pt-40 pb-20 fs-32 fw-500 color-999">详细说明</view>
    <view class="desc" v-if="station">
      <view class="flex-align-center" @click="openDesc">
        <view class="width-168 fs-26 color-666">充电费用</view>
        <view class="fs-26 color-000">{{ canUsePrice }}元/度</view>
        <view class="ml-auto lh-0">
          <uni-icons type="right" size="18" color="rgba(0,0,0,0.4)"></uni-icons>
        </view>
      </view>
      <view class="flex-align-center">
        <view class="width-168 fs-26 color-666">停车费用</view>
        <view class="fs-26 color-000">{{
          Number(station.parkFee) > 0 ? station.parkFee : "免费"
        }}</view>
      </view>
      <view
        class="flex-align-center"
        v-if="
          station &&
          station.equipmentInfos &&
          station.equipmentInfos.length &&
          station.equipmentInfos[0].connectorInfos
        "
      >
        <view class="width-168 fs-26 color-666">充电桩类型</view>
        <view class="fs-26 color-000"
          >{{
            station.equipmentInfos[0].connectorInfos[0].connectorType === 1
              ? "直流"
              : "交流"
          }}{{ station.equipmentInfos[0].connectorInfos[0].power }}kw</view
        >
      </view>
    </view>
    <view class="pt-40 flex-align-center">
      <view class="fs-32 fw-500 color-999">充电桩</view>
      <view class="fs-26 color-999" v-if="station"
        >（共{{ totalCount }}个）</view
      >
      <view class="ml-auto flex-align-center" @click="openStatus">
        <view class="fs-28 color-333 mr-16">{{
          statusList[status].title
        }}</view>
        <view
          style="
            width: 0;
            height: 0;
            border: 8rpx solid;
            border-color: #333 transparent transparent transparent;
            margin-top: 8rpx;
          "
        ></view>
      </view>
    </view>
    <template
      v-if="station"
      v-for="(item, index) in stationEquipmentInfos"
      :key="index"
    >
      <ChargeMachine
        :title="'NO.' + item.shortId"
        :price="station.totalFee"
        :time="currentTime"
        :list="item.connectorInfos"
      ></ChargeMachine>
    </template>
    <view class="dialog flex-align-end" v-if="dialogVisible">
      <view class="desc-dialog">
        <view class="desc-dialog_head flex-center">
          <view class="fw-500 color-000" style="font-size: 16px">{{
            dialogType === "desc" ? "充电费用说明" : "选择充电桩状态"
          }}</view>
          <view class="close" @click="closeDialog">
            <uni-icons type="closeempty" size="24" color="#2D284B"></uni-icons>
          </view>
        </view>
        <view class="desc-dialog_body">
          <view class="table" v-if="dialogType === 'desc'">
            <view class="tr flex">
              <view class="th flex-center fs-28">时间</view>
              <view class="th flex-center flex-column">
                <view>电费</view>
                <view class="fs-24 lh-24" style="color: rgba(0, 0, 0, 0.5)"
                  >（元/kwh）</view
                >
              </view>
              <view class="th flex-center flex-column">
                <view>服务费</view>
                <view class="fs-24 lh-24" style="color: rgba(0, 0, 0, 0.5)"
                  >（元/kwh）</view
                >
              </view>
            </view>
            <view
              class="tr flex"
              v-for="(item, index) in desc"
              :key="index"
              :style="{
                'border-top': `1rpx solid ${
                  index === 0 ? 'transparent' : '#E5E5E5'
                }`,
              }"
            >
              <view class="td flex-center">{{ item.startTimeFormat }}</view>
              <view class="td flex-center">{{ item.elecPrice }}</view>
              <view class="td flex-center">{{ item.servicePrice }}</view>
            </view>
          </view>
          <view class="status" v-if="dialogType === 'status'">
            <view
              :class="['fs-32', 'flex-align-center']"
              :style="{ color: status === index ? '#347DFF' : '#2d284b' }"
              v-for="(statusItem, index) in statusList"
              :key="index"
              @click="changeStatus(index)"
            >
              {{ statusItem.title }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { fetchStation, fetchStationPriceDesc } from "../../api/charge";
import { onLoad } from "@dcloudio/uni-app";
import ChargeMachine from "./charge-machine/charge-machine.vue";
const dialogVisible = ref(false);
const dialogType = ref("");
const desc = ref<any[]>([]);
const status = ref(0);
const statusList = ref([
  {
    title: "全部",
  },
  {
    title: "空闲",
  },
  {
    title: "充电中",
  },
]);

const totalCount = ref(0);
const canUseCount = ref(0);
const canUseTime = ref("");
const canUsePrice = ref("");
const title = ref("");
const location = ref({
  address: "",
  latitude: "",
  longitude: "",
});

const station = ref();
const stationEquipmentInfos = ref();
const currentTime = ref();

onLoad((options: any) => {
  const _title = options.title || "";
  uni.setNavigationBarTitle({
    title: _title,
  });
  title.value = _title;
  if (getApp<any>().globalData.lastData.station) {
    const { address, latitude, longitude } =
      getApp<any>().globalData.lastData.station;
    location.value = {
      address,
      latitude,
      longitude,
    };
    getApp<any>().globalData.lastData.station = undefined;
  }
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  fetchStation(Number(options.id))
    .then((res) => {
      console.log(res);
      let ConnectorID = "";
      if (res.equipmentInfos && res.equipmentInfos.length) {
        res.equipmentInfos.forEach((item: any) => {
          if (item.connectorInfos && item.connectorInfos.length) {
            item.connectorInfos.forEach((con: any) => {
              totalCount.value++;
              if (!ConnectorID) {
                ConnectorID = con.connectorId;
              }
              if (
                con.connectorStatusInfo &&
                con.connectorStatusInfo.status === 1
              ) {
                canUseCount.value++;
              }
            });
          }
        });
      }
      station.value = res;
      stationEquipmentInfos.value = res.equipmentInfos.map((item: any) => {
        return {
          ...item,
        };
      });
      if (ConnectorID) {
        return fetchStationPriceDesc(ConnectorID);
      } else {
        // eslint-disable-next-line promise/no-return-wrap
        return Promise.resolve({
          policyInfoss: [],
        });
      }
    })
    .then((res) => {
      uni.hideLoading();
      currentTime.value = res.currentTime;
      canUseTime.value = res.useTime;
      canUsePrice.value = `${res.minPrice}~${res.maxPrice}`;
      desc.value = res.policyInfoss || [];
    })
    .catch((err) => {
      // eslint-disable-next-line no-console
      console.log(err);
      uni.hideLoading();
      uni.showToast({
        title: "加载失败，请重试",
        icon: "none",
      });
    });
});
const openAddress = function () {
  uni.openLocation({
    latitude: Number(location.value.latitude),
    longitude: Number(location.value.longitude),
    scale: 18,
    name: title.value,
    address: location.value.address,
  });
};
const openDesc = function () {
  dialogVisible.value = true;
  dialogType.value = "desc";
};
const openStatus = function () {
  if (!stationEquipmentInfos.value || stationEquipmentInfos.value.length <= 0) {
    return;
  }
  dialogVisible.value = true;
  dialogType.value = "status";
};
const closeDialog = function () {
  dialogVisible.value = false;
};
const changeStatus = function (index: number) {
  if (status.value === index) {
    closeDialog();
    return;
  }
  status.value = index;
  if (index === 0) {
    stationEquipmentInfos.value = station.value.equipmentInfos.map(
      (item: any) => {
        return {
          ...item,
        };
      }
    );
    closeDialog();
    return;
  }
  const STATUS_MAP = [-1, 1, 3];
  let newStationEquipmentInfos: any[] = [];
  station.value.equipmentInfos.forEach((item: any) => {
    let check = false;
    if (item.connectorInfos && item.connectorInfos.length) {
      item.connectorInfos.forEach((con: any) => {
        if (
          con.connectorStatusInfo &&
          Number(con.connectorStatusInfo.status) === STATUS_MAP[status.value]
        ) {
          check = true;
        }
      });
    }
    if (check) {
      newStationEquipmentInfos.push(item);
    }
  });
  stationEquipmentInfos.value = newStationEquipmentInfos;
  closeDialog();
};
</script>

<style lang="scss">
@import "../../styles/dialog.scss";
page {
  background-color: #f5f5f5;
}

.container-hidden {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.banner {
  margin-top: 380rpx;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  background-color: #fff;
  min-height: 264rpx;
  padding: 0 40rpx;
  padding-top: 30rpx;

  .nav {
    flex-shrink: 0;
    width: 120rpx;
    height: 48rpx;
    border-radius: 40rpx;
    background: rgba(52, 125, 255, 0.1);
    image {
      width: 36rpx;
    }
  }

  .foot {
    border-top: 1px dashed rgba(0, 0, 0, 0.1);
    height: 96rpx;
  }
}

.desc {
  box-sizing: border-box;
  padding: 0rpx 30rpx;
  border-radius: 20rpx;
  background-color: #fff;
  & > view {
    height: 90rpx;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    &:first-child {
      border-top: none;
    }
  }
}

.desc-dialog {
  background-color: transparent;
  width: 100%;
  overflow: hidden;
  border-radius: 20rpx;

  &_head {
    padding: 24rpx 0px;
    position: relative;
    background-color: #fff;
    .close {
      position: absolute;
      right: 30rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  &_body {
    max-height: 860rpx;
    box-sizing: border-box;
    padding: 0rpx 30rpx 80rpx 30rpx;
    background-color: #fff;
    overflow-y: auto;

    .table {
      border: 1rpx solid #e5e5e5;
      border-radius: 10rpx;
      overflow: hidden;
    }

    .tr {
      width: 100%;

      & > view:nth-child(1) {
        width: 254rpx;
        flex-shrink: 0;
        border-right: 1rpx solid #e5e5e5;
      }

      & > view:nth-child(2) {
        width: 200rpx;
        flex-shrink: 0;
        border-right: 1rpx solid #e5e5e5;
      }

      & > view:nth-child(3) {
        flex-grow: 1;
      }
    }

    .th {
      border-bottom: 1rpx solid #e5e5e5;
      background-color: #f1f6ff;
      height: 92rpx;
      color: rgba(0, 0, 0, 0.7);
      font-size: 28rpx;

      view {
        color: rgba(0, 0, 0, 0.7);
        font-size: 28rpx;
      }
    }

    .td {
      color: #000;
      font-size: 26rpx;
      height: 76rpx;
    }

    .status {
      & > view {
        height: 92rpx;
        border-top: 1px solid rgba(0, 0, 0, 0.1);
        &:first-child {
          border-top: none;
        }
      }
    }
  }
}
</style>
