<template>
  <div class="app-container">
    <!-- 左上角按钮容器 -->
    <div class="buttons-container">
      <el-button
        type="primary"
        :disabled="formLoading || isFormDisabled"
        plain
        size="mini"
        @click="submitForm"
        >保 存</el-button
      >
      <!-- 提交菜单 -->
      <el-dropdown class="ml-5" trigger="click">
        <el-button type="primary" size="mini" plain>
          提交菜单
          <i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            :disabled="isButtonDisabled('commit')"
            @click.native="commit"
            >提交</el-dropdown-item
          >
          <el-dropdown-item
            :disabled="isButtonDisabled('cancel')"
            @click.native="cancel"
            >撤销</el-dropdown-item
          >
        </el-dropdown-menu>
      </el-dropdown>

      <!-- 审批菜单 -->
      <el-dropdown class="ml-5 mr-5" trigger="click">
        <el-button type="warning" size="mini" plain>
          审批菜单
          <i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            :disabled="isButtonDisabled('audit')"
            @click.native="audit"
            >审核</el-dropdown-item
          >
          <el-dropdown-item
            :disabled="isButtonDisabled('antiAudit')"
            @click.native="antiAudit"
            >反审核</el-dropdown-item
          >
        </el-dropdown-menu>
      </el-dropdown>
      <el-button
        type="primary"
        plain
        size="mini"
        :disabled="isFormDisabled"
        @click="add()"
        >新增明细</el-button
      >
      <el-button plain size="mini" @click="handleCancel">返 回</el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="明细信息" name="detail">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="dynamicFormRules"
          label-width="150px"
        >
          <el-row :gutter="20">
            <el-col :span="12"
              ><el-form-item label="业务类型" prop="businessType">
                <el-select
                  v-model="formData.businessType"
                  placeholder="请选择业务类型"
                  :disabled="!isEditable"
                  @change="changeBusinessType"
                >
                  <el-option
                    v-for="dict in getDictDatas('inout_business_type')"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="申请单号" prop="remark">
                <el-input
                  v-model="formData.requestNo"
                  :disabled="true"
                  placeholder="保存后自动生成"
                /> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item :label="getDeptLabel" prop="deptCode">
                <DepartMentSelect
                  ref="departMentSelect"
                  v-model="formData.deptCode"
                  :disabled="isFormDisabled || formData.businessType == null"
                  :placeholder="getDeptPlaceholder"
                  clearable
                  @change="selectDepart"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12"
              ><el-form-item label="业务分类名称" prop="businessDescribe">
                <el-select
                  v-model="formData.businessDescribe"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  filterable
                  placeholder="请选择业务类型"
                  @change="changeBusinessDescribe"
                >
                  <el-option
                    v-for="dict in businessDescribeList"
                    :key="dict.label"
                    :label="dict.label"
                    :value="dict.label"
                  />
                </el-select> </el-form-item
            ></el-col>

            <el-col :span="12"
              ><el-form-item label="优先级" prop="priority">
                <el-select
                  v-model="formData.priority"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  placeholder="请选择优先级"
                >
                  <el-option
                    v-for="dict in getDictDatas('priority')"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商编码" prop="supplierCode">
                <el-select
                  v-model="formData.supplierCode"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  placeholder="请选择供应商编码"
                  clearable
                  filterable
                  :filter-method="filterSupplier"
                >
                  <el-option
                    v-for="item in supplierOptions"
                    :key="item.code"
                    :label="`${item.code}  ${item.name}`"
                    :value="item.code"
                  >
                    <span style="display: inline-block; width: 120px">{{
                      item.code
                    }}</span>
                    <span style="color: #8492a6; font-size: 13px">{{
                      item.name
                    }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户编码" prop="customerCode">
                <el-select
                  v-model="formData.customerCode"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  placeholder="请选择客户编码"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in customerList"
                    :key="item.erpId"
                    :label="`${item.code} ${item.name || ''}`"
                    :value="item.code"
                  />
                  <!-- <el-option
                    v-for="item in customerList"
                    :key="item.code"
                    :value="item.code"
                  >
                    <span style="display: inline-block; width: 120px">{{
                      item.code
                    }}</span>
                    <span>{{ item.name }}</span>
                  </el-option> -->
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="源单编号" prop="sourceOrderNo">
                <el-select
                  v-model="formData.sourceOrderNo"
                  filterable
                  remote
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  reserve-keyword
                  placeholder="请输入源单编号"
                  :remote-method="remoteMethod"
                  :loading="loadingSourceOrder"
                  @change="changeSourceOrderNo"
                >
                  <el-option
                    v-for="item in sourceOrderNoList"
                    :key="item.sourceOrderNo"
                    :label="item.sourceOrderNo"
                    :value="item.sourceOrderNo"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="源单编号" prop="sourceOrderNo">
                <el-select
                  v-model="formData.sourceOrderNo"
                  filterable
                  remote
                  :disabled="isFormDisabled || formData.businessType == null"
                  reserve-keyword
                  placeholder="请输入源单编号"
                  :remote-method="remoteMethod"
                  :loading="loadingSourceOrder"
                  clearable
                  @change="changeSourceOrderNo"
                >
                  <el-option
                    v-for="item in sourceOrderNoList"
                    :key="item.sourceOrderNo"
                    :label="item.sourceOrderNo"
                    :value="item.sourceOrderNo"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计出入库时间" prop="expectedTime">
                <el-date-picker
                  v-model="formData.expectedTime"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  clearable
                  type="date"
                  value-format="timestamp"
                  placeholder="选择预计出入库时间"
                /> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="实际出入库时间" prop="actualTime">
                <el-date-picker
                  v-model="formData.actualTime"
                  clearable
                  :disabled="true"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择实际出入库时间"
                /> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  placeholder="请输入备注"
                /> </el-form-item
            ></el-col>
            <!-- <el-col :span="12">
              <el-form-item label="存储地点" prop="warehouseId">
                <el-select
                  v-model="formData.warehouseId"
                  filterable
                  remote
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  reserve-keyword
                  placeholder="请输入存储地点"
                  :remote-method="remoteWarehouse"
                  :loading="loadingWarehouse"
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.erpId"
                    :label="item.name"
                    :value="item.erpId"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item :label="getWarehouseLabel" prop="warehouseId">
                <el-select
                  v-model="formData.warehouseId"
                  :disabled="isFormDisabled || formData.businessType == null"
                  placeholder="请选择仓库"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.erpId"
                    :label="item.name"
                    :value="item.erpId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="formData.businessType === '13'" :span="12">
              <el-form-item label="调入区域" prop="areaCode">
                <el-select
                  v-model="formData.areaCode"
                  :disabled="isFormDisabled || formData.businessType == null"
                  filterable
                  placeholder="请输入调入区域"
                  clearable
                >
                  <el-option
                    v-for="item in areaList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.areaCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="formData.businessType === '13'" :span="12">
              <el-form-item label="调入货位" prop="locationCode">
                <el-select
                  v-model="formData.locationCode"
                  :disabled="isFormDisabled || formData.businessType == null"
                  filterable
                  placeholder="请输入调入货位"
                  clearable
                >
                  <el-option
                    v-for="item in locationList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.locationCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status" aria-disabled="true">
                <el-select
                  v-model="formData.status"
                  disabled
                  placeholder="请选择状态"
                >
                  <el-option
                    v-for="dict in getDictDatas('in_out_status')"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="text-right">
              <el-button
                type="primary"
                plain
                style="width: 60%"
                icon="el-icon-upload2"
                @click="handleUpload"
                >附件上传</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <!-- <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="明细信息" name="detail"> -->
        <el-table :data="formData.list" border size="mini">
          <el-table-column
            label="源单编号"
            align="center"
            prop="sourceRequestId"
            width="160"
            show-overflow-tooltip
          />
          <el-table-column
            label="源单行号"
            align="center"
            prop="sourceLineNo"
            width="160"
            show-overflow-tooltip
          />
          <el-table-column
            label="物料编码"
            align="center"
            prop="materialNo"
            width="200"
            show-overflow-tooltip
          >
            <template v-slot="scope">
              <el-select
                v-model="scope.row.materialNo"
                filterable
                remote
                reserve-keyword
                :disabled="isFormDisabled"
                placeholder="请选择物料编码"
                :remote-method="
                  (query) => remoteMaterialSearch(query, 'code', scope.$index)
                "
                :loading="loadingMaterial"
                @change="(value) => changeMaterial(value, scope.$index, 'code')"
              >
                <el-option
                  v-for="item in materialNoList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="物料名称"
            align="center"
            prop="materialName"
            width="200"
            show-overflow-tooltip
          >
            <template v-slot="scope">
              <el-select
                v-model="scope.row.materialName"
                filterable
                remote
                reserve-keyword
                :disabled="isFormDisabled"
                placeholder="请选择物料名称"
                :remote-method="
                  (query) => remoteMaterialSearch(query, 'name', scope.$index)
                "
                :loading="loadingMaterial"
                @change="(value) => changeMaterial(value, scope.$index, 'name')"
              >
                <el-option
                  v-for="item in materialNameList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="客户编码"
            align="center"
            prop="customerCode"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            label="客户名称"
            align="center"
            prop="customerName"
            width="160"
            show-overflow-tooltip
          />
          <el-table-column
            label="存储地点"
            align="center"
            prop="locationName"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            label="合格类型"
            align="center"
            prop="qcType"
            width="160"
            show-overflow-tooltip
          />
          <el-table-column
            label="退扣数量"
            align="center"
            prop="returnDeductQty"
            width="160"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.returnDeductQty"
                :disabled="isFormDisabled"
                @change="(val) => calculateNowDeliveredQty(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="退补数量"
            align="center"
            prop="returnSupplyQty"
            width="160"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.returnSupplyQty"
                :disabled="isFormDisabled"
                @change="(val) => calculateNowDeliveredQty(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="本次申请数量"
            align="center"
            prop="nowDeliveredQty"
            width="160"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.nowDeliveredQty"
                :disabled="isFormDisabled"
                @change="deliverChange"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="已出库数量"
            align="center"
            prop="completedQty"
            width="120"
          />
          <el-table-column
            label="源单计划数量"
            align="center"
            prop="planQty"
            width="120"
          />
          <el-table-column
            label="单位"
            align="center"
            prop="unitName"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            label="行备注"
            align="center"
            prop="remark"
            width="200"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :disabled="isFormDisabled" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="150px"
            class-name="small-padding fixed-width"
          >
            <template v-slot="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                :disabled="isFormDisabled"
                @click="handleDelete(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="审批任务" name="approvalTask" lazy>
        <ApprovalTask
          v-if="
            activeName === 'approvalTask' &&
            formData.bpmInstanceId !== null &&
            formData.bpmInstanceId !== undefined
          "
          :id="formData.bpmInstanceId"
        />
        <div v-else class="isNotApproval">暂未开启工作流</div>
      </el-tab-pane>
    </el-tabs>
    <!-- 移除原有的form-footer -->
    <!-- 附件上传 -->
    <AttachmentUpload ref="attachmentUpload" @files="getFileList" />
  </div>
</template>

<script>
import * as InRequestApi from "@/api/wms/output/inrequest";
import DepartMentSelect from "./DepartMentSelect.vue";
import AttachmentUpload from "../../../../wms/incoming/register/components/AttachmentUpload.vue";
// 审批任务
import ApprovalTask from "../../../../wms/quality/iqcInspection/components/ApprovalTaskNew.vue";
// import ShipmentNotification from "./ShipmentNotification.vue";
export default {
  name: "OutRequestForm",
  components: {
    // ShipmentNotification,
    DepartMentSelect,
    ApprovalTask,
    AttachmentUpload,
  },
  data() {
    return {
      activeName: "detail",
      materialNameList: [],
      materialNoList: [],
      sourceOrderNoList: [],
      allSourceOrderNoList: [],
      supplierList: [],
      supplierOptions: [],
      customerList: [],
      businessDescribeList: [],
      warehouseList: [],
      loadingMaterial: false,
      loadingSourceOrder: false,
      loadingWarehouse: false,
      loadingArea: false,
      loadingLocation: false,
      areaList: [],
      locationList: [],
      uploadFiles: [], // 上传的文件
      // 页面标题
      dialogTitle: "",
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 记录当前业务类型下选中的业务分类名称
      selectedBusinessDescribe: "",
      // 保存当前选中的业务类型整行字典数据
      currentBusinessTypeRow: null,
      // 保存当前选中的业务分类整行数据
      currentBusinessDescribeRow: null,
      // 表单参数
      formData: {
        departmentNo: undefined,
        deptCode: undefined,
        deptName: undefined,
        id: undefined,
        requestNo: undefined,
        requestType: undefined,
        businessType: undefined,
        businessCategory: undefined,
        businessDescribe: undefined,
        businessSubType: undefined,
        status: undefined,
        priority: undefined,
        warehouseId: undefined,
        relatedWarehouseId: undefined,
        supplierCode: undefined,
        customerCode: undefined,
        sourceOrderNo: undefined,
        expectedTime: undefined,
        actualTime: undefined,
        totalQty: undefined,
        totalSku: undefined,
        totalLine: undefined,
        remark: undefined,
        extendInfo: undefined,
        submitter: undefined,
        submitTime: undefined,
        auditor: undefined,
        auditTime: undefined,
        erpWriteFlag: undefined,
        erpErrMsg: undefined,
        erpBackId: undefined,
        list: [],
        bpmInstanceId: undefined,
        areaCode: undefined,
        locationCode: undefined,
      },
      // 表单校验
      formRules: {
        deptCode: [{ required: true, message: "请选择部门", trigger: "blur" }],
        requestNo: [
          { required: true, message: "申请单号不能为空", trigger: "blur" },
        ],
        expectedTime: [
          { required: true, message: "预计入库时间不能为空", trigger: "blur" },
        ],
        requestType: [
          {
            required: true,
            message: "申请类型不能为空",
            trigger: "change",
          },
        ],
        businessType: [
          {
            required: true,
            message: "业务类型不能为空",
            trigger: "change",
          },
        ],
        businessSubType: [
          {
            required: true,
            message: "业务子类型不能为空",
            trigger: "change",
          },
        ],
        priority: [
          {
            required: true,
            message: "优先级不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    // 判断表单是否不可编辑：路径有id且status>=1
    isFormDisabled() {
      // 检查是否有id（编辑模式）且status>=1
      return this.formData.status && Number(this.formData.status) >= 1;
    },
    // 计算属性判断修改状态下是否可编辑
    isEditable() {
      // 有 id 表示是编辑模式，不可编辑
      // 没有 id 表示是新增模式，可编辑
      return (
        this.formData.id === undefined ||
        this.formData.id === null ||
        this.formData.id === ""
      );
    },
    // 动态获取地点标签
    getWarehouseLabel() {
      const businessType = this.formData.businessType;
      if (businessType === "13") {
        return "调入仓库";
      }
      return "存储地点";
    },
    // 动态获取部门标签
    getDeptLabel() {
      const businessType = this.formData.businessType;
      if (businessType === "2") {
        // 生产领料
        return "发料部门";
      }
      return "部门";
    },
    // 动态获取部门占位符
    getDeptPlaceholder() {
      const businessType = this.formData.businessType;
      if (businessType === "2") {
        // 生产领料
        return "请选择发料部门";
      }
      return "请选择部门";
    },
    // 动态生成表单验证规则
    dynamicFormRules() {
      // 从原始规则中只保留基础字段
      const baseRules = {
        businessType: this.formRules.businessType,
        priority: this.formRules.priority,
        expectedTime: this.formRules.expectedTime,
      };

      const rules = { ...baseRules };
      const businessType = this.formData.businessType;

      // 只有选择了业务类型后，才添加其他字段的验证规则
      if (businessType) {
        // 生产领料(2)需要的必填字段
        if (businessType === "2") {
          rules.deptCode = [
            {
              required: true,
              message: this.getDeptLabel + "不能为空",
              trigger: "blur",
            },
          ];
          rules.businessDescribe = [
            {
              required: true,
              message: "业务分类名称不能为空",
              trigger: "blur",
            },
          ];
          rules.sourceOrderNo = [
            { required: true, message: "源单编号不能为空", trigger: "blur" },
          ];
          rules.warehouseId = [
            { required: true, message: "存储地点不能为空", trigger: "blur" },
          ];
        }
        // 采购退料(1)需要的必填字段
        else if (businessType === "1") {
          // rules.deptCode = [
          //   { required: true, message: "部门不能为空", trigger: "blur" },
          // ];
          rules.businessDescribe = [
            {
              required: true,
              message: "业务分类名称不能为空",
              trigger: "blur",
            },
          ];
          rules.supplierCode = [
            { required: true, message: "供应商不能为空", trigger: "blur" },
          ];
          rules.sourceOrderNo = [
            { required: true, message: "源单编号不能为空", trigger: "blur" },
          ];
          rules.warehouseId = [
            { required: true, message: "存储地点不能为空", trigger: "blur" },
          ];
        }
        // 其他出库(12)需要的必填字段
        else if (businessType === "12") {
          // rules.deptCode = [
          //   { required: true, message: "部门不能为空", trigger: "blur" },
          // ];
          rules.businessDescribe = [
            {
              required: true,
              message: "业务分类名称不能为空",
              trigger: "blur",
            },
          ];
          rules.warehouseId = [
            { required: true, message: "存储地点不能为空", trigger: "blur" },
          ];
        } else if (businessType === "13") {
          rules.warehouseId = [
            { required: true, message: "调入仓库不能为空", trigger: "blur" },
          ];
          rules.areaCode = [
            { required: true, message: "调入区域不能为空", trigger: "blur" },
          ];
          rules.locationCode = [
            { required: true, message: "调入货位不能为空", trigger: "blur" },
          ];
        }
      }

      return rules;
    },
  },
  watch: {
    "$route.query.id": {
      immediate: true,
      handler(newId, oldId) {
        // 只有当前路由路径包含"/outStorageManage/inrequest/InRequestForm"时才处理，避免标签跳转时错误调用API
        if (
          this.$route.path.includes("/outStorageManage/inrequest/InRequestForm")
        ) {
          // 只有当id变化时才执行操作，避免不必要的重复调用
          if (newId !== oldId) {
            if (newId) {
              this.dialogTitle = "修改";
              this.open(newId);
            } else {
              this.dialogTitle = "新增";
              this.reset();
            }
          }
        }
      },
    },
    // 监听仓库选择变化，获取对应区域列表
    "formData.warehouseId": {
      handler(newVal, oldVal) {
        if (this.formData.businessType === "13" && newVal) {
          this.loadAreaList(newVal);
          // 第一次 oldVal 为 undefined，认为是初始化，不清空
          if (oldVal === undefined) return;
          // 人工切换仓库
          this.formData.areaCode = undefined;
          this.formData.locationCode = undefined;
          this.locationList = [];
        } else {
          this.areaList = [];
          this.locationList = [];
        }
      },
    },
    // 监听区域选择变化，获取对应货位列表
    "formData.areaCode": {
      handler(newVal, oldVal) {
        if (
          this.formData.businessType === "13" &&
          newVal &&
          this.formData.warehouseId
        ) {
          this.loadLocationList(this.formData.warehouseId, newVal);
          if (oldVal === undefined) return; // 初始化阶段不清空
          this.formData.locationCode = undefined;
        } else {
          this.locationList = [];
        }
      },
    },
  },
  created() {
    // 一次性获取全部仓库
    this.loadWarehouseList();
    // 一次性获取全部供应商
    InRequestApi.getSupplierPage({ pageSize: 9999 }).then(({ data }) => {
      this.supplierList = data.list || [];
      this.supplierOptions = this.supplierList;
    });
    // 一次性获取全部客户编码
    InRequestApi.getCustomerPage({ pageSize: 9999 }).then(({ data }) => {
      this.customerList = data.list || [];
    });
  },
  methods: {
    /* 1. 保证仓库列表就位 */
    async loadWarehouseList() {
      if (this.warehouseList.length) return; // 已经拿过
      const { data } = await InRequestApi.getStockPage({ pageSize: 9999 });
      this.warehouseList = data.list || [];
    },
    // 通用的判断函数判断按钮是否可点击
    isButtonDisabled(buttonType) {
      const status = Number(this.formData.status);

      switch (buttonType) {
        case "commit":
          return status !== 0; // 提交，status=0时可点击
        case "cancel":
          return status !== 1; // 撤销，status=1时可点击
        case "audit":
          return status !== 1; // 审核，status=1时可点击
        case "antiAudit":
          return status < 2; // 反审核，status>=2时可点击
        default:
          return true;
      }
    },
    handleDelete(row) {
      console.log(row);
      this.formData.list.splice(row.$index, 1);
    },
    selectDepart(item) {
      this.formData.deptCode = item.code;
      this.formData.deptName = item.name;
    },
    remoteMaterialSearch(query, type, index) {
      if (query) {
        this.loadingMaterial = true;
        setTimeout(async () => {
          try {
            const params = {};
            if (type === "code") {
              params.code = query;
            } else {
              params.name = query;
            }
            const {
              data: { list },
            } = await InRequestApi.getMaterialPage(params);

            // 每次搜索都重新赋值，保证列表始终是最新数据
            if (type === "code") {
              this.materialNoList = list || [];
            } else {
              this.materialNameList = list || [];
            }
          } catch (error) {
            console.error("搜索物料失败:", error);
            // 出错时清空列表
            if (type === "code") {
              this.materialNoList = [];
            } else {
              this.materialNameList = [];
            }
          } finally {
            this.loadingMaterial = false;
          }
        }, 200);
      } else {
        // 清空对应的列表
        if (type === "code") {
          this.materialNoList = [];
        } else {
          this.materialNameList = [];
        }
      }
    },
    add() {
      if (!this.formData.businessType) {
        return this.$message.error("请先选择业务类型");
      }
      this.formData.list = this.formData.list || [];
      this.formData.list.push({});
    },
    changeMaterial(value, index, type) {
      // 根据选择的类型获取对应的列表
      const list =
        type === "code" ? this.materialNoList : this.materialNameList;

      // 查找选中的物料信息
      let selectedMaterial = null;
      if (type === "code") {
        selectedMaterial = list.find((item) => item.code === value);
        // 如果在当前列表找不到，尝试从另一个列表找
        if (!selectedMaterial) {
          selectedMaterial = this.materialNameList.find(
            (item) => item.code === value
          );
        }
      } else {
        selectedMaterial = list.find((item) => item.name === value);
        // 如果在当前列表找不到，尝试从另一个列表找
        if (!selectedMaterial) {
          selectedMaterial = this.materialNoList.find(
            (item) => item.name === value
          );
        }
      }

      if (selectedMaterial) {
        // 更新表单中的物料信息
        const newRow = {
          ...this.formData.list[index],
          materialNo: selectedMaterial.code,
          materialName: selectedMaterial.name,
          unitName: selectedMaterial.unit || "",
        };

        // 更新行数据
        this.$set(this.formData.list, index, newRow);
      }
    },
    // 本地过滤
    // remoteMethod(query) {
    //   if (query !== "") {
    //     this.sourceOrderNoList = this.allSourceOrderNoList.filter((item) =>
    //       item.sourceOrderNo.toLowerCase().includes(query.toLowerCase())
    //     );
    //   } else {
    //     this.sourceOrderNoList = this.allSourceOrderNoList;
    //   }
    // },
    remoteMethod(query) {
      if (!query) {
        // 清空：恢复全部
        this.sourceOrderNoList = this.allSourceOrderNoList;
      } else if (query.length <= 4) {
        // 1-4个字符：本地过滤
        this.sourceOrderNoList = this.allSourceOrderNoList.filter((item) =>
          item.sourceOrderNo.toLowerCase().includes(query.toLowerCase())
        );
      } else {
        // 超过4个字符：远程搜索
        this.loading = true;
        InRequestApi.getSourceOrder({
          businessType: this.formData.businessType,
          businessDescribe: this.selectedBusinessDescribe,
          businessCategory: this.currentBusinessDescribeRow?.value,
          sourceOrderNo: query,
          pageSize: 100,
        })
          .then(({ data }) => {
            this.sourceOrderNoList = data || [];
          })
          .catch(() => {
            this.sourceOrderNoList = [];
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    // 远程搜索调入区域
    remoteAreaSearch(query) {
      if (query !== "") {
        this.loadingArea = true;
        setTimeout(async () => {
          try {
            const {
              data: { list },
            } = await InRequestApi.getStockAreaPage({
              areaName: query,
              pageSize: 999,
            });
            this.areaList = list || [];
          } catch (error) {
            console.error("搜索调入区域失败:", error);
            this.areaList = [];
          } finally {
            this.loadingArea = false;
          }
        }, 200);
      } else {
        this.areaList = [];
      }
    },
    // 加载区域列表
    async loadAreaList(warehouseId) {
      this.loadingArea = true;
      try {
        // 通过erpId找到仓库的完整数据
        console.log("warehouseList的长度", this.warehouseList.length);
        const warehouseRow = this.warehouseList.find(
          (w) => w.erpId === warehouseId
        );
        // 获取仓库的id
        const wmsStockId = warehouseRow ? warehouseRow.id : warehouseId;
        const {
          data: { list },
        } = await InRequestApi.getStockAreaPage({
          wmsStockId: wmsStockId,
          pageSize: 9999,
        });
        this.areaList = list || [];
      } catch (error) {
        console.error("加载区域列表失败:", error);
        this.areaList = [];
      } finally {
        this.loadingArea = false;
      }
    },
    // 加载货位列表
    async loadLocationList(warehouseId, areaCode) {
      this.loadingLocation = true;
      try {
        // 通过areaCode找到区域的完整数据
        const area = this.areaList.find((w) => w.areaCode === areaCode);
        // 获取区域的id
        const wmsStockAreaId = area ? area.id : areaCode;

        const {
          data: { list },
        } = await InRequestApi.getStockLocationPage({
          wmsStockAreaId: wmsStockAreaId,
          pageSize: 9999,
        });
        this.locationList = list || [];
      } catch (error) {
        console.error("加载货位列表失败:", error);
        this.locationList = [];
      } finally {
        this.loadingLocation = false;
      }
    },
    // remoteWarehouse(query) {
    //   if (query !== "") {
    //     const that = this;
    //     this.loadingWarehouse = true;
    //     setTimeout(async () => {
    //       this.loadingWarehouse = false;
    //       const {
    //         data: { list },
    //       } = await InRequestApi.getStockPage({
    //         name: query,
    //         pageSize: 999,
    //       });
    //       this.warehouseList = list || [];
    //     }, 200);
    //   } else {
    //     this.warehouseList = [];
    //   }
    // },
    // changeSourceOrderNo(value) {
    //   this.sourceOrderNoList.map((v) => {
    //     if (v.sourceOrderNo == value) {
    //       this.formData.list = v.list;
    //     }
    //   });
    // },
    changeSourceOrderNo(value) {
      (this.sourceOrderNoList || []).forEach((v) => {
        if (v.sourceOrderNo === value) {
          this.formData.list = v.list || [];
        }
      });
    },
    // changeBusinessDescribe(e) {
    //   this.businessDescribeList.map((v) => {
    //     if (v.label == e) {
    //       this.formData.businessCategory = v.value;
    //     }
    //   });
    // },
    async changeBusinessDescribe(e) {
      // 1. 找到并存储选中的业务分类整行数据
      const selectedRow =
        (this.businessDescribeList || []).find((v) => v.label === e) || {};
      this.currentBusinessDescribeRow = selectedRow;

      // 2. 设置业务分类值
      if (selectedRow) {
        this.formData.businessCategory = selectedRow.value;
      }

      // 3. 记录选中的名称
      this.selectedBusinessDescribe = e;

      // 4. 调用源单接口
      if (this.formData.businessType && this.selectedBusinessDescribe) {
        this.loadingSourceOrder = true;
        try {
          const { data } = await InRequestApi.getSourceOrder({
            businessType: this.formData.businessType,
            businessDescribe: this.selectedBusinessDescribe,
            businessCategory: this.currentBusinessDescribeRow.value,
            id: this.$route.query.id || undefined,
            pageSize: 999,
          });
          this.allSourceOrderNoList = data || [];
          this.sourceOrderNoList = this.allSourceOrderNoList;
        } finally {
          this.loadingSourceOrder = false;
        }
      }
    },
    async changeBusinessType(value) {
      // 1. 先拿到业务类型对应的整条字典
      const dictRow =
        this.getDictDatas("inout_business_type").find(
          (d) => d.value === value
        ) || {};
      this.currentBusinessTypeRow = dictRow; // 整条数据存起来

      // 2. 原有逻辑保持不变
      this.formData.businessType = value;
      this.formData.businessDescribe = "";
      this.formData.businessCategory = "";
      this.formData.sourceOrderNo = "";
      this.formData.list = [];
      this.sourceOrderNoList = [];
      this.allSourceOrderNoList = [];
      this.selectedBusinessDescribe = "";
      this.currentBusinessDescribeRow = null; // 清空业务分类数据
      this.$nextTick(() => this.$refs.formRef.clearValidate());

      const { data } = await InRequestApi.getDictByOrderType({
        orderType: value,
      });
      this.businessDescribeList = data;
    },
    /** 初始化数据 */
    async open(id) {
      this.reset();
      if (!id) {
        // 新增
        this.dialogTitle = "新增";
        this.formData.list = [];
        return;
      }

      /* ---------- 编辑模式 ---------- */
      this.dialogTitle = "修改";
      this.formLoading = true;
      try {
        /* 1. 先保证仓库就位 */
        await this.loadWarehouseList();

        const res = await InRequestApi.getInRequest(id);
        res.data.businessType = res.data.businessType
          ? res.data.businessType.toString()
          : "0";
        res.data.businessDescribe = res.data.businessDescribe
          ? res.data.businessDescribe.toString()
          : "";
        res.data.priority = res.data.priority
          ? res.data.priority.toString()
          : "0";
        res.data.status = res.data.status ? res.data.status.toString() : "0";
        res.data.areaCode = res.data.areaCode
          ? res.data.areaCode.toString()
          : undefined;
        res.data.locationCode = res.data.locationCode
          ? res.data.locationCode.toString()
          : undefined;
        res.data.list = res.data.list || [];

        /* 4. 补业务分类下拉数据（你原来缺的） */
        if (res.data.businessType) {
          const { data: describeList } = await InRequestApi.getDictByOrderType({
            orderType: res.data.businessType,
          });
          this.businessDescribeList = describeList || [];
        }

        /* 5. ★ 关键：如果后端也返回了业务分类名称，顺手把源单列表拉回来 */
        if (res.data.businessType && res.data.businessDescribe) {
          // 找到当前分类整行，拿 value 字段
          const row = this.businessDescribeList.find(
            (v) => v.label === res.data.businessDescribe
          );
          this.currentBusinessDescribeRow = row || null;

          this.loadingSourceOrder = true;
          try {
            const { data: sourceList } = await InRequestApi.getSourceOrder({
              businessType: res.data.businessType,
              businessDescribe: res.data.businessDescribe,
              businessCategory: row?.value,
              id, // 当前单据 id
              pageSize: 999,
            });
            this.allSourceOrderNoList = sourceList || [];
            this.sourceOrderNoList = this.allSourceOrderNoList;
          } finally {
            this.loadingSourceOrder = false;
          }
        }

        /* 3. 现在仓库列表有了，先加载区域/货位 */
        if (res.data.businessType === "13" && res.data.warehouseId) {
          console.log("开始加载区域列表", res.data.warehouseId);
          await this.loadAreaList(res.data.warehouseId);
          console.log(
            "区域下拉",
            this.areaList.map((i) => i.areaCode)
          );
          if (res.data.areaCode) {
            console.log("开始加载货位列表", res.data.areaCode);
            await this.loadLocationList(
              res.data.warehouseId,
              res.data.areaCode
            );
            console.log(
              "货位下拉",
              this.locationList.map((i) => i.locationCode)
            );
          }
        }

        /* 最后再赋值表单数据 */
        this.formData = res.data;

        this.uploadFiles = res.data.filesListVos;
      } finally {
        this.formLoading = false;
      }
    },
    /** 保存按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        data.list = (data.list || [])
          .filter((v) => v.nowDeliveredQty)
          .map(
            ({
              completedQty,
              actualQty,
              stock_code,
              area_code,
              location_code,
              status,
              lineNo,
              inventory_status,
              ...rest
            }) => rest
          );

        // 上传的附件拼接传给后端
        const fileIds = (this.uploadFiles || [])
          .map((item) => {
            return item.id || item.name?.fileId;
          })
          .filter((id) => id && id !== "");

        // 拼接文件ID
        data.fileId = fileIds.join(",");

        // 只有businessType === "13"时才提交areaCode和locationCode
        if (data.businessType !== "13") {
          delete data.areaCode;
          delete data.locationCode;
        }

        // 修改的提交;
        if (data.id) {
          await InRequestApi.updateInRequest(data);
          this.$modal.msgSuccess("修改成功");
          // 提交成功后刷新数据
          await this.open(data.id);
          // this.$router.back();//修改时停留在当前页面
          return;
        }
        // 添加的提交
        await InRequestApi.createInRequest(data);
        this.$modal.msgSuccess("新增成功");
        this.$router.back();
      } finally {
        this.formLoading = false;
      }
    },
    /** 提交按钮 */
    async commit() {
      // 业务类型为13时，校验调入仓库、区域、货位
      if (this.formData.businessType === "13") {
        if (!this.formData.warehouseId) {
          this.$modal.msgError("调入仓库不能为空");
          return;
        }
        if (!this.formData.areaCode) {
          this.$modal.msgError("调入区域不能为空");
          return;
        }
        if (!this.formData.locationCode) {
          this.$modal.msgError("调入货位不能为空");
          return;
        }
      }
      const menuId = this.$route.meta.id;

      // 只提取需要的字段
      const requestData = {
        id: this.formData.id,
        menuId: menuId,
      };
      // 接口调用
      await InRequestApi.commitOutRequest(requestData);
      this.$modal.msgSuccess("提交成功");
      // 提交成功后刷新数据
      await this.open(this.formData.id);
      // 状态变化
      this.$set(this.formData, "status", "1");

      // 重新获取数据
      const res = await InRequestApi.getInRequest(this.formData.id);
      this.formData.bpmInstanceId = res.data.bpmInstanceId;
    },
    /** 撤销按钮 */
    async cancel() {
      // // 业务类型为13时，校验调入仓库、区域、货位
      // if (this.formData.businessType === "13") {
      //   if (!this.formData.warehouseId) {
      //     this.$modal.msgError("调入仓库不能为空");
      //     return;
      //   }
      //   if (!this.formData.areaCode) {
      //     this.$modal.msgError("调入区域不能为空");
      //     return;
      //   }
      //   if (!this.formData.locationCode) {
      //     this.$modal.msgError("调入货位不能为空");
      //     return;
      //   }
      // }
      const requestData = {
        id: this.formData.id,
      };
      // 接口调用
      await InRequestApi.cancelOutRequest(requestData);
      this.$modal.msgSuccess("撤销成功");
      // 状态变化
      this.$set(this.formData, "status", "0");
    },
    /** 审核按钮 */
    async audit() {
      // 业务类型为13时，校验调入仓库、区域、货位
      if (this.formData.businessType === "13") {
        if (!this.formData.warehouseId) {
          this.$modal.msgError("调入仓库不能为空");
          return;
        }
        if (!this.formData.areaCode) {
          this.$modal.msgError("调入区域不能为空");
          return;
        }
        if (!this.formData.locationCode) {
          this.$modal.msgError("调入货位不能为空");
          return;
        }
      }
      // 检查是否存在工作流实例ID
      if (this.formData.bpmInstanceId) {
        // 如果存在工作流实例，跳转到审批任务tab页
        this.activeName = "approvalTask";
        this.$modal.msgWarning("请在审批任务页面完成审核！");
        return;
      }

      const requestData = {
        id: this.formData.id,
      };
      // 接口调用
      await InRequestApi.auditOutRequest(requestData);
      this.$modal.msgSuccess("审核成功");
      // 状态变化
      this.$set(this.formData, "status", "2");
    },
    /** 反审核按钮 */
    async antiAudit() {
      // // 业务类型为13时，校验调入仓库、区域、货位
      // if (this.formData.businessType === "13") {
      //   if (!this.formData.warehouseId) {
      //     this.$modal.msgError("调入仓库不能为空");
      //     return;
      //   }
      //   if (!this.formData.areaCode) {
      //     this.$modal.msgError("调入区域不能为空");
      //     return;
      //   }
      //   if (!this.formData.locationCode) {
      //     this.$modal.msgError("调入货位不能为空");
      //     return;
      //   }
      // }
      const requestData = {
        id: this.formData.id,
      };
      // 接口调用
      await InRequestApi.antiAuditOutRequest(requestData);
      this.$modal.msgSuccess("反审核成功");
      // 状态变化
      this.$set(this.formData, "status", "0");
    },
    /** 取消按钮 */
    handleCancel() {
      this.reset();
      this.$router.back();
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        requestNo: undefined,
        requestType: undefined,
        businessType: undefined,
        businessCategory: undefined,
        businessDescribe: undefined,
        businessSubType: undefined,
        status: undefined,
        priority: undefined,
        warehouseId: undefined,
        relatedWarehouseId: undefined,
        supplierCode: undefined,
        customerCode: undefined,
        sourceOrderNo: undefined,
        expectedTime: undefined,
        actualTime: undefined,
        totalQty: undefined,
        totalSku: undefined,
        totalLine: undefined,
        remark: undefined,
        extendInfo: undefined,
        submitter: undefined,
        submitTime: undefined,
        auditor: undefined,
        auditTime: undefined,
        erpWriteFlag: undefined,
        erpErrMsg: undefined,
        erpBackId: undefined,
        list: [],
        areaCode: undefined,
        locationCode: undefined,
      };
      this.resetForm("formRef");
    },
    // 标签页切换处理
    handleClick(tab, event) {
      // 可以在这里添加标签切换时的逻辑
      console.log(tab, event);
    },
    deliverChange(val) {
      // 这里可以写“本次出入数量”变化后的校验或计算逻辑
      console.log("deliverChange", val);
    },
    // 计算本次申请数量 = 退补数量 + 退扣数量
    calculateNowDeliveredQty(row) {
      const returnSupplyQty = Number(row.returnSupplyQty) || 0;
      const returnDeductQty = Number(row.returnDeductQty) || 0;
      row.nowDeliveredQty = returnSupplyQty + returnDeductQty;
    },
    // 附件上传
    handleUpload() {
      this.$refs.attachmentUpload.isUploadShow = -1;
      this.$refs.attachmentUpload.title = "上传附件";

      // 直接使用当前组件维护的 uploadFiles，而不是重新获取
      this.$refs.attachmentUpload.fileList = this.uploadFiles || [];

      this.$refs.attachmentUpload.visible = true;
    },
    // 获取上传的附件
    getFileList(data) {
      this.uploadFiles = data;
    },
    // 供应商编码过滤方法
    filterSupplier(keyword) {
      const key = (keyword || "").toLowerCase();
      this.supplierOptions = this.supplierList.filter(
        (item) =>
          item.code.toLowerCase().includes(key) ||
          (item.name && item.name.toLowerCase().includes(key))
      );
    },
  },
};
</script>
<style scoped>
/* 新增按钮容器样式，将所有按钮放在标题下方 */
.buttons-container {
  position: relative;
  display: flex;
  gap: 10px;
  padding: 10px 0;
  margin-bottom: 20px;
}

/* 调整app-header的位置 */
.app-header {
  margin-bottom: 10px;
}
.app-container {
  min-width: 900px;
  margin: 0 auto;
  overflow-x: auto;
}
</style>
