<!-- 设备列表 -->
<script name="DeviceListEmbedded" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IDictType } from '../common-interface'
import type { IDeviceInfo, IListQuery } from './device-info'
import AddDeviceDialog from './addDeviceDialog.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import { exportExcel } from '@/utils/exportXlsx'
import { delDevice, delDeviceBatch, exportDevice, getDeviceListPage, batchImportDevice } from '@/api/basic/device'
import axios from 'axios'
const props = defineProps({
  groupId: {
    type: String,
    required: true,
  },
})

const { proxy } = getCurrentInstance() as any
const router = useRouter()

// 对象引用
const refAddDeviceDialog = ref()

// 查询条件
const searchQuery = ref<IListQuery>({
  groupId: props.groupId, // 分组
  devcode: '',
  imei: '',
  deviceType: '',
  offset: 1,
  limit: 10,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '设备编号', value: 'devcode', align: 'center', width: '160' },
  { text: '所属产品', value: 'productName', align: 'center' },
  { text: '设备类型', value: 'deviceTypeName', align: 'center', width: '200' },
  { text: '设备型号', value: 'model', align: 'center', width: '200' },
  { text: 'IMEI', value: 'imei', align: 'center', width: '160' },
  { text: '加密方式', value: 'encipherTypeName', align: 'center', width: '200' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
  { text: '创建人', value: 'createUserName', align: 'center', width: '120' },
])
const dataList = ref<Array<IDeviceInfo>>([]) // 表格数据

const deviceTypeDict = ref<Array<IDictType>>([])

const recordSelected = ref<IDeviceInfo[]>([])

// 逻辑
// 导出所有
const exportAllDevice = () => {
  if (dataList.value.length > 0) {
    const loading = ElLoading.service({
      lock: true,
      text: '下载中请稍后',
      background: 'rgba(255, 255, 255, 0.8)',
    })
    getDeviceListPage({ ...searchQuery.value, offset: 1, limit: 9999 }).then(res => {
      exportExcel({
        json: res.data.rows.map((item: any, index: number) => ({
          '1index': index + 1,
          '2devcode': item.devcode,
          '3productName': item.productName,
          '4deviceTypeName': item.deviceTypeName,
          '5model': item.model,
          '6imei': item.imei,
          '7encipherTypeName': item.encipherTypeName,
          '8createTime': item.createTime,
          '9createUserName': item.createUserName,
        })),
        titleArr: ['序号', '设备编号', '所属产品', '设备类型', '设备型号', 'IMEI', '加密方式', '创建时间', '创建人'],
        name: `设备列表_${new Date().valueOf()}`,
        sheetName: 'sheet1',
      })
      loading.close()
    }).catch(() => {
      loading.close()
    })

    // 导出接口
    // exportDevice(searchQuery.value).then((res) => {
    //   const blob = new Blob([res.data])
    //   exportFile(blob, filename)

    //   nextTick(() => {
    //     // 关闭loading
    //     loading.close()
    //   })
    // }).catch(() => {
    //   loading.close()
    // })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
}

// 详情
const detail = (row: IDeviceInfo) => {
  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: '/basic/device/detail',
  })
}

// 编辑
const updateById = (row: IDeviceInfo) => {
  sessionStorage.setItem('deviceInfo', JSON.stringify(row))
  refAddDeviceDialog.value.initDialog({ type: 'update', id: row.id })
}

