<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单编号" prop="orderCode">
            <el-input
              v-model="formData.orderCode"
              placeholder="请点击选择工单编号"
              readonly
              class="!w-full"
              @click="handleSelectWorkOrder"
              style="cursor: pointer;"
            >
              <template #suffix>
                <Icon icon="ep:search" class="cursor-pointer" @click="handleSelectWorkOrder" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="领料单号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入领料单号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="领料时间" prop="requisitionTime">
            <el-date-picker
              v-model="formData.requisitionTime"
              type="datetime"
              placeholder="请选择领料时间"
              value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人" prop="applicantName">
            <el-input
              v-model="formData.applicantName"
              placeholder="系统自动设置"
              readonly
              class="!w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="选择BOM">
            <el-select
              v-model="selectedBomId"
              placeholder="请选择BOM带出物料"
              filterable
              clearable
              class="!w-full"
              @change="handleBomChange"
            >
              <el-option
                v-for="bom in bomOptions"
                :key="bom.id"
                :label="bom.bomName + (bom.version ? ' (V' + bom.version + ')' : '') + ' - ' + (bom.productName || '')"
                :value="bom.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark"  placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>



      <!-- 领料明细 -->
      <el-form-item label="领料明细" class="!mb-0">
        <el-button type="primary" plain class="mb-10px" @click="handleAddItem">
          <Icon icon="ep:plus" class="mr-5px" />添加明细
        </el-button>
        <el-table :data="formData.items" border max-height="400px" style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="产品" min-width="200">
            <template #default="{ $index }">
              <el-form-item
                :prop="'items.' + $index + '.materialId'"
                :rules="[{ required: true, message: '请选择产品', trigger: 'change' }]"
                class="!mb-0"
              >
                <el-select
                  v-model="formData.items[$index].materialId"
                  placeholder="请选择或输入产品（支持输入条码或名称）"
                  filterable
                  allow-create
                  default-first-option
                  class="!w-full"
                  @change="handleProductChange($index)"
                >
                  <el-option
                    v-for="p in productOptions"
                    :key="p.id"
                    :label="p.barCode ? p.name + '（' + p.barCode + '）' : p.name"
                    :value="p.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="物料信息" min-width="240">
            <template #default="{ $index }">
              <div>
                <el-form-item :prop="'items.' + $index + '.materialCode'" class="!mb-4px">
                  <el-input
                    v-model="formData.items[$index].materialCode"
                    :disabled="formData.items[$index].matched === true"
                    placeholder="物料编码"
                  />
                </el-form-item>
                <el-form-item :prop="'items.' + $index + '.materialName'" class="!mb-4px">
                  <el-input v-model="formData.items[$index].materialName" placeholder="物料名称" />
                </el-form-item>
                <el-form-item :prop="'items.' + $index + '.unit'" class="!mb-0">
                  <el-input v-model="formData.items[$index].unit" placeholder="单位" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="计划数量" width="140">
            <template #default="{ $index }">
              <el-form-item
                :prop="'items.' + $index + '.planQuantity'"
                :rules="[{ required: true, message: '计划数量不能为空', trigger: 'blur' }]"
                class="!mb-0"
              >
                <el-input-number
                  v-model="formData.items[$index].planQuantity"
                  :min="0"
                  :precision="2"
                  :step="1"
                  placeholder="请输入计划数量"
                  class="!w-full"
                  controls-position="right"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="仓库" min-width="160">
            <template #default="{ $index }">
              <el-form-item
                :prop="'items.' + $index + '.warehouseId'"
                :rules="[{ required: true, message: '仓库不能为空', trigger: 'blur' }]"
                class="!mb-0"
              >
                <el-select
                  v-model="formData.items[$index].warehouseId"
                  placeholder="请选择仓库"
                  class="!w-full"
                  @change="handleWarehouseChange($index)"
                >
                  <el-option
                    v-for="w in warehouseOptions"
                    :key="w.id"
                    :label="w.name"
                    :value="w.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="过磅单号" min-width="160">
            <template #default="{ $index }">
              <el-form-item :prop="'items.' + $index + '.no'" class="!mb-0">
                <el-input
                  v-model="formData.items[$index].no"
                  placeholder="请点击选择过磅单"
                  readonly
                  class="!w-full"
                  @click="handleSelectWeigh($index)"
                  style="cursor: pointer;"
                >
                  <template #suffix>
                    <Icon icon="ep:search" class="cursor-pointer" @click="handleSelectWeigh($index)" />
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="180">
            <template #default="{ $index }">
              <el-input v-model="formData.items[$index].remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="{ $index }">
              <el-tooltip
                content="过磅详情"
                placement="top"
                v-if="formData.items[$index].purchaseId"
              >
                <el-button link type="primary" @click="handleViewWeigh($index)">
                  <Icon icon="ep:document" />
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="danger" @click="handleDeleteItem($index)">
                  <Icon icon="ep:delete" />
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
  </Dialog>

  <!-- 确认领料弹窗 -->
  <Dialog title="确认领料" v-model="completeDialogVisible" width="80%">
    <el-form
      ref="completeFormRef"
      :model="completeFormData"
      :rules="completeFormRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-table :data="completeFormData.items" border max-height="400px">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="物料编码" prop="materialCode" min-width="120" />
        <el-table-column label="物料名称" prop="materialName" min-width="120" />
        <el-table-column label="单位" prop="unit" width="80" />
        <el-table-column label="仓库" width="300px">
          <template #default="{ $index }">
            <el-form-item
              :prop="'items.' + $index + '.warehouseId'"
              :rules="[{ required: true, message: '仓库不能为空', trigger: 'blur' }]"
              class="!mb-0"
            >
              <el-select
                v-model="completeFormData.items[$index].warehouseId"
                placeholder="请选择仓库"
                class="!w-full !text-left"
                @change="handleCompleteWarehouseChange($index)"
              >
                <el-option
                  v-for="w in warehouseOptions"
                  :key="w.id"
                  :label="w.name"
                  :value="w.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="过磅单号" min-width="150px">
          <template #default="{ $index }">
            <el-form-item :prop="'items.' + $index + '.no'" class="!mb-0">
              <el-input
                v-model="completeFormData.items[$index].no"
                placeholder="请点击选择过磅单"
                readonly
                class="!w-full !text-left"
                @click="handleCompleteSelectWeigh($index)"
                style="cursor: pointer; text-align: left;"
              >
                <template #suffix>
                  <Icon icon="ep:search" class="cursor-pointer" @click="handleCompleteSelectWeigh($index)" />
                </template>
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="实际数量" width="200px">
          <template #default="{ $index }">
            <el-form-item
              :prop="'items.' + $index + '.actualQuantity'"
              :rules="[{ required: true, message: '实际数量不能为空', trigger: 'blur' }]"
              class="!mb-0"
            >
              <el-input
                v-model.number="completeFormData.items[$index].actualQuantity"
                placeholder="请输入实际数量"
                class="!w-full !text-left"
                type="number"
                style="text-align: left;"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="120">
          <template #default="{ $index }">
            <el-input v-model="completeFormData.items[$index].remark" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="completeDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitCompleteForm" :loading="formLoading">确认</el-button>
    </template>
  </Dialog>

  <!-- 工单选择弹窗 -->
  <Dialog title="选择工单" v-model="workOrderSelectDialogVisible" width="80%">
    <div class="mb-4">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="workOrderSearchForm.code"
            placeholder="请输入工单编号"
            clearable
            @keyup.enter="handleWorkOrderSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="workOrderSearchForm.name"
            placeholder="请输入工单名称"
            clearable
            @keyup.enter="handleWorkOrderSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="workOrderSearchForm.status"
            placeholder="请选择状态"
            multiple
            clearable
            class="!w-full"
          >
            <el-option label="草稿" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="已审核" :value="2" />
            <el-option label="生产中" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已关闭" :value="5" />
            <el-option label="已取消" :value="6" />
            <el-option label="已入库" :value="7" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleWorkOrderSearch">
            <Icon icon="ep:search" class="mr-5px" />搜索
          </el-button>
          <el-button @click="handleWorkOrderReset">
            <Icon icon="ep:refresh" class="mr-5px" />重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="workOrderSelectList"
      border
      max-height="400px"
      style="width: 100%"
      @row-click="handleWorkOrderRowSelect"
      highlight-current-row
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="工单编号" prop="code" min-width="150" />
      <el-table-column label="工单名称" prop="name" min-width="200" />
      <el-table-column label="产品名称" prop="productName" min-width="150" />
      <el-table-column label="计划数量" prop="planQuantity" width="100" align="center" />
      <el-table-column label="已完成数量" prop="producedQuantity" width="100" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getWorkOrderStatusType(row.status)">
            {{ getWorkOrderStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划开始时间" prop="planStartTime" width="160" align="center">
        <template #default="{ row }">
          {{ row.planStartTime ? formatDate(row.planStartTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" prop="planEndTime" width="160" align="center">
        <template #default="{ row }">
          {{ row.planEndTime ? formatDate(row.planEndTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleWorkOrderSelect(row)">
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4 flex justify-center">
      <el-pagination
        v-model:current-page="workOrderPagination.pageNo"
        v-model:page-size="workOrderPagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="workOrderPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleWorkOrderPageSizeChange"
        @current-change="handleWorkOrderPageChange"
      />
    </div>

    <template #footer>
      <el-button @click="workOrderSelectDialogVisible = false">取消</el-button>
    </template>
  </Dialog>

  <!-- 过磅单选择弹窗 -->
  <Dialog title="选择过磅单" v-model="weighSelectDialogVisible" width="80%">
    <div class="mb-4">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="weighSearchForm.no"
            placeholder="请输入过磅单号"
            clearable
            @keyup.enter="handleWeighSearch"
          />
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="weighSearchForm.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleWeighSearch"
          />
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="handleWeighSearch">
            <Icon icon="ep:search" class="mr-5px" />搜索
          </el-button>
          <el-button @click="handleWeighReset">
            <Icon icon="ep:refresh" class="mr-5px" />重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="weighSelectList"
      border
      max-height="400px"
      style="width: 100%"
      @row-click="handleWeighRowSelect"
      highlight-current-row
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="过磅单号" prop="no" min-width="150" />
      <el-table-column label="产品名称" prop="productName" min-width="150" />
      <el-table-column label="车牌号" prop="vehicleNumber" width="120" />
      <el-table-column label="净重(kg)" prop="netWeight" width="100" align="center" />
      <el-table-column label="计划重量(kg)" prop="plannedWeight" width="120" align="center" />
      <el-table-column label="剩余重量(kg)" prop="remainingWeight" width="120" align="center" />
             <el-table-column label="供应商" min-width="150">
         <template #default="{ row }">
           {{ row.supplierName || row.supplierName2 || '-' }}
         </template>
       </el-table-column>
      <el-table-column label="入库状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.inStatus === 1 ? 'success' : 'warning'">
            {{ row.inStatus === 1 ? '已入库' : '未入库' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="160" align="center">
        <template #default="{ row }">
          {{ row.createTime ? formatDate(row.createTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleWeighSelect(row)">
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4 flex justify-center">
      <el-pagination
        v-model:current-page="weighPagination.pageNo"
        v-model:page-size="weighPagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="weighPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleWeighPageSizeChange"
        @current-change="handleWeighPageChange"
      />
    </div>

    <template #footer>
      <el-button @click="weighSelectDialogVisible = false">取消</el-button>
    </template>
  </Dialog>

  <!-- 过磅单详情弹窗 -->
  <Dialog title="过磅单详情" v-model="weighDialogVisible" width="50%">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="过磅单号">{{ weighDetail?.no || '-' }}</el-descriptions-item>
      <el-descriptions-item label="入库状态">{{
        weighDetail?.inStatus === 1 ? '已入库' : '未入库'
      }}</el-descriptions-item>
      <el-descriptions-item label="产品">{{
        weighDetail?.productName || '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="车牌">{{
        weighDetail?.vehicleNumber || '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="毛重">{{
        weighDetail?.grossWeight != null ? weighDetail.grossWeight + ' kg' : '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="皮重">{{
        weighDetail?.tareWeight != null ? weighDetail.tareWeight + ' kg' : '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="净重">{{
        weighDetail?.netWeight != null ? weighDetail.netWeight + ' kg' : '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="计划重量">{{
        weighDetail?.plannedWeight != null ? weighDetail.plannedWeight + ' kg' : '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="剩余重量">{{
        weighDetail?.remainingWeight != null ? weighDetail.remainingWeight + ' kg' : '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="杂质率">{{
        weighDetail?.impurityRate != null ? (weighDetail.impurityRate * 100).toFixed(2) + '%' : '-'
      }}</el-descriptions-item>
             <el-descriptions-item label="供应商">{{
         weighDetail?.supplierName || weighDetail?.supplierName2 || '-'
       }}</el-descriptions-item>
       <el-descriptions-item label="供应商类型">{{
         weighDetail?.supplierName2 || '-'
       }}</el-descriptions-item>
      <el-descriptions-item label="身份证号">{{
        weighDetail?.idCardNumber || '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="司机">{{ weighDetail?.driver || '-' }}</el-descriptions-item>
      <el-descriptions-item label="管理员">{{
        weighDetail?.administrator || '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="过磅员">{{ weighDetail?.weigher || '-' }}</el-descriptions-item>
      <el-descriptions-item label="产地证编号">{{
        weighDetail?.originCertificateNumber || '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="附件">
        <template v-if="weighDetail?.fileUrl">
          <a :href="weighDetail.fileUrl" target="_blank">查看附件</a>
        </template>
        <template v-else>-</template>
      </el-descriptions-item>
      <el-descriptions-item label="备注" :span="2">{{
        weighDetail?.remark || '-'
      }}</el-descriptions-item>
      <el-descriptions-item label="创建时间" :span="2">{{
        weighDetail?.createTime ? formatDate(weighDetail.createTime) : '-'
      }}</el-descriptions-item>
    </el-descriptions>

    <!-- 检验信息部分 - 仅当有检验数据时显示 -->
    <template v-if="hasInspectionData">
      <el-divider content-position="left">检验信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="取样日期">{{
          weighDetail?.sampleDate ? formatDate(weighDetail.sampleDate) : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="取样地点">{{
          weighDetail?.sampleLocation || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="代表重量">{{
          weighDetail?.representativeWeight != null ? weighDetail.representativeWeight + ' kg' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="样品重量">{{
          weighDetail?.sampleWeight != null ? weighDetail.sampleWeight + ' kg' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="杂质重量">{{
          weighDetail?.impurityWeight != null ? weighDetail.impurityWeight + ' kg' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="沙土重量">{{
          weighDetail?.sandWeight != null ? weighDetail.sandWeight + ' kg' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="感官">{{
          weighDetail?.sensoryEvaluation || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="合格率">{{
          weighDetail?.qualificationRate ? weighDetail.qualificationRate + '%' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="水分">{{
          weighDetail?.moistureContent ? weighDetail.moistureContent + '%' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="含糖">{{
          weighDetail?.sugarContent ? weighDetail.sugarContent + '%' : '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="RA值">{{
          weighDetail?.raValue || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="STV值">{{
          weighDetail?.stvValue || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="化验员">{{
          weighDetail?.labTechnician || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="检验备注" :span="2">{{
          weighDetail?.inspectionRemark || '-'
        }}</el-descriptions-item>
      </el-descriptions>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import * as MaterialRequisitionApi from '@/api/mes/production/material-requisition'
import { formatDate } from '@/utils/formatTime'
import { ProductApi } from '@/api/erp/product/product'
import { WarehouseApi } from '@/api/erp/stock/warehouse'
import { WeighApi } from '@/api/erp/purchase/weigh'
import { YVHgetWorkOrderPage } from '@/api/mes/production/workorder'
import { getProductBomPage, getProductBom, ProductBomVO, ProductBomItemVO } from '@/api/mes/product/bom'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')
const productOptions = ref<any[]>([])
const warehouseOptions = ref<any[]>([])
const bomOptions = ref<ProductBomVO[]>([])
const selectedBomId = ref<number | undefined>(undefined)

const weighDialogVisible = ref(false)
const weighDetail = ref<any>(null)

// 判断是否有检验数据
const hasInspectionData = computed(() => {
  if (!weighDetail.value) return false
  return !!(
    weighDetail.value.sampleDate ||
    weighDetail.value.sampleLocation ||
    weighDetail.value.representativeWeight ||
    weighDetail.value.sampleWeight ||
    weighDetail.value.impurityWeight ||
    weighDetail.value.sandWeight ||
    weighDetail.value.sensoryEvaluation ||
    weighDetail.value.qualificationRate ||
    weighDetail.value.moistureContent ||
    weighDetail.value.sugarContent ||
    weighDetail.value.raValue ||
    weighDetail.value.stvValue ||
    weighDetail.value.labTechnician ||
    weighDetail.value.inspectionRemark
  )
})

// 工单选择弹窗相关
const workOrderSelectDialogVisible = ref(false)
const workOrderSelectList = ref<any[]>([])
const workOrderSearchForm = reactive({
  code: '',
  name: '',
  status: [] as number[]
})
const workOrderPagination = reactive({
  pageNo: 1,
  pageSize: 20,
  total: 0
})

// 过磅单选择弹窗相关
const weighSelectDialogVisible = ref(false)
const currentSelectIndex = ref<number>(-1)
const weighSelectList = ref<any[]>([])
const weighSearchForm = reactive({
  no: '',
  productName: ''
})
const weighPagination = reactive({
  pageNo: 1,
  pageSize: 20,
  total: 0
})

interface MaterialRequisitionItem {
  id?: number
  materialId: number | string
  materialCode: string
  materialName: string
  unit: string
  planQuantity: number
  actualQuantity?: number
  warehouseId: number
  warehouseName: string
  no?: string
  purchaseId?: number
  weighRemainingWeight?: number
  remark?: string
  matched?: boolean
}

interface MaterialRequisitionForm {
  id?: number
  code: string
  orderCode: string
  orderId?: number
  requisitionTime: string
  status: number
  applicantId?: number
  applicantName?: string
  remark?: string
  items: MaterialRequisitionItem[]
}

// 初始化默认值
const defaultFormData: MaterialRequisitionForm = {
  code: '',
  orderCode: '',
  orderId: undefined,
  requisitionTime: new Date().toISOString(),
  status: 0,
  applicantId: undefined,
  applicantName: '',
  remark: '',
  items: []
}

const formData = ref<MaterialRequisitionForm>({
  ...defaultFormData
})

const formRef = ref()
const formRules = reactive({
  code: [{ required: true, message: '请输入领料单号', trigger: 'blur' }],
  orderCode: [{ required: true, message: '请输入工单编号', trigger: 'blur' }],
  requisitionTime: [{ required: true, message: '请选择领料时间', trigger: 'change' }]
})

interface CompleteFormData {
  id: number
  items: Array<{
    id: number
    materialId: number
    materialCode: string
    materialName: string
    unit: string
    warehouseId: number
    warehouseName: string
    actualQuantity: number
    no?: string
    purchaseId?: number
    weighRemainingWeight?: number
    remark?: string
  }>
}

const completeDialogVisible = ref(false)
const completeFormData = ref<CompleteFormData>({
  id: 0,
  items: []
})
const completeFormRef = ref()
const completeFormRules = {}

const loadProductOptions = async () => {
  try {
    const list = await ProductApi.getProductSimpleList()
    productOptions.value = Array.isArray(list) ? list : list?.data || []
  } catch (e) {
    console.error('加载产品列表失败', e)
  }
}

const loadWarehouseOptions = async () => {
  try {
    const list = await WarehouseApi.getWarehouseSimpleList()
    warehouseOptions.value = Array.isArray(list) ? list : list?.data || []
    // 为已存在但未选择仓库的明细设置默认仓库（列表第一个）
    if (warehouseOptions.value.length > 0) {
      const first = warehouseOptions.value[0]
      formData.value.items.forEach((it: any) => {
        if (it.warehouseId == null || it.warehouseId === 0) {
          it.warehouseId = first.id
          it.warehouseName = first.name
        }
      })
    }
  } catch (e) {
    console.error('加载仓库列表失败', e)
  }
}

// 加载BOM列表
const loadBomOptions = async () => {
  try {
    const res: any = await getProductBomPage({ pageNo: 1, pageSize: 100, status: 1 })
    bomOptions.value = res?.list || res?.data?.list || []
  } catch (e) {
    console.error('加载BOM列表失败', e)
  }
}

// 选择BOM后带出物料
const handleBomChange = async (bomId: number | undefined) => {
  if (!bomId) return
  try {
    formLoading.value = true
    const bom: any = await getProductBom(bomId)
    const bomData = bom?.data || bom
    if (bomData && Array.isArray(bomData.items) && bomData.items.length > 0) {
      // 获取默认仓库
      let defaultWarehouseId = 0
      let defaultWarehouseName = ''
      if (warehouseOptions.value.length > 0) {
        defaultWarehouseId = warehouseOptions.value[0].id
        defaultWarehouseName = warehouseOptions.value[0].name
      }

      // 将BOM物料转换为领料明细
      const newItems: MaterialRequisitionItem[] = bomData.items.map((item: ProductBomItemVO) => ({
        materialId: item.materialId,
        materialCode: item.materialCode || '',
        materialName: item.materialName || '',
        unit: item.unit || '',
        planQuantity: item.unitQuantity || 0,
        warehouseId: defaultWarehouseId,
        warehouseName: defaultWarehouseName,
        remark: item.remark || '',
        matched: true,
        no: '',
        purchaseId: undefined
      }))

      // 追加到现有明细中
      formData.value.items.push(...newItems)
      ElMessage.success(`已从BOM带出 ${newItems.length} 条物料明细`)
    } else {
      ElMessage.warning('该BOM没有物料明细')
    }
  } catch (e) {
    console.error('获取BOM详情失败', e)
    ElMessage.error('获取BOM详情失败')
  } finally {
    formLoading.value = false
    // 重置选择，允许再次选择同一BOM
    selectedBomId.value = undefined
  }
}





const handleWarehouseChange = (index: number) => {
  const item = formData.value.items[index]
  if (!item) return
  const w = warehouseOptions.value.find((x: any) => x.id === item.warehouseId)
  item.warehouseName = w ? w.name : ''
}

const handleCompleteWarehouseChange = (index: number) => {
  const item = completeFormData.value.items[index]
  if (!item) return
  const w = warehouseOptions.value.find((x: any) => x.id === item.warehouseId)
  item.warehouseName = w ? w.name : ''
}

const handleProductChange = async (index: number) => {
  const item = formData.value.items[index]
  if (!item) return
  try {
    let prod: any = null
    const raw = (item.materialId ?? '').toString().trim()
    if (!raw) {
      item.matched = false
      item.materialCode = ''
      item.materialName = ''
      item.unit = ''
      return
    }

    const asNumber = Number(raw)
    if (Number.isInteger(asNumber) && asNumber > 0) {
      // 数字：按 ID 匹配
      prod = productOptions.value.find((p: any) => p.id === asNumber)
      if (!prod) {
        prod = await ProductApi.getProduct(asNumber)
      }
      if (prod) {
        item.materialId = asNumber
        item.matched = true
        item.materialCode = prod?.barCode || ''
        item.materialName = prod?.name || ''
        item.unit = prod?.unitName || ''
        return
      }
    }

    // 非纯数字：尝试按条码或名称匹配
    prod = productOptions.value.find(
      (p: any) => p.barCode === raw || p.name === raw || (p.barCode && p.barCode.includes(raw))
    )
    if (prod) {
      item.materialId = prod.id
      item.matched = true
      item.materialCode = prod?.barCode || ''
      item.materialName = prod?.name || ''
      item.unit = prod?.unitName || ''
    } else {
      // 未匹配：使用用户输入作为物料编码，清空名称与单位，允许手动填写
      item.matched = false
      item.materialId = raw
      item.materialCode = raw
      item.materialName = ''
      item.unit = ''
    }
  } catch (e) {
    console.error('获取产品详情失败', e)
  }
}



// 打开过磅单选择弹窗
const handleSelectWeigh = (index: number) => {
  currentSelectIndex.value = index
  weighSelectDialogVisible.value = true
  // 重置搜索条件并加载数据
  weighSearchForm.no = ''
  weighSearchForm.productName = ''
  weighPagination.pageNo = 1
  loadWeighSelectList()
}

// 加载过磅单选择列表
const loadWeighSelectList = async () => {
  try {
    formLoading.value = true
    const params = {
      pageNo: weighPagination.pageNo,
      pageSize: weighPagination.pageSize,
      inStatus: 1, // 只显示已入库的过磅单
      ...(weighSearchForm.no && { no: weighSearchForm.no }),
      ...(weighSearchForm.productName && { productName: weighSearchForm.productName })
    }

    const res: any = await WeighApi.getWeighPage(params)
    // 兼容不同返回结构
    weighSelectList.value = res?.list || res?.data?.list || []
    weighPagination.total = res?.total || res?.data?.total || 0
  } catch (e) {
    console.error('加载过磅单列表失败', e)
    ElMessage.error('加载过磅单列表失败')
  } finally {
    formLoading.value = false
  }
}

// 搜索过磅单
const handleWeighSearch = () => {
  weighPagination.pageNo = 1
  loadWeighSelectList()
}

// 重置搜索条件
const handleWeighReset = () => {
  weighSearchForm.no = ''
  weighSearchForm.productName = ''
  weighPagination.pageNo = 1
  loadWeighSelectList()
}

// 分页变化
const handleWeighPageChange = (page: number) => {
  weighPagination.pageNo = page
  loadWeighSelectList()
}

const handleWeighPageSizeChange = (size: number) => {
  weighPagination.pageSize = size
  weighPagination.pageNo = 1
  loadWeighSelectList()
}

// 行点击选择
const handleWeighRowSelect = (row: any) => {
  handleWeighSelect(row)
}

// 选择过磅单
const handleWeighSelect = (row: any) => {
  if (currentSelectIndex.value >= 0) {
    // 判断是在主表单还是确认领料弹窗中
    if (formData.value.items.length > currentSelectIndex.value) {
      const item = formData.value.items[currentSelectIndex.value]
      item.no = row.no
      item.purchaseId = row.id
      // 保存过磅单的剩余重量信息，用于后续扣减
      item.weighRemainingWeight = row.remainingWeight

      // 可选：同时填充相关信息，如产品信息
      if (row.productName && !item.materialName) {
        item.materialName = row.productName
      }
    } else if (completeFormData.value.items.length > currentSelectIndex.value) {
      const item = completeFormData.value.items[currentSelectIndex.value]
      item.no = row.no
      item.purchaseId = row.id
      // 保存过磅单的剩余重量信息，用于后续扣减
      item.weighRemainingWeight = row.remainingWeight
    }
  }

  weighSelectDialogVisible.value = false
  ElMessage.success('选择过磅单成功')
}

// 确认领料弹窗中选择过磅单
const handleCompleteSelectWeigh = (index: number) => {
  currentSelectIndex.value = index
  weighSelectDialogVisible.value = true
  // 重置搜索条件并加载数据
  weighSearchForm.no = ''
  weighSearchForm.productName = ''
  weighPagination.pageNo = 1
  loadWeighSelectList()
}

const handleViewWeigh = async ($index: number) => {
  const item = formData.value.items[$index]
  if (!item?.purchaseId) {
    ElMessage.warning('未关联过磅单')
    return
  }
  try {
    formLoading.value = true
    const res: any = await WeighApi.getWeigh(item.purchaseId)
    weighDetail.value = res?.data || res
    weighDialogVisible.value = true
  } catch (e) {
    console.error('获取过磅单详情失败', e)
    ElMessage.error('获取过磅单详情失败')
  } finally {
    formLoading.value = false
  }
}

// 打开工单选择弹窗
const handleSelectWorkOrder = () => {
  workOrderSelectDialogVisible.value = true
  // 重置搜索条件并加载数据
  workOrderSearchForm.code = ''
  workOrderSearchForm.name = ''
  workOrderSearchForm.status = [2,3]
  workOrderPagination.pageNo = 1
  loadWorkOrderSelectList()
}

// 加载工单选择列表
const loadWorkOrderSelectList = async () => {
  try {
    formLoading.value = true
    const params = {
      pageNo: workOrderPagination.pageNo,
      pageSize: workOrderPagination.pageSize,
      ...(workOrderSearchForm.code && { code: workOrderSearchForm.code }),
      ...(workOrderSearchForm.name && { name: workOrderSearchForm.name }),
      ...(workOrderSearchForm.status && { status: workOrderSearchForm.status })
    }

    const res: any = await YVHgetWorkOrderPage(params)
    // 兼容不同返回结构
    workOrderSelectList.value = res?.list || res?.data?.list || []
    workOrderPagination.total = res?.total || res?.data?.total || 0
  } catch (e) {
    console.error('加载工单列表失败', e)
    ElMessage.error('加载工单列表失败')
  } finally {
    formLoading.value = false
  }
}

// 搜索工单
const handleWorkOrderSearch = () => {
  workOrderPagination.pageNo = 1
  loadWorkOrderSelectList()
}

// 重置搜索条件
const handleWorkOrderReset = () => {
  workOrderSearchForm.code = ''
  workOrderSearchForm.name = ''
  workOrderSearchForm.status = [] as number[]
  workOrderPagination.pageNo = 1
  loadWorkOrderSelectList()
}

// 分页变化
const handleWorkOrderPageChange = (page: number) => {
  workOrderPagination.pageNo = page
  loadWorkOrderSelectList()
}

const handleWorkOrderPageSizeChange = (size: number) => {
  workOrderPagination.pageSize = size
  workOrderPagination.pageNo = 1
  loadWorkOrderSelectList()
}

// 行点击选择
const handleWorkOrderRowSelect = (row: any) => {
  handleWorkOrderSelect(row)
}

// 选择工单
const handleWorkOrderSelect = (row: any) => {
  formData.value.orderCode = row.code || String(row.id)
  formData.value.orderId = row.id
  // 自动设置领料编号与工单号相同
  formData.value.code = formData.value.orderCode

  workOrderSelectDialogVisible.value = false
  ElMessage.success('选择工单成功')
}

// 工单状态相关函数
const getWorkOrderStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '草稿',
    1: '待审核',
    2: '已审核',
    3: '生产中',
    4: '已完成',
    5: '已关闭',
    6: '已取消',
    7: '已入库'
  }
  return statusMap[status] || '未知'
}

const getWorkOrderStatusType = (status: number) => {
  const typeMap: Record<number, 'info' | 'warning' | 'primary' | 'success' | 'danger'> = {
    0: 'info',      // 草稿 - 灰色
    1: 'warning',   // 待审核 - 黄色
    2: 'primary',   // 已审核 - 蓝色
    3: 'primary',   // 生产中 - 蓝色
    4: 'success',   // 已完成 - 绿色
    5: 'info',      // 已关闭 - 灰色
    6: 'danger',    // 已取消 - 红色
    7: 'success'    // 已入库 - 绿色
  }
  return typeMap[status] || 'info'
}



const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增领料单' : '修改领料单'
  formType.value = type

  // 重置表单数据
  formData.value = JSON.parse(JSON.stringify(defaultFormData))

  // 加载产品下拉
  if (!productOptions.value.length) await loadProductOptions()
  // 加载仓库下拉
  if (!warehouseOptions.value.length) await loadWarehouseOptions()
  // 加载BOM下拉
  if (!bomOptions.value.length) await loadBomOptions()
  // 重置BOM选择
  selectedBomId.value = undefined


  // 修改时获取详情
  if (type === 'update' && id) {
    formLoading.value = true
    try {
      const result = await MaterialRequisitionApi.getMaterialRequisition(id)
      console.log('获取到的详情数据:', result)

      // 直接使用返回的数据，不需要 .data
      if (result) {
        // 确保所有必要字段都存在
        formData.value = {
          id: result.id,
          code: result.code || '',
          orderCode: result.orderCode || '',
          orderId: result.orderId,
          requisitionTime: result.requisitionTime || '',
          status: result.status || 0,
          applicantId: result.applicantId,
          applicantName: result.applicantName || '',
          remark: result.remark || '',
          items: Array.isArray(result.items)
            ? result.items.map((item) => ({
                id: item.id,
                materialId: item.materialId,
                materialCode: item.materialCode || '',
                materialName: item.materialName || '',
                unit: item.unit || '',
                planQuantity: item.planQuantity || 0,
                warehouseId: item.warehouseId,
                warehouseName: item.warehouseName || '',
                no: item.no || '',
                purchaseId: item.purchaseId,
                remark: item.remark || ''
              }))
            : []
        }
      }
    } catch (error) {
      console.error('获取领料单详情失败:', error)
      ElMessage.error('获取领料单详情失败')
    } finally {
      formLoading.value = false
    }
  }
}

const openComplete = async (id: number) => {
  completeDialogVisible.value = true
  completeFormData.value = {
    id,
    items: []
  }

  // 确保仓库选项已加载
  if (!warehouseOptions.value.length) await loadWarehouseOptions()

  formLoading.value = true
  try {
    const result = await MaterialRequisitionApi.getMaterialRequisition(id)
    console.log('获取到的确认领料数据:', result)

    // 直接使用返回的数据，不需要 .data
    if (result && Array.isArray(result.items)) {
      completeFormData.value = {
        id,
        items: result.items.map((item: any) => {
          // 确保仓库名称正确回显
          let warehouseName = item.warehouseName || ''
          if (!warehouseName && item.warehouseId && warehouseOptions.value.length > 0) {
            const warehouse = warehouseOptions.value.find((w: any) => w.id === item.warehouseId)
            warehouseName = warehouse ? warehouse.name : ''
          }

          return {
            id: item.id,
            materialId: item.materialId,
            materialCode: item.materialCode,
            materialName: item.materialName,
            unit: item.unit,
            warehouseId: item.warehouseId,
            warehouseName: warehouseName,
            actualQuantity: item.planQuantity || 0,
            no: item.no || '',
            purchaseId: item.purchaseId,
            weighRemainingWeight: item.weighRemainingWeight,
            remark: item.remark || ''
          }
        })
      }
    }
  } catch (error) {
    console.error('获取领料单详情失败:', error)
    ElMessage.error('获取领料单详情失败')
    completeDialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

const handleAddItem = () => {
  const newItem: MaterialRequisitionItem = {
    materialId: '',
    materialCode: '',
    materialName: '',
    unit: '',
    planQuantity: 0,
    warehouseId: 0,
    warehouseName: '',
    remark: '',
    matched: false,
    no: '',
    purchaseId: undefined
  }
  // 默认设置为仓库列表第一个
  if (warehouseOptions.value.length > 0) {
    const first = warehouseOptions.value[0]
    newItem.warehouseId = first.id
    newItem.warehouseName = first.name
  }
  formData.value.items.push(newItem)
}

const handleDeleteItem = (index: number) => {
  formData.value.items.splice(index, 1)
}



const submitForm = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    formLoading.value = true

    // 提交数据
    const func =
      formType.value === 'create'
        ? MaterialRequisitionApi.createMaterialRequisition
        : MaterialRequisitionApi.updateMaterialRequisition

    // 检查表单数据
    console.log('提交的表单数据:', formData.value)

    const result = await func(formData.value)
    console.log('提交结果:', result)

    dialogVisible.value = false
    emit('success')
    ElMessage.success(formType.value === 'create' ? '新增成功' : '修改成功')
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  } finally {
    formLoading.value = false
  }
}

const submitCompleteForm = async () => {
  if (!completeFormRef.value) return

  try {
    // 表单验证
    await completeFormRef.value.validate()

    formLoading.value = true

    // 检查表单数据
    console.log('提交的确认领料数据:', completeFormData.value)

    // 确保发送的数据格式正确
    const result = await MaterialRequisitionApi.completeMaterialRequisition({
      id: completeFormData.value.id,
      items: completeFormData.value.items.map((item) => ({
        id: item.id,
        materialCode: item.materialCode,
        warehouseId: item.warehouseId,
        actualQuantity: item.actualQuantity,
        purchaseId: item.purchaseId,
        no: item.no,
        weighRemainingWeight: item.weighRemainingWeight,
        remark: item.remark
      }))
    })
    console.log('确认领料结果:', result)

    completeDialogVisible.value = false
    emit('success')
    ElMessage.success('确认领料成功')
  } catch (error) {
    console.error('确认领料失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  } finally {
    formLoading.value = false
  }
}

defineExpose({
  open,
  openComplete
})
</script>
