<template>
  <div class="app-container">
    <div class="flex">
      <!-- 左侧树形结构区域 -->
      <div class="w-250px mr-16px bg-white p-16px rounded-8px shadow-sm">
        <el-tabs v-model="activeTab">
          <!-- 部门选项卡 -->
          <el-tab-pane label="部门" name="dept">
            <el-input
              v-model="deptFilterText"
              placeholder="输入部门名称过滤"
              clearable
              class="mb-10px"
            />
            <el-tree
              ref="deptTreeRef"
              :data="deptTree"
              :props="defaultProps"
              node-key="id"
              highlight-current
              default-expand-all
              :expand-on-click-node="false"
              :filter-node-method="filterDeptNode"
              @node-click="handleDeptNodeClick"
            />
          </el-tab-pane>

          <!-- 位置选项卡 -->
          <el-tab-pane label="位置" name="location">
            <el-input
              v-model="locationFilterText"
              placeholder="输入位置名称过滤"
              clearable
              class="mb-10px"
            />
            <el-tree
              ref="locationTreeRef"
              :data="locationTree"
              :props="{ ...defaultProps, label: 'locationName' }"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              :filter-node-method="filterLocationNode"
              @node-click="handleLocationNodeClick"
            />
          </el-tab-pane>

          <!-- 类别选项卡 -->
          <el-tab-pane label="类别" name="category">
            <el-input
              v-model="categoryFilterText"
              placeholder="输入类别名称过滤"
              clearable
              class="mb-10px"
            />
            <el-tree
              ref="categoryTreeRef"
              :data="categoryTree"
              :props="{ ...defaultProps, label: 'categoryName' }"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              :filter-node-method="filterCategoryNode"
              @node-click="handleCategoryNodeClick"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 右侧内容区域 -->
      <div class="flex-1" style="width: 600px">
        <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="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-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">
              <template #default="scope">
                <el-link type="primary" @click="openForm(scope.row.id)">
                  {{ scope.row.deviceNumber }}
                </el-link>
              </template>
            </el-table-column>

            <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="120px" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="openForm(scope.row.id)"> 详情 </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" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getStrDictOptions, getBoolDictOptions, 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, CategoryVO } from '@/api/device/category'
import { LocationApi, LocationVO } from '@/api/device/location'
import * as DeptApi from '@/api/system/dept'
import InfoForm from './InfoForm.vue'
import { defaultProps, handleTree } from '@/utils/tree'

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

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

const loading = ref(true) // 列表的加载中
const list = ref<Info[]>([]) // 列表的数据
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 activeTab = ref('dept') // 当前激活的选项卡
const deptTree = ref<any[]>([]) // 部门树
const locationTree = ref<any[]>([]) // 位置树
const categoryTree = ref<any[]>([]) // 类别树
const deptFilterText = ref('') // 部门过滤文本
const locationFilterText = ref('') // 位置过滤文本
const categoryFilterText = ref('') // 类别过滤文本
const deptTreeRef = ref() // 部门树引用
const locationTreeRef = ref() // 位置树引用
const categoryTreeRef = 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()
  // 重置树形选择
  deptTreeRef.value.setCurrentKey(null)
  locationTreeRef.value.setCurrentKey(null)
  categoryTreeRef.value.setCurrentKey(null)
  // 重置查询参数
  queryParams.deviceDept = undefined
  queryParams.usageLocation = undefined
  queryParams.deviceCategoryId = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id?: number) => {
  formRef.value.open(id)
}

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

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

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Info[]) => {
  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
  }
}

/** 部门树节点点击事件 */
const handleDeptNodeClick = (data: any) => {
  if (data.id === 0) {
    queryParams.deviceDept = undefined
  } else {
    queryParams.deviceDept = data.id
  }
  handleQuery()
}

/** 位置树节点点击事件 */
const handleLocationNodeClick = (data: any) => {
  if (data.id === 0) {
    queryParams.usageLocation = undefined
  } else {
    queryParams.usageLocation = data.id
  }
  handleQuery()
}

/** 类别树节点点击事件 */
const handleCategoryNodeClick = (data: any) => {
  if (data.id === 0) {
    queryParams.deviceCategoryId = undefined
  } else {
    queryParams.deviceCategoryId = data.id
  }
  handleQuery()
}

/** 部门树过滤方法 */
const filterDeptNode = (value: string, data: any) => {
  if (!value) return true
  return data.deptName.includes(value)
}

/** 位置树过滤方法 */
const filterLocationNode = (value: string, data: any) => {
  if (!value) return true
  return data.locationName.includes(value)
}

/** 类别树过滤方法 */
const filterCategoryNode = (value: string, data: any) => {
  if (!value) return true
  return data.categoryName.includes(value)
}

// 监听过滤文本变化
watch(deptFilterText, (val) => {
  deptTreeRef.value.filter(val)
})
watch(locationFilterText, (val) => {
  locationTreeRef.value.filter(val)
})
watch(categoryFilterText, (val) => {
  categoryTreeRef.value.filter(val)
})

/** 初始化 **/
onMounted(() => {
  getList()
  getDeptTree()
  getLocationTree()
  getCategoryTree()
})

/** 获得部门树 */
const getDeptTree = async () => {
  const data = await DeptApi.getSimpleDeptCompanyList()
  deptTree.value = handleTree(data, 'id', 'parentId')
}

/** 获得位置树 */
const getLocationTree = async () => {
  const data = await LocationApi.getLocationList()
  locationTree.value = handleTree(data, 'id', 'parentId')
}

/** 获得类别树 */
const getCategoryTree = async () => {
  const data = await CategoryApi.getCategoryList()
  categoryTree.value = handleTree(data, 'id', 'parentId')
}
</script>

<style scoped></style>
