<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="materialCode">
          <el-input
            v-model="queryParams.materialCode"
            :placeholder="t('workOrderMaterial.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('workOrderMaterial.materialName')" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            :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-button @click="handleConfirm" class="custom-green-button"
            ><Icon icon="ep:check" class="mr-5px" />
            {{ t('workOrderMaterial.confirm') }}</el-button
          >
          <el-button @click="handleView" type="warning"
            ><Icon icon="ep:plus" class="mr-5px" />
            {{ t('workOrderMaterial.added') }}</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"
        :row-class-name="rowClassName"
      >
        <el-table-column width="60" :label="t('workOrderMaterial.select')">
          <template #default="{ row }">
            <el-checkbox
              :model-value="selectedRows.some(item =>
                item.factoryId === row.factoryId &&
                item.costCenterId === row.costCenterId &&
                item.storageLocationId === row.storageLocationId &&
                item.materialCode === row.materialCode
              )"
              @click.stop="toggleRow(row)"
              class="no-label-radio"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('workOrderMaterial.factory')"
          align="center"
          prop="factoryId"
          class="!w-100px"
          v-if="false"
        />
        <el-table-column
          :label="t('workOrderMaterial.factory')"
          align="center"
          prop="factory"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          :label="t('workOrderMaterial.costCenter')"
          align="center"
          prop="costCenterId"
          class="!w-100px"
          v-if="false"
        />
        <el-table-column
          :label="t('workOrderMaterial.costCenter')"
          align="center"
          prop="costCenter"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          :label="t('workOrderMaterial.storageLocation')"
          align="center"
          prop="storageLocationId"
          class="!w-100px"
          v-if="false"
        />
        <el-table-column
          :label="t('workOrderMaterial.storageLocation')"
          align="center"
          prop="projectDepartment"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          :label="t('workOrderMaterial.materialCode')"
          align="center"
          prop="materialCode"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          :label="t('workOrderMaterial.materialName')"
          align="center"
          prop="materialName"
          :show-overflow-tooltip="true"
        />
        <el-table-column :label="t('workOrderMaterial.unit')" align="center" prop="unit" />
        <el-table-column :label="t('workOrderMaterial.unitPrice')" align="center" prop="unitPrice" />
        <el-table-column :label="t('workOrderMaterial.total')" align="center" prop="totalInventoryQuantity" />
        <el-table-column :label="t('workOrderMaterial.source')" align="center" prop="materialSource" />
        <el-table-column :label="t('workOrderMaterial.ConsumptionQuantity')" align="center" prop="quantity">
          <template #default="scope">
            <el-input
              type="number"
              :controls="false"
              v-model="scope.row.quantity"
              @click.stop=""
              @focus="handleInputFocus(scope.row)"
              @blur="(event) => handleQuantityBlur(event, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </Dialog>
  <MaintainMaterialDrawer
    ref="showDrawer"
    :model-value="drawerVisible"
    @update:model-value="(val) => (drawerVisible = val)"
    @add="handleChildSubmit"
  />
</template>

<script setup lang="ts">
import { IotMaintainMaterialVO } from '@/api/pms/maintain/material'
import * as WorkOrderBomMaterialApi from '@/api/pms/iotmainworkorderbommaterial'
import { defineExpose, ref } from 'vue'
import MaintainMaterialDrawer from '@/views/pms/maintain/material/MaintainMaterialDrawer.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 total = ref(0) // 列表的总页数
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: '',
  materialCode: '',
  materialName: '',
})

// 保存初始查询参数用于重置
const defaultQueryParams = {
  materialName: '',
  materialCode: '',
  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 handleChildSubmit = (formData) => {
  const modified = removeOnesFromKeys(formData)
  modified.materialName = modified.name;
  modified.materialCode = modified.code;
  modified.materialSource = '手动添加';
  modified.quantity = modified.depleteCount;
  modified.unitPrice = modified.price;
  addMaterial.value = modified;
  list.value.unshift(modified)
  total.value = total.value+1

  // 将新添加的行添加到选中列表
  selectedRows.value.push(modified)
  // 设置新添加行的索引
  lastAddedIndex.value = 0;
}

const removeOnesFromKeys = (obj: Record<string, any>) => {
  return Object.keys(obj).reduce(
    (acc, key) => {
      const newKey = key.replace(/1/g, '') // 替换所有 1
      acc[newKey] = obj[key]
      return acc
    },
    {} as Record<string, any>
  )
}
// 点击整行选中
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 = '维修项'
  }
  await getList()
}

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

const getList = async () => {
  loading.value = true
  try {
    // queryParams.deptId = props.deptId
    const data =
      await WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialApi.workOrderMaterials(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 确认选择
const handleConfirm = () => {
  // 检查是否有未通过校验的行
  const invalidRows = selectedRows.value.filter(row => {
    const quantity = parseFloat(row.quantity);
    return isNaN(quantity) || quantity <= 0;
  });

  if (invalidRows.length > 0) {
    ElMessage.error('存在无效的 消耗数量，请检查');
    return;
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  const filters = selectedRows.value.filter((item) => item.quantity === null||item.quantity === undefined)
  if (filters.length > 0) {
    message.error('消耗数量必填')
    return
  }
  emit(
    'choose',
    selectedRows.value.map((row) => ({
      ...row,
      // 确保返回必要字段
      id: row.id,
      materialCode: row.materialCode,
      materialName: row.materialName,
      unitPrice: row.unitPrice,
      unit: row.unit,
      quantity: row.quantity
    }))
  )
  dialogVisible.value = false
  handleClose()
}

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

const rowClassName = ({ row }: { row: any }) => {
  let className = '';
  if(row.bomMaterialFlag === 'Y'){
    className = ''
  }
  if (row.materialSource === '本地库存' && row.bomMaterialFlag != 'Y') {
    className = ''
  }
  if (row.materialSource === 'sap库存') {
    className = ''
  }
  return className
}

// 多选 切换行选中状态
const toggleRow = (row) => {
  // 创建复合唯一标识
  const getRowUniqueKey = (row) => {
    return `${row.factoryId}_${row.costCenterId}_${row.storageLocationId}_${row.materialCode}`
  }

  const currentKey = getRowUniqueKey(row)
  const index = selectedRows.value.findIndex(item =>
    getRowUniqueKey(item) === currentKey
  )

  if (index > -1) {
    selectedRows.value.splice(index, 1) // 取消选中
  } else {
    selectedRows.value.push(row) // 选中
  }
}

// 处理 消耗数量 quantity 输入框失焦事件
const handleQuantityBlur = (event: Event, row: any) => {
  const inputValue = (event.target as HTMLInputElement).value;
  let num = parseFloat(inputValue);
  // 处理无效值
  if (isNaN(num)) {
    row.quantity = 0;
    return;
  }
  // 处理小于等于0的情况
  if (num <= 0) {
    row.quantity = 0;
    return;
  }
  // 保留两位小数
  row.quantity = parseFloat(num.toFixed(2));
};

// 处理输入框焦点事件（自动选中当前行）
const handleInputFocus = (row: WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO) => {
  const getRowUniqueKey = (row) => {
    return `${row.factoryId}_${row.costCenterId}_${row.storageLocationId}_${row.materialCode}`
  }
  const currentKey = getRowUniqueKey(row)
  // 如果未选中则添加到选中列表
  const exists = selectedRows.value.some(item => getRowUniqueKey(item) === currentKey)
  if (!exists) {
    selectedRows.value.push(row)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: IotMaintainMaterialVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  Object.assign(queryParams, defaultQueryParams)
  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;
}

: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>
