<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备编码" prop="deviceNumber">
        <el-input
          v-model="queryParams.deviceNumber"
          placeholder="请输入设备编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!--      <el-form-item label="资产编号" prop="assetNumber">
        <el-input
          v-model="queryParams.assetNumber"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="序列号" prop="serialNumber">
        <el-input
          v-model="queryParams.serialNumber"
          placeholder="请输入序列号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>-->
      <el-form-item label="设备分类" prop="deviceCategoryId">
        <el-tree-select
          v-model="queryParams.deviceCategoryId"
          :data="categoryTree"
          :props="{ ...defaultProps, label: 'categoryName' }"
          check-strictly
          placeholder="请选择类别"
          clearable
          filterable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备位置" prop="usageLocation">
        <el-tree-select
          v-model="queryParams.usageLocation"
          :data="locationTree"
          :props="{ ...defaultProps, label: 'locationName' }"
          check-strictly
          placeholder="请选择位置"
          clearable
          filterable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select
          v-model="queryParams.deviceStatus"
          placeholder="请选择设备状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DEVICE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="使用状态" prop="usageStatus">
        <el-select
          v-model="queryParams.usageStatus"
          placeholder="请选择使用状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.USAGE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['device:info:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['device:info:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['device:info:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="图片" align="center" prop="deviceCover" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.deviceCover"
            class="image"
            :preview-src-list="[scope.row.deviceCover]"
            preview-teleported
            :src="scope.row.deviceCover"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备编码" align="center" prop="deviceNumber" width="120" />
      <el-table-column label="设备名称" align="center" prop="deviceName" width="120" />
      <el-table-column label="资产编号" align="center" prop="assetNumber" width="120" />
      <el-table-column label="序列号" align="center" prop="serialNumber" width="120" />
      <el-table-column label="类别" align="center" prop="deviceCategoryName" width="120" />
      <el-table-column
        label="设备状态"
        align="center"
        prop="deviceStatus"
        width="100"
        fixed="right"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DEVICE_STATUS" :value="scope.row.deviceStatus" />
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="usageStatus" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.USAGE_STATUS" :value="scope.row.usageStatus" />
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="responsibleName" width="100" />
      <el-table-column label="品牌" align="center" prop="brand" width="100" />
      <el-table-column label="规格型号" align="center" prop="specificationModel" width="100" />
      <el-table-column label="设备等级" align="center" prop="deviceLevel" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DEVICE_LEVEL" :value="scope.row.deviceLevel" />
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="deviceDeptName" width="100" />
      <el-table-column label="功能位置" align="center" prop="usageLocationName" width="100" />
      <el-table-column label="单位" align="center" prop="unit" width="100" />
      <el-table-column label="供应商" align="center" prop="supplierName" width="100" />
      <el-table-column label="购置日期" align="center" prop="purchaseDate" width="100" />
      <el-table-column label="采购金额" align="center" prop="purchaseAmount" width="100" />
      <el-table-column label="保修期至" align="center" prop="warrantyPeriod" width="100" />
      <el-table-column label="启用日期" align="center" prop="commissioningDate" width="100" />
      <el-table-column label="预计报废日期" align="center" prop="scrapDate" min-width="120px" />
      <el-table-column label="设备来源" align="center" prop="deviceSource" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DEVICE_SOURCE" :value="scope.row.deviceSource" />
        </template>
      </el-table-column>
      <el-table-column label="计量设备" align="center" prop="measurementFlag" width="100">
        <template #default="scope">
          <span v-if="scope.row.measurementNumber">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="计量编号" align="center" prop="measurementNumber" width="100" />
      <el-table-column
        label="电子标签码"
        align="center"
        prop="electronicTagCode"
        min-width="120px"
      />
      <el-table-column label="入账方式" align="center" prop="accountingMethod" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ACCOUNTING_METHOD" :value="scope.row.accountingMethod" />
        </template>
      </el-table-column>
      <el-table-column label="生产编号" align="center" prop="productionNumber" width="100" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="技术参数" align="center" prop="technicalParameters" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="100" />
      <el-table-column label="操作" align="center" min-width="170px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="getQr(scope.row)" v-hasPermi="['device:info:qr']">
            二维码
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['device:info:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['device:info:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InfoForm ref="formRef" @success="getList" />
  <QrDialog ref="qrDialogRef" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InfoApi, InfoVO } from '@/api/device/info'
import { CategoryApi } from '@/api/device/category'
import { LocationApi } from '@/api/device/location'
import InfoForm from './InfoForm.vue'
import QrDialog from './components/QrDialog.vue'
import { defaultProps, handleTree } from '@/utils/tree'

/** 设备基本信息 列表 */
defineOptions({ name: 'DeviceInfo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<InfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceNumber: undefined,
  deviceName: undefined,
  assetNumber: undefined,
  serialNumber: undefined,
  deviceCategoryId: undefined,
  deviceStatus: undefined,
  deviceSpecial: undefined,
  usageStatus: undefined,
  brand: undefined,
  model: undefined,
  deviceLevel: undefined,
  deviceDept: undefined,
  usageLocation: undefined,
  supplierCode: undefined,
  supplierName: undefined,
  productionNumber: undefined,
  deviceType: undefined,
  deviceSource: undefined,
  purchaseDate: [],
  purchaseAmount: undefined,
  commissioningDate: [],
  warrantyPeriod: undefined,
  scrapDate: [],
  technicalParameters: undefined,
  unit: undefined,
  power: undefined,
  weight: undefined,
  volume: undefined,
  temperature: undefined,
  humidity: undefined,
  specificationModel: undefined,
  accountingMethod: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const categoryTree = ref() // 树形结构
const locationTree = ref() // 树形结构

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InfoApi.getInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
const qrDialogRef = ref()
const getQr = (item) => {
  const fileName = `设备_${item.deviceName}_${item.deviceNumber}`
  qrDialogRef.value.open(item.id, fileName)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InfoApi.deleteInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除设备基本信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await InfoApi.deleteInfo(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: InfoVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InfoApi.exportInfo(queryParams)
    download.excel(data, '设备基本信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()

  getCategoryTree()
  getLocationTree()
})

/** 获得设备类别树 */
const getCategoryTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.getCategoryList('')
  categoryTree.value = handleTree(data, 'id', 'parentId')
}
/** 获得设备类别树 */
const getLocationTree = async () => {
  locationTree.value = []
  const data = await LocationApi.getLocationList('')
  locationTree.value = handleTree(data, 'id', 'parentId')
}
</script>
