<template>
    <div class='table-box' ref='popupBaseView'>
      <ProTable
          ref='proTable'
          :columns='columns'
          :request-api='getTableList'
      >
        <!-- :requestApi="getRoleList" -->
        <!-- 表格 header 按钮 -->
        <template #tableHeader='scope'>
          <el-button v-auth.device="'add'" type='primary' :icon='CirclePlus' @click="openDialog('add')">新增</el-button>
          <el-button v-auth.device="'delete'" type='danger' :icon='Delete' plain :disabled='!scope.isSelected'
                     @click='batchDelete(scope.selectedListIds)'>
            删除
          </el-button>
          <el-button v-auth.device="'export'" type='primary' :icon='Upload' plain @click='downloadFile()'>导出</el-button>
          <el-button v-auth.device="'import'" type='primary' :icon='Download' plain @click="importFile()">导入
           </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation='scope'>
          <el-button v-auth.device="'edit'" type='primary' link :icon='EditPen' :model-value='false'
                     @click="openDialog('edit', scope.row)">编辑
          </el-button>
          <el-button v-auth.device="'delete'" type='primary' link :icon='Delete' @click='handleDelete(scope.row)'>删除
          </el-button>
        </template>
  
      </ProTable>
    </div>
    <StandardDevicePopup :refresh-table='proTable?.getTableList' ref='standardDevicePopup'/>
     <ImportExcel ref='deviceImportExcel'/>
  </template>
  
  <script setup lang='tsx' name='useRole'>
  import {type StandardDevice} from '@/api/device/interface/standardDevice.ts'
  import {useHandleData} from '@/hooks/useHandleData'
  import {useDownload} from '@/hooks/useDownload'
  import ProTable from '@/components/ProTable/index.vue'
  import {type ColumnProps, type ProTableInstance} from '@/components/ProTable/interface'
  import StandardDevicePopup from '@/views/machine/standardDevice/components/standardDevicePopup.vue'
  import {CirclePlus, Delete, Download, EditPen, Upload} from '@element-plus/icons-vue'
  import {deletePqStandardDev, getPqStandardDevList,getPqStandardDevById,exportPqStandardDev,downloadTemplate,importPqStandardDev} from '@/api/device/standardDevice/index.ts'
  import {computed, onBeforeMount, reactive, ref} from 'vue'
  import { getPqDev} from '@/api/device/device/index.ts'
  import {type Device} from '@/api/device/interface/device.ts'
  import {useDictStore} from '@/stores/modules/dict'
  import { ElMessageBox } from 'element-plus'
  import ImportExcel from '@/components/ImportExcel/index.vue'
  // ProTable 实例
  const proTable = ref<ProTableInstance>()
  const standardDevicePopup = ref()
  // 存储设备类型选项
  const devTypeOptions = ref<Device.ResDev[]>([])
  const dictStore = useDictStore()


  const getTableList = async (params: any) => {
    let newParams = JSON.parse(JSON.stringify(params))

    return getPqStandardDevList(newParams)
  }
  
  // 表格配置项
  const columns = reactive<ColumnProps<StandardDevice.ResPqStandardDevice>[]>([
    {type: 'selection', fixed: 'left', width: 70},
    {type: 'index', fixed: 'left', width: 70, label: '序号'},
    {
      prop: 'name',
      label: '名称',
      search: {el: 'input'},
      minWidth: 200,
    },
    {
      prop: 'devType',
      label: '设备类型',
      enum:computed(() => {
            return devTypeOptions.value.map(item => ({
              id: item.id,
              name: item.name,
              icd: item.icd,
              power: item.power,
              devVolt: item.devVolt,
              devCurr: item.devCurr,
              devChns: item.devChns,
            }))
      }),
      search: {el: 'select', props: {filterable: true}, order: 1},
      fieldNames: {label: 'name', value: 'id'},
      render: (scope) => {
      // 查找设备类型名称
      const name = devTypeOptions.value.find(option => option.id === scope.row.devType)
      return <span>{name?.name}</span>
    },
      minWidth: 200,
    },
    {
      prop: 'inspectChannel',
      label: '可检通道',
      minWidth: 150,
      render: (scope) => {
        const codes = scope.row.inspectChannel // 获取当前行的 datasourceIds 字段
        if (!codes) {
          return '/'
        }
        // 确保 codes 是一个字符串
        const codeString = Array.isArray(codes) ? codes.join(',') : codes
        const codeArray = codeString.split(',')
        return codeArray.length > 1 ? codeArray.join(', ') : codeArray[0]
      },
    },
    {
      prop: 'ip',
      label: 'IP地址',
      minWidth: 110,
    },
    {
      prop: 'manufacturer',
      label: '设备厂家',
      enum: dictStore.getDictData('Dev_Manufacturers'),
      search: {el: 'select', props: {filterable: true}, order: 1},
      fieldNames: {label: 'name', value: 'id'},
      minWidth: 200,
    },
    {
      prop: 'createTime',
      label: '创建时间',
      minWidth: 200,
      render: scope => {
        if (scope.row.createTime) {
          const date = new Date(scope.row.createTime);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        return '';
      }
    },
    {prop: 'operation', label: '操作', fixed: 'right', width: 200},
  ])
  
  


  const formContent = reactive<StandardDevice.ResPqStandardDevice>({
      id: '',
      name: '',
      devType:'',
      manufacturer:'',
      hardwareVersion: '',
      softwareVersion: '',
      ip: '172.17.102.200',
      port: 102,
      inspectChannel:'',
      encryptionFlag: 0,
      state: 1,
    })

  // 打开 drawer(新增、编辑)
  const openDialog = async (titleType: string, row: Partial<StandardDevice.ResPqStandardDevice> = {}) => {
    if(titleType === 'add'){
       row = formContent
       standardDevicePopup.value?.open(titleType, row,devTypeOptions.value)
    }else{
      row = await getPqStandardDevById(row)
      standardDevicePopup.value?.open(titleType, row.data,devTypeOptions.value)
    }
    
  }
  
  
  // 批量删除设备
  const batchDelete = async (id: string[]) => {
    await useHandleData(deletePqStandardDev, id, '删除所选设备')
    proTable.value?.clearSelection()
    proTable.value?.getTableList()
  }
  
  // 删除设备
  const handleDelete = async (params: StandardDevice.ResPqStandardDevice) => {
    await useHandleData(deletePqStandardDev,  [params.id] , `删除【${params.name}】设备`)
    proTable.value?.getTableList()
  }



  // 导出设备
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出标准设备?', '温馨提示', {type: 'warning'}).then(() => {
    useDownload(exportPqStandardDev, '标准设备导出数据', {...proTable.value?.searchParam}, false, '.xlsx')
  })
}

//导入设备
const deviceImportExcel = ref<InstanceType<typeof ImportExcel> | null>(null)

const importFile = async () => {
    const params = {
      title: '标准设备',
      showCover: false,
      tempApi: downloadTemplate,
      importApi: importPqStandardDev,
      getTableList: proTable.value?.getTableList,
    }
    deviceImportExcel.value?.acceptParams(params)
}
  

  onBeforeMount(async () => {
   const response = await getPqDev()
    devTypeOptions.value = (response.data as Device.ResDev[]).map(item => ({
    id: item.id,
    name: item.name,
    icd: item.icd,
    power: item.power,
    devVolt: item.devVolt,
    devCurr: item.devCurr,
    devChns: item.devChns,
  }))

})

  </script>
    