<script setup lang="ts">
import { ScanCodeUtil, formatStatusName } from '../utils/index'
import router from '@/router'
import { StaticUrl } from '@/config'

const { statusBarHeight, MenuButtonHeight } = storeToRefs(useSysStore())
const activeTab = ref('price')
definePage({
  name: 'charge-detail',
  islogin: false,
  style: {
    navigationBarTitleText: '充电详情',
    navigationStyle: 'custom',
  },
})
const stationId = ref()
onLoad((options: any) => {
  stationId.value = Number(options.stationId)
  activeTab.value = options.type
})
onMounted(() => {
  getPricesList()
  getConnectorsList()
})

const priceDetail = ref<Api.chargeStationPrices>()
async function getPricesList() {
  const res = await Apis.charge.prices({ data: { stationId: stationId.value } })
  priceDetail.value = res.data
}

const connectorsDetail = ref<Api.chargeStationConnectors>()
async function getConnectorsList() {
  const res = await Apis.charge.connectors({ data: { stationId: stationId.value } })
  connectorsDetail.value = res.data
}

/**
 * 处理站点设备状态
 *status 状态：0-离线 1-空闲 2-占用
 */
function getStatusImageByStatus(deviceStatus: number) {
  switch (deviceStatus) {
    case 1: // 空闲
      return 'kx'
    case 2: // 占用
      return 'zy'
    case 3: // 占用
      return 'zy'
    case 0: // 离线
      return 'lx'
    default:
      return 'unknown'
  }
}
// 切换选项卡的方法
function switchTab(tab: string) {
  activeTab.value = tab
}

// 计算样式的方法
function getTabStyle(tab: string) {
  return activeTab.value === tab
    ? { background: 'var(--them-color)', color: '#FFF' }
    : {}
}
async function getDeviceInfo(connectorCode: string) {
  useGlobalLoading().loading({})
  const res = await Apis.charge.connectorDetail({ data: { connectorCode } })
  useGlobalLoading().close()
  if (res.data.status === 0 || res.data.status === 255) {
    useGlobalMessage().alert('此设备异常或被占用，请更换其他设备')
  }
  else {
    router.push({ name: 'charge-start', params: { connectorCode } })
  }
}
async function scanCode() {
  try {
    const connectorCode = await ScanCodeUtil.scanAndGetConnectorCode()
    if (!connectorCode) {
      useGlobalMessage().alert('二维码不正确')
      return
    }
    // 获取设备信息
    getDeviceInfo(connectorCode)
  }
  catch (error) {
    console.error('扫码失败:', error)
  }
}
</script>

