<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('iotDevice.brand')" prop="brandName">-->
<!--          <el-input-->
<!--            v-model="queryParams.brandName"-->
<!--            :placeholder="t('iotDevice.brandHolder')"-->
<!--            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 v-if="selectedRows.length > 0"
                 style="margin: -10px 0px 10px; padding: 10px 15px; background: #f8fafc; border-radius: 4px; border: 1px solid #ebeef5;">
      <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 8px;">
        <div style="font-weight: bold; color: #606266; margin-right: 10px;">已选物料：</div>
        <el-tag
          v-for="item in selectedRows"
          :key="item.id"
          @close="removeTag(item)"
          style="margin-bottom: 5px; position: relative; padding-right: 25px;"
        >
          {{ item.item }}
          <!-- 自定义关闭按钮 -->
          <span class="close-icon" @click.stop="removeTag(item)">
            <Icon icon="ep:close" style="font-size: 12px; position: absolute; right: 8px; top: 50%; transform: translateY(-50%);"/>
          </span>
        </el-tag>
      </div>
    </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 width="80" :label="t('workOrderMaterial.select')">
          <template #default="{ row }">
            <el-checkbox
              :model-value="selectedRows.some(item => item.id === row.id&&item.deviceCode===row.deviceCode)"
              @click.stop="selectRow(row)"
              class="no-label-radio"
            />
          </template>
        </el-table-column>
        <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('iotDevice.brand')" align="center" prop="brandName" />
        <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,
  brandName:undefined,
  deviceId: undefined,
  createTime: undefined
})
const openWeb = (url) => {
  window.open(
    'http://1.94.244.160:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
  )
}
const removeTag = (route) => {
  // 从已选列表中移除
  const index = selectedRows.value.findIndex(item => item.id === route.id);
  debugger
  if (index !== -1) {
    selectedRows.value.splice(index, 1);
  }

  // 如果当前行在当前页，取消其选中状态
  const rowInTable = list.value.find(item => item.id === route.id);
  if (rowInTable) {
    const rowIndex = list.value.indexOf(rowInTable);
    // 这里可以添加逻辑强制更新行状态（如果需要）
  }
};
const selectRow = (row) => {
  selectedRow.value = selectedRow.value?.id === row.id ? null : row
  emit('choose', row)
  dialogVisible.value = false
}
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, brandName) => {
  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
  queryParams.brandName = brandName
  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>
