<template>
  <Dialog v-model="dialogVisible" :title="t('route.selectInspectionItems')" style="width: 1300px; min-height: 50%">
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item :label="t('inspect.InspectionItems')" prop="item" style="margin-left: 45px">
          <el-input
            v-model="queryParams.item"
            :placeholder="t('inspect.itemHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item :label="t('common.createTime')" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            :start-placeholder="t('info.start')"
            :end-placeholder="t('info.end')"
            :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" /> {{ t('operationFill.search') }}</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('operationFill.reset') }}</el-button>
          <el-button @click="handleConfirm" type="danger"
            ><Icon icon="ep:check" class="mr-5px" /> {{ t('workOrderMaterial.confirm') }}</el-button
          >
          <el-button @click="toggleAll" type="primary"
            ><Icon icon="ep:refresh" class="mr-5px" />{{ t('chooseMaintain.selectAll') }}</el-button
          >
          <el-button @click="invertSelection" type="info"
            ><Icon icon="ep:refresh" class="mr-5px" />{{ t('chooseMaintain.cancelAllSelection') }}</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
          type="selection"
          :reserve-selection="true"
          :selectable="(row) => !row.disabled"
        />
        <el-table-column :label="t('inspect.InspectionItems')" align="center" prop="item" />
        <el-table-column :label="t('inspect.InspectionStandards')" align="center" prop="standard" />
        <el-table-column :label="t('fileInfo.appendix')" align="center" prop="urls">
          <template #default="scope">
            <el-button v-if="scope.row.urls" link type="primary" @click="openWeb(scope.row.urls)">
              <Icon size="19" icon="ep:view"
            /></el-button>
          </template>
        </el-table-column>
        <el-table-column :label="t('common.sort')" align="center" prop="sort" />
        <el-table-column
          :label="t('common.createTime')"
          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 { useCache } from '@/hooks/web/useCache'
import { IotInspectItemApi, IotInspectItemVO } from '@/api/pms/inspect/item'
const { t } = useI18n() // 国际化
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 openWeb = (url) => {
  window.open(
    'http://1.94.244.160:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
  )
}
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
  queryParams.deviceId = undefined
  // if (id) {
  //   queryParams.deviceId = id
  //   await getList()
  //   if (list.value.length === 0) {
  //     queryParams.deviceId = undefined
  //     queryParams.deviceClassify = classify
  //     await getList()
  //   }
  // } else {
  //   queryParams.deviceClassify = classify
  //   await getList()
  // }
  queryParams.deviceId = id
  queryParams.deviceClassify = classify
  await getList()
}
defineExpose({ open })
const { wsCache } = useCache()
const getList = async () => {
  loading.value = true
  try {
    const data = await IotInspectItemApi.getIotInspectRouteItemPage(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>