<template>
  <view class="charge-detail-page min-h-screen bg-[linear-gradient(181deg,var(--them-color)_0%,#F5F7FB_100%)]">
    <wd-navbar
      title="充电详情" custom-style="background: var(--them-color);"
      :bordered="false" :z-index="999" safe-area-inset-top left-arrow fixed @click-left="router.back()"
    />
    <view :style="{ paddingTop: `${(Number(statusBarHeight) || 44) + MenuButtonHeight + 12}px` }" />
    <view class="content-page box-border px24rpx">
      <view class="flex items-center justify-between">
        <view>
          <view class="text-32rpx font-bold">
            {{ priceDetail?.stationName }}
          </view>
          <view class="mt-16rpx text-24rpx text-#fff">
            {{ priceDetail?.tips || '--' }}
          </view>
        </view>
        <view>
          <image class="h-132rpx w-140rpx" :src="`${StaticUrl}/site-name-icon.png`" />
        </view>
      </view>
      <view class="items-centerrounded-16rpx mt-20rpx flex bg-#FFF p-20rpx">
        <view class="w-230rpx text-center">
          <view class="text-32rpx text-[var(--them-color)] font-bold">
            {{ connectorsDetail?.idleCount }}
          </view>
          <view class="text-24rpx font-500">
            空闲
          </view>
        </view>
        <view class="h-76rpx w-2rpx bg-#F0F0F0" />
        <view class="w-230rpx text-center">
          <view class="text-32rpx text-[var(--them-color)] font-bold">
            {{ connectorsDetail?.occupiedCount }}
          </view>
          <view class="text-24rpx font-500">
            占用
          </view>
        </view>
        <view class="h-76rpx w-2rpx bg-#F0F0F0" />
        <view class="w-230rpx text-center">
          <view class="text-32rpx text-[var(--them-color)] font-bold">
            {{ connectorsDetail?.offlineCount }}
          </view>
          <view class="text-24rpx font-500">
            离线
          </view>
        </view>
      </view>
      <view class="mt-28rpx">
        <view class="flex items-center justify-between rounded-42rpx bg-#FFF p-6rpx">
          <view
            class="h-80rpx w-348rpx rounded-60rpx text-center line-height-[80rpx]" :style="getTabStyle('price')"
            @click="switchTab('price')"
          >
            电站价格
          </view>
          <view
            class="h-80rpx w-348rpx rounded-60rpx text-center line-height-[80rpx]" :style="getTabStyle('terminal')"
            @click="switchTab('terminal')"
          >
            充电终端
          </view>
        </view>
      </view>
      <view v-if="activeTab == 'price'">
        <view
          v-for="item in priceDetail?.priceList" :key="item.timePeriod"
          class="mt-20rpx rounded-16rpx bg-#FFF p-24rpx"
          :style="{ border: item.currentPeriod ? '2rpx solid var(--them-color)' : '' }"
        >
          <view class="relative flex items-center justify-between">
            <view class="flex items-center gap-20rpx">
              <view
                class="h-40rpx w-40rpx rounded-8rpx bg-#CCC text-center text-28rpx text-#FFF font-bold line-height-[40rpx]"
              >
                {{ item.periodFlagName }}
              </view>
              <view class="text-28rpx font-bold">
                {{ item.timePeriod }}
              </view>
            </view>
            <view
              v-if="item.currentPeriod"
              class="absolute h-40rpx w-152rpx rounded-[0_16rpx_0_16rpx] bg-[linear-gradient(181deg,var(--them-color)_0%,#F5F7FB_100%)] text-center text-28rpx text-#FFF font-600 -right-24rpx -top-24rpx"
            >
              当前时段
            </view>
          </view>
          <view class="mt-24rpx rounded-16rpx bg-#F6F6F6 p-20rpx">
            <view class="flex items-center justify-between">
              <view class="text-24rpx text-#222222">
                抵扣券电价
              </view>
              <view
                class="text-24rpx"
                :style="{ color: item.currentPeriod ? '#FF6464' : '', fontWeight: item.currentPeriod ? '800' : '' }"
              >
                <text>{{ item.totalPrice }}</text>
                <text class="text-#AAA">
                  元/度
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-if="activeTab == 'terminal'">
        <view
          v-for="item in connectorsDetail?.connectorList" :key="item.connectorId"
          class="mt-20rpx flex items-center gap-20rpx rounded-16rpx bg-#FFF p-20rpx"
          @click="router.push({ name: 'charge-start', params: { connectorCode: item.connectorCode } })"
        >
          <view
            class="h-116rpx w-116rpx text-center"
            :style="{ backgroundImage: `url(${StaticUrl}/site-status-${getStatusImageByStatus(item.status)}.png)`, backgroundSize: 'cover', backgroundPosition: 'center' }"
          >
            <image class="mt-20rpx h-38rpx w-27.18rpx" :src="`${StaticUrl}/terminal-icon.png`" />
            <view class="text-24rpx font-bold">
              {{ formatStatusName(item.statusName) }}
            </view>
          </view>
          <view>
            <view class="text-bold text-28rpx">
              {{ item.connectorName }}
            </view>
            <view class="mt-4rpx text-24rpx text-#AAA">
              电类分类：{{ item.equipmentType }}
            </view>
            <view class="mt-4rpx w-400rpx overflow-hidden truncate whitespace-nowrap text-24rpx text-#AAA">
              终端编号：{{ item.connectorCode }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="h-180rpx" />
    <view
      class="fixed bottom-66rpx left-24rpx h-100rpx w-702rpx rounded-16rpx bg-[var(--them-color)] text-center text-28rpx font-800 line-height-[100rpx] shadow-[inset_0rpx_6rpx_20rpx_2rpx_#FFFFFF]"
      @click="scanCode"
    >
      扫码充电
    </view>
  </view>
</template>

<style lang="scss" scoped></style>
