<template>
  <Dialog v-model="dialogVisible" title="选择巡检项" style="width: 1300px; min-height: 80%">
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="巡检项" prop="item">
          <el-input
            v-model="queryParams.item"
            placeholder="请输入巡检项"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </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-240px"
          />
        </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 @click="handleConfirm" type="danger"
            ><Icon icon="ep:check" class="mr-5px" /> 确认选择</el-button
          >
          <el-button @click="toggleAll" type="primary"
            ><Icon icon="ep:refresh" class="mr-5px" />全选</el-button
          >
          <el-button @click="invertSelection" type="info"
            ><Icon icon="ep:refresh" class="mr-5px" />取消全选</el-button
          >
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @row-click="handleRowClick"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <!--        <el-table-column width="60" label="选择" type="selection" :reserve-selection="true">-->
        <!--          <template #default="{ row }">-->
        <!--            <el-checkbox-->
        <!--              :model-value="selectedRows.some(item => item.id === row.id)"-->
        <!--              @click.stop="toggleRow(row)"-->
        <!--              class="no-label-radio"-->
        <!--            />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          type="selection"
          :reserve-selection="true"
          :selectable="(row) => !row.disabled"
        />
        <el-table-column label="巡检项" align="center" prop="item" />
        <el-table-column label="巡检标准" align="center" prop="standard" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </Dialog>
</template>

<script setup lang="ts">
import { IotDeviceVO } from '@/api/pms/device'
import { dateFormatter } from '@/utils/formatTime'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { IotInspectItemApi, IotInspectItemVO } from '@/api/pms/inspect/item'

const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<IotDeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  item: undefined,
  deptId: undefined,
  deviceClassify: undefined,
  deviceId: undefined,
  createTime: undefined,
})
const toggleAll = () => {
  list.value.forEach((row) => {
    tableRef.value.toggleRowSelection(row, true)
  })
}
const handleSelectionChange = (val) => {
  selectedRows.value = val
}
const invertSelection = () => {
  selectedRows.value.forEach((row) => {
    tableRef.value.toggleRowSelection(row, false)
    selectedRows.value.splice(row)
  })
}
const selectedRows = ref<IotInspectItemVO[]>([]) // 多选数据（存储所有选中行的数组）
const tableRef = ref()

// 多选 切换行选中状态
const toggleRow = (row) => {
  const includes = selectedRows.value.includes(row)
  if (includes) {
    selectedRows.value.splice(row)
  } else {
    selectedRows.value.push(row) // 选中
  }
  tableRef.value.toggleRowSelection(row, !includes)
}

// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row)
}
const open = async (classify, id) => {
  dialogVisible.value = true
  selectedRows.value = []
  queryParams.createTime = undefined
  queryParams.item = undefined
  queryParams.pageNo = 1;
  if (id) {
    queryParams.deviceId = id
    await getList()
    debugger
    if (list.value.length === 0) {
      queryParams.deviceId = undefined
      queryParams.deviceClassify = classify
      await getList()
    }
  } else {
    queryParams.deviceClassify = classify
    await getList()
  }
}
defineExpose({ open })
const { wsCache } = useCache()
const getList = async () => {
  loading.value = true
  try {
    const data = await IotInspectItemApi.getIotInspectItemPage(queryParams)
    list.value = data.list
    list.value = list.value.sort((a, b) => {
      return a.sort-b.sort
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个巡检项')
    return
  }

  // emit('choose', selectedRows.value);
  emit(
    'choose',
    selectedRows.value.map((row) => ({
      ...row,
      // 确保返回必要字段
      code: row.item,
      name: row.standard,
    }))
  )
  dialogVisible.value = false
  handleClose()
}

// 关闭时清空选择
const handleClose = () => {
  tableRef.value?.clearSelection()
  selectedRows.value = []
  emit('close')
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: DictDataVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
</script>
<style lang="scss">
.no-label-radio .el-radio__label {
  display: none;
}
.no-label-radio .el-radio__inner {
  margin-right: 0;
}
</style>
