<template>
  <Dialog v-model="dialogVisible" title="选择设备"
          style="width: 1100px; max-height: 800px"  @close="handleClose">
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
        @submit.prevent
      >
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            @keyup.enter="handleQuery"
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            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" class="custom-green-button"><Icon icon="ep:check" class="mr-5px" /> 确认选择</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        ref="tableRef"
        :show-overflow-tooltip="true"
        @row-click="handleRowClick"
      >
        <el-table-column width="60" label="选择">
          <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 label="资产编码" align="center" prop="deviceCode" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="所在部门id" align="center" prop="deptId" v-if="false"/>
        <el-table-column label="所在部门" align="center" prop="deptName" />
        <el-table-column label="设备状态" align="center" prop="deviceStatus">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="scope.row.deviceStatus" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
          :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 { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<IotDeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const tableRef = ref();
const selectedRows = ref<IotDeviceVO[]>([]); // 多选数据（存储所有选中行的数组）

// 调整 emit 类型
const emit = defineEmits<{
  (e: 'choose', value: IotDeviceVO[]): void
  (e: 'close'): void
}>()

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  deptId: undefined,
  assetClass: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  name: undefined,
  code: undefined
})

// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row)
}
const open = async () => {
  dialogVisible.value = true
  // 重置为初始参数（保留分页设置）
  Object.assign(queryParams, initialQueryParams)
  queryFormRef.value?.resetFields()
  await getList()
}
defineExpose({ open })
const { wsCache } = useCache()
const getList = async () => {
  loading.value = true
  try {
    // const user = wsCache.get(CACHE_KEY.USER)
    // queryParams.deptId = user.user.deptId
    const data = await IotDeviceApi.getIotDevicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const initialQueryParams = {
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  deptId: undefined,
  assetClass: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  name: undefined,
  code: undefined
}

// 多选 切换行选中状态
const toggleRow = (row) => {
  const index = selectedRows.value.findIndex(item => item.id === row.id);
  if (index > -1) {
    selectedRows.value.splice(index, 1); // 取消选中
  } else {
    selectedRows.value.push(row); // 选中
  }
};

// 关闭时清空选择
const handleClose = () => {
  tableRef.value?.clearSelection();
  selectedRows.value = []
  emit('close')
};

// 确认选择
const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  emit('choose', selectedRows.value.map(row => ({
    ...row,
    // 确保返回必要字段
    id: row.id,
    deviceCode: row.deviceCode,
    deviceName: row.deviceName,
    deviceStatus: row.deviceStatus,
    deptName: row.deptName,
    assetProperty: row.assetProperty,
    name: row.name,
    code: row.code
  })))
  dialogVisible.value = false;
  handleClose()
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: DictDataVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  // 重置为初始参数
  Object.assign(queryParams, initialQueryParams)
  queryFormRef.value?.resetFields()
  handleQuery()
}
</script>
<style lang="scss" scoped>
.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>
