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

const { statusBarHeight, MenuButtonHeight } = storeToRefs(useSysStore())
const { Location } = storeToRefs(useAddressStore())
const { opcity } = storeToRefs(useSysStore())
const stationId = ref()
onLoad((options: any) => {
  console.log(options)
  stationId.value = Number(options.stationId)
})
definePage({
  name: 'charge-site-detail',
  islogin: true,
  style: {
    navigationBarTitleText: '站点详情',
    navigationStyle: 'custom',
  },
})
const activeFilter = ref('0')
onMounted(() => {
  getStationDetail()
  opcity.value = 0
})
/**
 * 获取电站详情
 */
const stationDetail = ref<Api.chargeStationDetail>()
async function getStationDetail() {
  useGlobalLoading().loading({})
  const res = await Apis.charge.detail({ data: { stationId: stationId.value, latitude: Location.value.latitude, longitude: Location.value.longitude } })
  stationDetail.value = res.data
  useGlobalLoading().close()
}
// 使用计算属性动态计算筛选选项
const filterOptions = computed(() => {
  const counts = {
    0: 0, // 离线
    1: 0, // 空闲
    2: 0, // 占用
  }

  // 遍历充电站连接器列表，统计各状态数量
  if (stationDetail.value?.connectorList) {
    stationDetail.value.connectorList.forEach((item) => {
      // 检查status是否为有效键值
      if (item.status === 0 || item.status === 1 || item.status === 2) {
        counts[item.status as keyof typeof counts]++
      }
    })
  }

  return [
    { key: '0', label: `离线(${counts['0']})` },
    { key: '1', label: `空闲(${counts['1']})` },
    { key: '2', label: `占用(${counts['2']})` },
  ]
})

// 添加计算属性来过滤设备列表
const filteredConnectors = computed(() => {
  if (!stationDetail.value?.connectorList)
    return []
  // 根据当前选中的状态过滤设备，并限制为前3个
  return stationDetail.value.connectorList.filter(
    item => String(item.status) === activeFilter.value,
  ).slice(0, 3)
})
/**
 * 处理站点设备状态
 *status 状态：0-离线 1-空闲 2-占用
 */
function getStatusImageByStatus(deviceStatus: number) {
  switch (deviceStatus) {
    case 1: // 空闲
      return 'kx'
    case 2: // 占用
      return 'zy'
    case 0: // 离线
      return 'lx'
    default:
      return 'unknown'
  }
}

onPageScroll((e) => {
  const calculatedOpacity = e.scrollTop / 100
  opcity.value = Math.min(1, Math.max(0.1, calculatedOpacity))
})

// 处理筛选项点击的方法
function handleFilterClick(filterKey: string) {
  activeFilter.value = filterKey
  console.log(`选择了: ${filterKey}`)
}

