<template>
  <Dialog v-model="dialogVisible" title="选择物料" style="width: 1100px; min-height: 800px">
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="物料编码" prop="code">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入物料编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </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-button @click="handleView" type="warning"
            ><Icon icon="ep:plus" 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"
        :row-class-name="rowClassName"
      >
        <el-table-column width="60" label="选择">
          <template #default="{ row }">
            <el-checkbox
              :model-value="selectedRows.some((item) => item.materialCode === row.materialCode)"
              @click.stop="toggleRow(row)"
              class="no-label-radio"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="物料编码"
          align="center"
          prop="materialCode"
          :show-overflow-tooltip="true"
          class="!w-100px"
        />
        <el-table-column
          label="物料名称"
          align="center"
          prop="materialName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="总库存数量" align="center" prop="totalInventoryQuantity" />
        <el-table-column label="来源" align="center" prop="materialSource" />
        <el-table-column label="消耗数量" align="center" prop="quantity">
          <template #default="scope">
            <el-input
              v-model="scope.row.quantity"
              @click.stop=""
              @focus="scope.$el.querySelector('input').focus()"
            />
          </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 message = useMessage() // 消息弹窗
// const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
// 调整 emit 类型
const emit = defineEmits<{
  (e: 'choose', value: WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]): void
  (e: 'close'): void
}>()
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 queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: 0,
  bomNodeId: 0,
  name: '',
  code: ''
})
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const handleView = () => {
  drawerVisible.value = true
  showDrawer.value.openDrawer()
}
const addMateriall = ref(null)
const handleChildSubmit = (formData) => {
  const modified = removeOnesFromKeys(formData)
  modified.materialName = modified.name;
  modified.materialCode = modified.code;
  modified.materialSource = '手动添加';
  addMateriall.value = modified;
  list.value.unshift(modified)
  total.value = total.value+1
}
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) => {
  console.log('传递过来的数据：', deptId)
  selectedRows.value = []
  dialogVisible.value = true
  queryParams.deptId = deptId
  queryParams.bomNodeId = bomNodeId
  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 = () => {
  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 = 'row-green-bg'
  }
  if (row.materialSource === '本地库存' && row.bomMaterialFlag != 'Y') {
    className = ''
  }
  if (row.materialSource === 'sap库存') {
    className = 'row-red-bg'
  }
  return className
}

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

/** 搜索按钮操作 */
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" 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>
