<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="SN" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入SN"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="持有人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入持有人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-cascader
          class="!w-240px"
          v-model="queryParams.deptId"
          :options="deptList"
          :props="{
            checkStrictly: true,
            label: 'name',
            value: 'id',
            children: 'children',
            emitPath: false
          }"
          clearable
        />
      </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="['gas:hand-detector:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['gas:hand-detector:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['gas:hand-detector: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="SN" align="center" prop="sn" min-width="150px" />
      <el-table-column label="持有人" align="center" prop="name" />
      <el-table-column label="应用围栏" align="center" prop="fenceIds">
        <template #default="scope">
          {{
            scope.row.fenceIdsArray &&
            scope.row.fenceIdsArray.length > 0 &&
            scope.row.fenceIdsArray
              .map((item) => handDetectorStore.getFences.find((fence) => fence.id == item)?.name)
              .join('、')
          }}
        </template>
      </el-table-column>
      <!-- 围栏类型 -->
      <el-table-column label="围栏类型" align="center" prop="fenceType">
        <template #default="scope">
          <DictTag
            :type="DICT_TYPE.HAND_DETECTOR_FENCE_TYPE"
            :value="scope.row.fenceType"
            v-if="scope.row.fenceType"
          />
        </template>
      </el-table-column>
      <el-table-column label="气体类型" align="center" prop="gasTypeId">
        <template #default="scope">
          {{ handDetectorStore.getGasTypes.find((item) => item.id === scope.row.gasTypeId)?.name }}
        </template>
      </el-table-column>
      <!-- 部门 -->
      <el-table-column label="部门" align="center" prop="deptId">
        <template #default="scope">
          <span v-if="scope.row.deptId">
            {{ deptList.find((dept) => dept.id === scope.row.deptId)?.name || '-' }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="enableStatus">
        <template #default="scope">
          <DictTag :type="DICT_TYPE.HAND_DETECTOR_ENABLE_STATUS" :value="scope.row.enableStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="160px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['gas:hand-detector:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['gas:hand-detector: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>

  <!-- 表单弹窗：添加/修改 -->
  <HandDetectorForm ref="formRef" @success="getList" :fences="fences" :gasTypes="gasTypes" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import download from '@/utils/download'
import { HandDetectorApi, HandDetector } from '@/api/gas/handdetector'
import { DeptVO, getSimpleDeptList } from '@/api/system/dept'

import HandDetectorForm from './HandDetectorForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { Fence } from '@/api/gas/fence'
import type { Type } from '@/api/gas/gastype'
import { useHandDetectorStore } from '@/store/modules/handDetector'
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
/** GAS手持探测器 列表 */
defineOptions({ name: 'HandDetector' })
const handDetectorStore = useHandDetectorStore()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<HandDetector[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  sn: undefined,
  name: undefined,
  deptId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const fences = ref<Fence[]>([])
const gasTypes = ref<Type[]>([])
const deptList = ref<DeptVO[]>([]) // 部门列表
function getDeptList() {
  getSimpleDeptList().then((res) => {
    deptList.value = handleTree(res || [])
  })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await HandDetectorApi.getHandDetectorPage(queryParams)
    data.list.forEach((item: HandDetector) => {
      item.fenceIds && (item.fenceIdsArray = item.fenceIds.split(','))
    })
    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) => {
  if (fences.value.length === 0) {
    getAllFences()
  }
  if (gasTypes.value.length === 0) {
    getAllGasTypes()
  }
  formRef.value.open(type, id)
}

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

/** 批量删除GAS手持探测器 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await HandDetectorApi.deleteHandDetectorList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await HandDetectorApi.exportHandDetector(queryParams)
    download.excel(data, '手持探测器.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const getAllFences = async () => {
  fences.value = await handDetectorStore.getAllFences()
}

const getAllGasTypes = async () => {
  gasTypes.value = await handDetectorStore.getAllGasTypes()
}
/** 初始化 **/
onMounted(() => {
  getList()
  getAllFences()
  getAllGasTypes()
  getDeptList()
})
</script>