// 新增
const addDevice = () => {
  refAddDeviceDialog.value.initDialog({ type: 'create', groupId: props.groupId })
}
// 上传逻辑
const fileRef = ref()
const onFileChange = (event: any) => {
  // 原生上传
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    batchImportDevice(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('上传成功')
        loading.close()
        fileRef.value.value = ''
        fetchData(true)
      }
      else {
        // ElMessage.error(res.message)
        fileRef.value.value = ''
        loading.close()
      }
    }).catch(() => {
      // ElMessage.error(err.message)
      fileRef.value.value = ''
      loading.close()
    })
  }
}
// 导入文件批量新增
const batchAddDevice = () => {
  fileRef.value.click()
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getDeviceListPage(searchQuery.value).then((response) => {
    if (response.code === 200) {
      dataList.value = response.data.rows.map((item: IDeviceInfo) => {
        return {
          ...item,
        }
      })
      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

const searchList = () => {
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 删除
const deleteDeviceById = (row: IDeviceInfo) => {
  ElMessageBox.confirm(`是否删除设备 ${row.devcode}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delDevice(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`设备 ${row.devcode} 删除成功`)
        searchList()
      }
      else {
        ElMessage.error(`设备 ${row.devcode} 删除失败: ${res.message}`)
      }
    })
  })
}
// 模板下载
const downTemplate = () => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  axios.get('./file/device_template.xlsx', {
    responseType: 'blob', // 关键配置
  }).then(res => {
    // console.log(res, '111')
    const blob = new Blob([res.data])
    loading.close()
    exportFile(blob, 'device_template.xlsx')
  }).catch(() => {
    loading.close()
  })
}
// 批量删除设备
const batchDeleteDevice = () => {
  if (recordSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

  ElMessageBox.confirm(`是否批量删除设备 ${recordSelected.value.length} 台`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = recordSelected.value.map((item: IDeviceInfo) => {
      return item.id
    })
    delDeviceBatch(ids).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`${recordSelected.value.length} 台设备删除成功`)
        searchList()
      }
      else {
        ElMessage.error(`${recordSelected.value.length} 台设备删除失败: ${res.message}`)
      }
    })
  })
}

const recordMultiSelect = (e: any) => {
  recordSelected.value = e
}

const deviceSavedHandler = () => {
  fetchData(true)
}

// 获取在用状态字典值
const getDeviceTypeDict = async () => {
  getDictByCode('deviceType').then((res: any) => {
    if (res.code === 200) {
      deviceTypeDict.value = res.data
      sessionStorage.setItem('deviceType', JSON.stringify(res.data))
    }
  })
}
// 获取加密方式字典值
const getEncipherTypeDict = async () => {
  getDictByCode('encipherType').then((res: any) => {
    if (res.code === 200) {
      sessionStorage.setItem('encipherType', JSON.stringify(res.data))
    }
  })
}

const getDict = async () => {
  await getDeviceTypeDict()
  await getEncipherTypeDict()
}

onMounted(async () => {
  await getDict()
  searchList()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="false" @search="searchList">
      <search-item>
        <el-input v-model="searchQuery.devcode" placeholder="设备编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.imei" placeholder="设备IMEI号" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.deviceType" placeholder="设备类型" clearable style="width: 192px;">
          <el-option v-for="dict in deviceTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
        </el-select>
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container title="设备列表">
      <!-- 表头区域 -->
      <template #btns-right>
        <el-button v-if="proxy.hasPerm(`/basic/device/add`)" type="primary" @click="addDevice">
          新增
        </el-button>
        <el-button  type="primary" @click="batchAddDevice">
          导入
        </el-button>

        <el-button type="primary" @click="exportAllDevice">
          导出
        </el-button>
        <el-button type="primary" @click="downTemplate">
          模板下载
        </el-button>
        <el-button v-if="proxy.hasPerm(`/basic/device/del`)" type="danger" @click="batchDeleteDevice">
          批量删除
        </el-button>
        <!-- 导入上传组件 -->
        <input ref="fileRef" style="display: none;" type="file" accept=".xls,.xlsx" @change="onFileChange">
      </template>

      <!-- 表格区域 -->
      <normal-table :data="dataList" :columns="columns" :total="total"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }" :list-loading="loadingTable"
        :is-showmulti-select="true" :is-multi="true" @change="changePage" @multi-select="recordMultiSelect">
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset! - 1) * searchQuery.limit! + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>

        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm(`/basic/device/edit`)" size="small" type="primary" link
                @click="updateById(row)">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm(`/basic/device/del`)" size="small" type="danger" link
                @click="deleteDeviceById(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>

    <add-device-dialog ref="refAddDeviceDialog" @record-saved="deviceSavedHandler" />
  </app-container>
</template>
