<script setup lang="ts">
import { clientGet } from '@/utils/request.ts'
import type { BaseResponse } from '@/utils/type.ts'
import { ref } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import { useDebounceFn } from '@vueuse/core'

interface StatusParams {
  cmd: number,
  lightNums: string,
  packageId: string
}

interface StatusResponse extends BaseResponse {
  data: string
}

interface LightData {
  light_num: string;       // 灯编号
  brightness: number | boolean;      // 亮度
  voltage: number;         // 电压
  current: number;         // 电流
  power: number;           // 功率
  power_quantity: number;  // 电量
  onlineStatus: number;    // 在线状态
}

const cardDatas = ref<LightData[]>([]);
const linkDialogVisible = ref(false);
// const downloadUrl = ref('public/LedOK Express.rar');

const orignalParams = [
  {
    cmd: 6012,
    lightNums: '40005289',
    packageId: '1050'
  },
  {
    cmd: 6012,
    lightNums: '40005272',
    packageId: '1050'
  },
  {
    cmd: 6012,
    lightNums: '40005274',
    packageId: '1050'
  },
  {
    cmd: 6012,
    lightNums: '40005281',
    packageId: '1050'
  }
]
const getData = async () => {
  let process = 0
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载数据' + process + '/' + orignalParams.length,
    background: 'rgba(200, 200, 200, .8)'
  })
  const list = []
  try {
    for (let i = 0; i < orignalParams.length; i++) {
      const res = await clientGet<StatusParams, StatusResponse>('/pole/instruct/issued/equipmentStatus', {
        params: orignalParams[i]
      })
      list.push(res)
      process = i + 1
      loading.setText('正在加载数据' + process + '/' + orignalParams.length)
    }

    const resList: LightData[] = list.map(res => {
      return JSON.parse(JSON.parse(res.data).params)
    })
    cardDatas.value = resList.flat(-1 >>> 1).map(item => {
      item.brightness = item.brightness != 0
      return item
    })
  } catch (error) {
    console.error('数据获取失败:', error)
  } finally {
    loading.close()
  }
}
const changeLight = useDebounceFn(async (light: LightData) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在操作灯杆' + light.light_num,
    background: 'rgba(200, 200, 200, .8)'
  })
  if (typeof light.brightness === 'number') {
    ElMessage.warning('出现了错误')
    return
  }
  try {
    const newBrightness = light.brightness ? 0 : 100
    await clientGet('/pole/instruct/issued/reportEnvironmentalData', {
      params: {
        cmd: 6011,
        lightNums: light.light_num,
        packageId: '1050',
        brightness: newBrightness
      }
    })
    const qq = await getSingleLightStatus({
      cmd: 6012,
      lightNums: light.light_num,
      packageId: '1050'
    })
    if(qq == null){
      ElMessage.error('获取状态失败，请重试')
      return
    }
    qq.brightness = qq.brightness != 0
    const updatedLightIndex = cardDatas.value.findIndex(card => card.light_num === light.light_num)
    if (updatedLightIndex !== -1) {
      cardDatas.value[updatedLightIndex] = (qq as LightData);
    }
    ElMessage.success(light.brightness ? '关灯' : '开灯')
  } catch (error) {
    console.error('开灯/关灯失败:', error)
    ElMessage.error('操作失败，请重试')
  }finally {
    loading.close()
  }
},500);
const getSingleLightStatus = async (params: StatusParams): Promise<LightData | null> => {
  try {
    const res = await clientGet<StatusParams, StatusResponse>('/pole/instruct/issued/equipmentStatus', {
      params: params
    });
    const parsedData = JSON.parse(JSON.parse(res.data).params);
    return parsedData[0];
  } catch (error) {
    console.error('获取单个灯杆状态失败:', error);
    ElMessage.error('获取状态失败，请重试');
    return null;
  }
};
const updateCurrentData = async (light:LightData)=>{
  const loading = ElLoading.service({
    lock: true,
    text: '正在获取当前灯杆数据',
    background: 'rgba(200, 200, 200, .8)'
  })
  const res = await getSingleLightStatus({cmd:6012,lightNums:light.light_num,packageId:'1050'})
  if(!res){
    ElMessage.error('获取状态失败，请重试')
    return
  }
  res.brightness = res.brightness != 0
  const updatedLightIndex = cardDatas.value.findIndex(card => card.light_num === light.light_num);
  if (updatedLightIndex !== -1) {
    cardDatas.value[updatedLightIndex] = res as LightData;
  }
  loading.close()
}
const toOtherLink = (linkStr:'一键报警'|'灯杆显示屏')=>{
  switch (linkStr){
    case '一键报警':
      window.open('https://172.16.102.27:8088/')
      break;
    case '灯杆显示屏':
      linkDialogVisible.value = true
      break;
  }
}
const init = () => {
  getData()
}
init()

</script>

<template>
  <div>
    <el-row :gutter="30" class="p-30px">
      <el-col :span="24">
        <el-row>
          <el-col :span="6">
            <el-button type="primary" @click="init">获取最新数据</el-button>
          </el-col>
          <el-col :span="4" :offset="14">
            <el-button type="info" @click="toOtherLink('一键报警')">一键报警</el-button>
            <el-button type="warning" @click="toOtherLink('灯杆显示屏')">灯杆显示屏</el-button>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="12" sm="24" v-for="(item,index) in cardDatas" :key="index" class="my-4">
        <el-card>
          <template #header>
            <div class="flex gap-1 justify-between px-3">
              <div class="flex gap-1">
                <div class="w-20px h-20px">
                  <img class="w-full h-full" src="/src/assets/svg/灯杆.svg"  alt="灯杆"/>
                </div>
                <div>灯杆信息</div>
              </div>
              <div>
                <el-button @click="updateCurrentData(item)">更新当前灯杆数据</el-button>
              </div>
            </div>
          </template>
          <template #default>
            <el-descriptions :title="'灯杆编号'+item.light_num" :column="2" border>
              <el-descriptions-item
                label="电压"
                label-align="right"
                align="center"
              >
                {{ item.voltage.toFixed(2) + 'V' }}
              </el-descriptions-item>
              <el-descriptions-item label="电流" label-align="right" align="center">
                {{ item.current.toFixed(2) + 'A' }}
              </el-descriptions-item>
              <el-descriptions-item label="功率" label-align="right" align="center">
                {{ item.power.toFixed(3) + 'kW' }}
              </el-descriptions-item>
              <el-descriptions-item label="电量" label-align="right" align="center">
                {{ item.power_quantity.toFixed(2) + '度' }}
              </el-descriptions-item>
              <el-descriptions-item label="在线状态" label-align="right" align="center">
                <el-tag :type="item.onlineStatus==1?'success':'danger'">
                  <span v-if="item.onlineStatus==1">在线</span>
                  <span v-else>离线</span>
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="开关" label-align="right" align="center" class-name="flex gap-20px">
                <el-text>当前
                  <el-tag :type="item.brightness?'success':'danger'">{{ item.brightness ? '开' : '关' }}</el-tag>
                </el-text>
                <el-button :type="item.brightness?'info':'primary'" @click="changeLight(item)">
                  {{ item.brightness ? '关闭' : '打开' }}
                </el-button>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="linkDialogVisible" title="请下载大屏显示器软件">
      <template #default>
        <div class="flex flex-col gap-10px">
          <div>
            <a :href="'/LedOK Express.rar'" download="LedOK_Express.rar">下载大屏显示器软件</a>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="linkDialogVisible=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
