<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.devType="'add'" type='primary' :icon='CirclePlus' @click="openDialog('add')">新增</el-button>
          <el-button v-auth.devType="'delete'" type='danger' :icon='Delete' plain :disabled='!scope.isSelected'
                     @click='batchDelete(scope.selectedListIds)'>
            删除
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation='scope'>
          <el-button v-auth.devType="'edit'" type='primary' link :icon='EditPen' :model-value='false'
                     @click="openDialog('edit', scope.row)">编辑
          </el-button>
          <el-button v-auth.devType="'delete'" type='primary' link :icon='Delete' @click='handleDelete(scope.row)'>删除
          </el-button>
        </template>
  
      </ProTable>
    </div>
    <DevTypePopup :refresh-table='proTable?.getTableList' ref='devTypePopup' />
  </template>
  
  <script setup lang='tsx' name='useRole'>
  import TimeControl from '@/components/TimeControl/index.vue'
  import { type DevType } from '@/api/device/interface/devType'
  import { useHandleData } from '@/hooks/useHandleData'
  import { useDownload } from '@/hooks/useDownload'
  import ProTable from '@/components/ProTable/index.vue'
  import { type ProTableInstance, type ColumnProps } from '@/components/ProTable/interface'
  import { CirclePlus, Delete, EditPen, Download, Upload } from '@element-plus/icons-vue'
  import { useDictStore } from '@/stores/modules/dict'
  import {
    getDevTypeList,
    deleteDevType,
  } from '@/api/device/devType/index.ts'
  import { onBeforeMount, reactive, ref } from 'vue'
  import { useModeStore, useAppSceneStore } from '@/stores/modules/mode'
import { getICDAllList } from '@/api/device/icd'
import type { ICD } from '@/api/device/interface/icd'
  
  // defineOptions({
  //   name: 'devType',
  // })
  const modeStore = useModeStore()
  const dictStore = useDictStore()
  // ProTable 实例
  const proTable = ref<ProTableInstance>()
  const devTypePopup = ref()
  const icdOptions = ref<ICD.ResICD[]>([])
  
  const getTableList = async (params: any) => {
    let newParams = JSON.parse(JSON.stringify(params))
    return getDevTypeList(newParams)
  }
  
  
  // 表格配置项
  const columns = reactive<ColumnProps<DevType.ResPqDevType>[]>([
    { type: 'selection', fixed: 'left', width: 70 },
    { type: 'index', fixed: 'left', width: 70, label: '序号' },
    {
      prop: 'name',
      label: '名称',
      search: { el: 'input' },
      minWidth: 150,
    },
    {
      prop: 'power',
      label: '工作电源',
      minWidth: 150,
    },
    {
      prop: 'devChns',
      label: '通道数',
      minWidth: 100,
    },
    {
      prop: 'devVolt',
      label: '额定电压（V）',
      minWidth: 100,
    },
    {
      prop: 'devCurr',
      label: '额定电流（A）',
      minWidth: 100,
    },
    {
      prop: 'reportName',
      label: '报告模版名称',
      minWidth: 150,
      enum: dictStore.getDictData('Report_Template'),
      fieldNames: { label: 'name', value: 'id' },
    },
    {
      prop: 'icd',
      label: '设备关联ICD',
      minWidth: 200,
      render: (scope) => {
      // 查找ICD名称
      const name = icdOptions.value.find(option => option.id === scope.row.icd)
      return <span>{name?.name}</span>
    },
    },
    {
      prop: 'createTime',
      label: '创建时间',
      width: 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 },
  ])
  
  

  // 打开 drawer(新增、编辑)
  const openDialog = (titleType: string, row: Partial<DevType.ResPqDevType> = {}) => {
    devTypePopup.value?.open(titleType, row,icdOptions.value)
  }
  
  
  // 批量删除设备类型
  const batchDelete = async (id: string[]) => {
    await useHandleData(deleteDevType, id, '删除所选设备类型')
    proTable.value?.clearSelection()
    proTable.value?.getTableList()
  }
  
  // 删除设备类型
  const handleDelete = async (params: DevType.ResPqDevType) => {
    await useHandleData(deleteDevType,  [params.id] , `删除【${params.name}】设备类型`)
    proTable.value?.getTableList()
    
  }


  onBeforeMount(async () => {
    const response = await getICDAllList({
        id: '',
        name: '',
        path: '',
        state: 1
    })
    icdOptions.value = (response.data as ICD.ResICD[]).map(item => ({
      id: item.id,
      name: item.name,
      path: item.path,
      state: item.state,
    }))
})
  
  </script>
    