function openMap() {
  uni.openLocation({
    latitude: Number(stationDetail.value?.latitude),
    longitude: Number(stationDetail.value?.longitude),
  })
}

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="site-detail-page min-h-screen bg-#F6FAFF">
    <wd-navbar
      title="站点详情" :custom-style="`background-color: rgba(226, 255, 145, ${opcity})`" :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="site-detail-content">
      <!-- <view>
        <wd-swiper :list="swiperList" :height="260" :indicator="{ type: 'fraction' }" value-key="advertImg" />
      </view> -->
      <view class="bg-#FFF p-20rpx">
        <view class="mt-28rpx box-border px24rpx">
          <view class="text-32rpx font-800">
            {{ stationDetail?.stationName }}
          </view>
          <view class="mt-20rpx flex items-center gap-20rpx">
            <view class="h-30rpx w-30rpx rounded-4rpx bg-#5BE7FF text-center text-24rpx text-#fff line-height-[30rpx]">
              P
            </view>
            <view class="text-24rpx text-#AAA">
              {{ stationDetail?.tips || '--' }}
            </view>
          </view>
        </view>
        <view class="ml-10rpx">
          <view
            class="cardBg-set mt-20rpx box-border h-138rpx w-680rpx flex items-center justify-between rounded-16rpx"
            :style="{ backgroundImage: `url(${StaticUrl}/site-detail-navBg.png)` }"
          >
            <view class="ml-24rpx">
              <view class="text-28rpx text-#2B303A font-bold">
                距离您{{ stationDetail?.distance || '--' }}km
              </view>
              <view class="mt-8rpx w-408rpx overflow-hidden text-ellipsis whitespace-nowrap text-24rpx text-#AAA">
                {{ stationDetail?.address }}
              </view>
            </view>
            <view class="mr-24rpx" @click="openMap">
              <view>
                <image class="h-40rpx w-40rpx" :src="`${StaticUrl}/site-detail-nav.png`" />
              </view>
              <view class="mt-8rpx text-24rpx">
                导航
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="mt20rpx box-border px24rpx">
      <view class="rounded-24rpx bg-#FFF p-24rpx">
        <view class="flex items-center justify-between">
          <view class="text-32rpx font-bold">
            费用信息
          </view>
          <view class="flex items-center" @click="router.push({ name: 'charge-detail', params: { stationId: String(stationDetail?.stationId), type: 'price' } })">
            <view class="text-24rpx text-#AAA">
              查看全部
            </view>
            <wd-icon name="chevron-right" size="22px" color="#AAAAAA" />
          </view>
        </view>
        <view class="mt-24rpx rounded-16rpx bg-[linear-gradient(90deg,#FEE4C6_0%,rgba(251,235,198,0.23)_100%)] p-24rpx">
          <view class="relative flex items-center justify-between">
            <view class="text-28rpx font-bold">
              当前价
            </view>
            <view class="absolute -right-20rpx -top-20rpx">
              <image class="h-52rpx w-125rpx" :src="`${StaticUrl}/site-price-tag.png`" />
            </view>
          </view>
          <view class="mt-24rpx flex items-center justify-between">
            <view>
              <view class="flex items-center">
                <text class="text-48rpx text-#FF6464 font-800">
                  {{ stationDetail?.currentPrice }}
                </text>
                <text class="text-24rpx">
                  元/度
                </text>
              </view>
              <view class="mt-12rpx text-28rpx">
                当前时段：
              </view>
              <view class="text-bold mt-16rpx text-28rpx">
                {{ stationDetail?.currentPeriod }}
              </view>
            </view>
            <view>
              <image class="h-182rpx w-88rpx" :src="`${StaticUrl}/site-price-icon.png`" />
            </view>
          </view>
        </view>
      </view>
      <view class="mt-20rpx rounded-24rpx bg-#FFF p-24rpx">
        <view class="flex items-center justify-between">
          <view class="text-32rpx font-bold">
            充电终端
          </view>
          <view class="flex items-center" @click="router.push({ name: 'charge-detail', params: { stationId: String(stationDetail?.stationId), type: 'terminal' } })">
            <view class="text-24rpx text-#AAA">
              查看全部
            </view>
            <wd-icon name="chevron-right" size="22px" color="#AAAAAA" />
          </view>
        </view>
        <view class="mt-28rpx flex items-center gap-20rpx">
          <view
            v-for="item in filterOptions" :key="item.key"
            class="select-item h-60rpx w-152rpx text-28rpx line-height-[60rpx]" :class="[{ 'select-item-active': activeFilter === item.key }]" @click="handleFilterClick(item.key)"
          >
            {{ item.label }}
          </view>
        </view>
        <view class="mt-24rpx">
          <view v-for="item in filteredConnectors" :key="item.connectorId" class="mb-20rpx flex items-center gap-20rpx rounded-16rpx bg-#F6F6F6 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-300rpx overflow-hidden truncate whitespace-nowrap text-24rpx text-#AAA">
                终端编号：{{ item.connectorCode }}
              </view>
            </view>
          </view>
          <view v-if="filteredConnectors.length < 1" class="h-100rpx w-full text-center text-24rpx text-#AAA line-height-[100rpx]">
            暂无终端信息
          </view>
        </view>
      </view>
    </view>
    <view class="h-170rpx" />
    <view class="fixed bottom-0 left-0 right-0 h-166rpx w-full rounded-[30rpx_30rpx_0_0] bg-#FFF">
      <view
        class="h-166rpx"
        :style="{ backgroundImage: `url(${StaticUrl}/site-price-bg.png)`, backgroundSize: 'cover', backgroundPosition: 'center' }"
      >
        <view class="h-166rpx flex items-center justify-center gap-32rpx">
          <view class="ml-248rpx">
            <text class="text-bold text-#F5531A">
              ￥
            </text>
            <text class="text-bold text-40rpx text-#F5531A">
              {{ stationDetail?.currentPrice }}
            </text>
            <text class="text-24rpx text-#AAA">
              元/度
            </text>
          </view>
          <view class="scan-qrcode" @click="scanCode">
            扫码充电
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.cardBg-set {
  background-size: cover;
  background-position: center;
}

.select-item {
  background: #f5f3f3;
  border-radius: 16rpx;
  color: #2B303A;
  text-align: center;
}

.select-item-active {
  background: #9ED605;
  box-shadow: inset 0rpx 20rpx 40rpx 2rpx rgba(100, 255, 218, 0.26);
  border-radius: 0rpx 16rpx 0rpx 16rpx;
  font-weight: bold;
  color: #FFFFFF;
}

.scan-qrcode {
  width: 220rpx;
  height: 100rpx;
  background: linear-gradient(90deg, #DBFC81 0%, #9ED605 100%);
  box-shadow: inset 0rpx 6rpx 20rpx 2rpx #FFFFFF;
  border-radius: 16rpx;
  font-weight: 800;
  font-size: 28rpx;
  line-height: 112rpx;
  text-align: center;
}
</style>
