<template>
  <div class="text-right mb-5">
    <el-button type="primary" @click="applyComunications" icon="pointer"> 应用 </el-button>
    <el-button type="primary" @click="copy" icon="CopyDocument">复制配置</el-button>
    <el-button type="primary" @click="addDevice" icon="plus">添加通信参数</el-button>
  </div>
  <div class="demo-collapse">
    <el-collapse>
      <el-collapse-item class="" v-for="(device_info_list, station_id) in device_infos">
        <template #title>
          <span class="text-2xl font-bold"> {{ station_id }} </span>
        </template>
        <div class="deviceCard">
          <device-info-card
              @deleteDeviceInfo="deleteDeviceInfo"
              v-for="device_info in device_info_list"
              :device-info="device_info"
              :tab-type="props.tabType"
          />
        </div>

      </el-collapse-item>
    </el-collapse>
  </div>

  <edit-dialog 
    :is-show="isShow" 
    :tab-type="props.tabType"
    @close="isShow = false" 
    @change-device-info="changeDeviceInfo"
    type="add" />
</template>

<script setup lang="ts">
import axios from 'axios';
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import useClipboard from 'vue-clipboard3'

import DeviceInfoCard from '@/components/device_communication/DeviceInfoCard'
import type { DeviceInfo } from '@/components/device_communication/types'
import EditDialog from '@/components/device_communication/EditDialog';

type propType = {
  tabType: string
}
const props = defineProps<propType>()
// device info card 相关
const device_infos = ref<Record<string, DeviceInfo[]>>({})
// 获取当前选择的页面
onMounted(() => {
  axios.get('/api/device_communication/' + props.tabType + '/')
    .then(res => {
      // console.log(res.data);
      // 将数据按照不同的 station_id 分组
      for (let i = 0; i < res.data.length; i++) {
        if (device_infos.value[res.data[i].station_id] !== undefined) {
          device_infos.value[res.data[i].station_id].push(res.data[i])
        } else {
          device_infos.value[res.data[i].station_id] = [res.data[i]]
        }
      }
    })
    .catch(err => {
      console.log(err);
    })
})

type param = {
  station_id: string
  id: number
}
const deleteDeviceInfo = (params: param) => {
  for (let i = 0; i < device_infos.value[params.station_id].length; i++) {
    if ((device_infos.value[params.station_id])[i].id === params.id) {
      // 如果 station_id 对应的设备列表为空,则删除 station_id
      if (device_infos.value[params.station_id].length === 1) {
        delete device_infos.value[params.station_id]
        return
      }

      // 删除
      device_infos.value[params.station_id].splice(i, 1)
    }
  }
}

const isShow = ref(false)
const addDevice = () => {
  isShow.value = true
}

const changeDeviceInfo = (params: DeviceInfo) => {
  console.log('changeDeviceInfo')
  console.log(params);

  if (device_infos.value[params.station_id] === undefined) {
    device_infos.value[params.station_id] = [params]
  } else {
    device_infos.value[params.station_id].push(params)
  }
}

// clipboard 赋值到设备信息到 ini 文件中
const { toClipboard } = useClipboard()
const copy = async () => {
  let configText = composeConfigText()
  try {
    await toClipboard(configText)
    ElMessage({
      message: '复制成功',
      type: 'success',
    })
  } catch (error) {
    console.log(error);
  }
}

// 生成和 ini 文件中类似的配置格式
function composeConfigText(): string {
  let configText = ''
  for (const [station_level, device_info_list] of Object.entries(device_infos.value)) {
    configText += `[Device_info_${station_level}]\n`
    configText += `dev_num=${device_info_list.length}\n`
    for (let i = 1; i <= device_info_list.length; i++) {
      configText += `dev${i}_id=${device_info_list[i - 1].device_id}\n`
      configText += `dev${i}_name=${device_info_list[i - 1].device_name}\n`
      configText += `dev${i}_name_chn=${device_info_list[i - 1].device_name_chn}\n`
      configText += `dev${i}_datacatlog=${device_info_list[i - 1].protocol_name}\n`
    }
  }
  return configText
}

// 应用设备通信参数
const applyComunications = () => {
  console.log('applyComunications')
  axios.post('/api/device_communication/set_communication_to_devinfo_table/', {
    type: props.tabType
  })
  .then((res) => {
    console.log(res.data);
    ElMessage({
      message: '应用成功',
      type: 'success'
    })
  })
  .catch((err) => {
    console.log(err);
    ElMessage({
      message: '应用失败',
      type: 'error'
    })
  })
}
</script>

<style>
.deviceCard{

  width: 90%;
  margin: auto;
}
</style>
