<template>
  <Dialog v-model="dialogVisible" :title="t('chooseMaintain.selectRepairItem')" style="width: 1100px; min-height: 300px">
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item :label="t('chooseMaintain.materialCode')" prop="code" style="margin-left: 25px">
          <el-input
            v-model="queryParams.code"
            :placeholder="t('chooseMaintain.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('chooseMaintain.materialName')" prop="name" style="margin-left: 25px">
          <el-input
            v-model="queryParams.name"
            :placeholder="t('chooseMaintain.nameHolder')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />
            {{ t('chooseMaintain.search') }}</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />
            {{ t('chooseMaintain.reset')  }}</el-button>
          <el-button @click="handleConfirm" type="danger"
            ><Icon icon="ep:check" class="mr-5px" />
            {{ t('chooseMaintain.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('chooseMaintain.deviceCode')"
          align="center"
          prop="deviceCode"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          :label=" t('chooseMaintain.deviceName')"
          align="center"
          prop="deviceName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label=" t('chooseMaintain.deviceName')"
          align="center"
          prop="deviceName"
          :show-overflow-tooltip="true"
        />
        <el-table-column :label=" t('chooseMaintain.repairItems')" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column
          :label="t('chooseMaintain.createTime')"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
      </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 { IotDeviceApi } from '@/api/pms/device'
import { IotMaintainMaterialVO } from '@/api/pms/maintain/material'
import { propTypes } from '@/utils/propTypes'
import { dateFormatter } from '@/utils/formatTime'
const message = useMessage() // 消息弹窗
const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const selectedRows = ref<any[]>([]) // 多选数据（存储所有选中行的数组）
const list = ref<any[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const tableRef = ref()
const { t } = useI18n() // 国际化
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceIds: [],
  bomFlag: 'w'
})
const props = defineProps({
  deptId: propTypes.number.def(undefined)
})
const invertSelection = () => {
  selectedRows.value.forEach((row) => {
    tableRef.value.toggleRowSelection(row, false)
    selectedRows.value.splice(row)
  })
}
const toggleAll = () => {
  list.value.forEach((row) => {
    tableRef.value.toggleRowSelection(row, true)
  })
}
const selectedRow = ref(null)
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 selectRow = (row) => {
  selectedRow.value = selectedRow.value?.id === row.id ? null : row
  emit('choose', row)
  dialogVisible.value = false
}

// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row)
}
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 handleSelectionChange = (val) => {
  selectedRows.value = val
}
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  queryParams.deviceIds = []
  queryParams.deviceIds.push(id)
  queryParams.bomFlag = 'w'
  list.value = []
  await getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const getList = async () => {
  loading.value = true
  try {
    const res = await IotDeviceApi.deviceAssociateBomListPage(queryParams)
    const rawData = res || []
    if (rawData.length === 0) {
      message.error('选择的设备不存在待保养BOM项')
    }
    list.value = rawData.list
    total.value = rawData.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: IotMaintainMaterialVO) => {
  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;
}
/* 自定义淡绿色按钮 */
:deep(.custom-green-button) {
  background-color: #e1f3d8;
  border-color: #e1f3d8;
  color: #67c23a;
}

/* 悬停效果 */
:deep(.custom-green-button:hover) {
  background-color: #d1e8c0;
  border-color: #d1e8c0;
  color: #5daf34;
}

/* 点击效果 */
:deep(.custom-green-button:active) {
  background-color: #c2dca8;
  border-color: #c2dca8;
}
</style>
