<template>
  <Dialog v-model="dialogVisible" title="保养项物料" style="width: 1200px; min-height: 400px">

    <!-- 新增设备分类和BOM节点信息显示 -->
    <div style="margin: 0 0px 15px; background: #f5f7fa; padding: 12px 20px; border-radius: 4px;">
      <el-row>
        <el-col :span="8">
          <span style="font-weight: bold; margin-right: 10px;">设备编码：</span>
          <span>{{ deviceCode }}</span>
        </el-col>
        <el-col :span="8">
          <span style="font-weight: bold; margin-right: 10px;">设备名称：</span>
          <span>{{ deviceName }}</span>
        </el-col>
        <el-col :span="8">
          <span style="font-weight: bold; margin-right: 10px;">{{bomNodeLabel}}：</span>
          <span>{{ bomNodeName }}</span>
        </el-col>
      </el-row>
    </div>

    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item :label="t('workOrderMaterial.materialCode')" prop="code">
          <el-input
            v-model="queryParams.code"
            :placeholder="t('workOrderMaterial.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('workOrderMaterial.materialName')" prop="name">
          <el-input
            v-model="queryParams.name"
            :placeholder="t('workOrderMaterial.nameHolder')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />
            {{ t('workOrderMaterial.search') }}</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />
            {{ t('workOrderMaterial.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="paginatedList"
        :stripe="true"
        ref="tableRef"
        :show-overflow-tooltip="true"
        @row-click="handleRowClick"
        :row-class-name="rowClassName"
      >
        <el-table-column
          :label="t('workOrderMaterial.materialCode')"
          align="center"
          prop="code"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          :label="t('workOrderMaterial.materialName')"
          align="center"
          prop="name"
          :show-overflow-tooltip="true"
        />
        <el-table-column :label="t('workOrderMaterial.unit')" align="center" prop="unit" />
        <el-table-column :label="t('route.quantity')" align="center" prop="quantity" />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handleLocalPagination"
      />
    </ContentWrap>
  </Dialog>
</template>

<script setup lang="ts">
import { IotMaintainMaterialVO } from '@/api/pms/maintain/material'
import * as WorkOrderBomMaterialApi from '@/api/pms/iotmainworkorderbommaterial'
import { defineExpose, ref } from 'vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
// const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
// 调整 emit 类型
const emit = defineEmits<{
  (e: 'choose', value: WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]): void
  (e: 'close'): void
}>()
// 跟踪新添加的行的索引
const lastAddedIndex = ref<number | null>(null)
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]>([]) // 列表的数据

const originalList = ref<WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]>([]) // 原始数据
const filteredList = ref<WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]>([]) // 过滤后数据

const tableRef = ref()
const selectedRows = ref<WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]>([]) // 多选数据（存储所有选中行的数组）

const deviceName = ref('') // 设备名称
const deviceCode = ref('')    // 设备编码
const bomNodeName = ref('')   // 保养项 or 维修项 名称
const bomNodeLabel = ref('')   // 保养项 or 维修项 名称

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: 0,
  bomNodeId: 0,
  deviceId: 0,
  name: '',
  code: ''
})

// 保存初始查询参数用于重置
const defaultQueryParams = {
  name: '',
  code: '',
  pageNo: 1,
  pageSize: 10,
}

const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const handleView = () => {
  drawerVisible.value = true
  showDrawer.value.openDrawer()
}
const addMaterial = ref(null)

// 计算当前页的数据切片
const paginatedList = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize;
  return filteredList.value.slice(start, start + queryParams.pageSize)
});

// 计算总条数（直接使用 list.length）
const total = computed(() => filteredList.value.length);

// 本地分页切换逻辑
const handleLocalPagination = (e: { page: number; limit: number }) => {
  queryParams.pageNo = e.page;
  queryParams.pageSize = e.limit;
  // 无需调用 getList，paginatedList 会自动更新
};

// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row)
}
const open = async (deptId: number, bomNodeId: number, row: any, type: string) => {
  console.log('传递过来的数据：', row.deviceId)
  Object.assign(queryParams, defaultQueryParams)

  selectedRows.value = []
  dialogVisible.value = true
  queryParams.deptId = deptId
  queryParams.bomNodeId = bomNodeId
  queryParams.deviceId = row.deviceId
  if(type === 'repair'){
    queryParams.deviceId = row.deviceId
  }
  deviceName.value = row.deviceName
  deviceCode.value = row.deviceCode
  bomNodeName.value = row.name
  if (type === 'maintenance') {
    bomNodeLabel.value = '保养项'
  } else if (type === 'repair') {
    bomNodeLabel.value = '维修项'
  }

  // 修改后的设备BOM物料处理逻辑
  let sourceData = []
  if (row.deviceBomMaterials) {
    sourceData = typeof row.deviceBomMaterials === 'string'
      ? JSON.parse(row.deviceBomMaterials)
      : row.deviceBomMaterials
  }
  // 统一字段并保存
  originalList.value = sourceData.map(normalizeItem)
  // 初始化过滤列表
  resetQuery()
  // 重置分页参数
  queryParams.pageNo = 1;
  queryParams.pageSize = 10;
  loading.value = false
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

// 字段统一处理
const normalizeItem = (item: any): WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO => ({
  ...item,
  code: item.code,
  name: item.name
})

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  const { code, name } = queryParams

  // 本地过滤逻辑
  filteredList.value = originalList.value.filter(item => {
    const codeMatch = (item.code || '').toLowerCase().includes(code.toLowerCase())
    const nameMatch = (item.name || '').toLowerCase().includes(name.toLowerCase())
    return codeMatch && nameMatch
  })
}
const choose = (row: IotMaintainMaterialVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  Object.assign(queryParams, defaultQueryParams)
  filteredList.value = [...originalList.value] // 恢复完整数据集
}
</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;
}

:deep(.el-table .row-green-bg) {
  background-color: #f0f9eb !important; /* Element Plus 绿色背景 */
}

:deep(.el-table .bg-blue-5) {
  background-color: #3fa5de !important; /* Element Plus 绿色背景 */
}
</style>
