<template>
  <div class="app-container">
    <div class="page-header">
      <div class="header-content">
        <!-- 按钮区域 -->
        <div class="header-buttons">
          <el-button
            type="primary"
            :loading="formLoading"
            plain
            size="mini"
            :disabled="isFormDisabled"
            @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 @click="reset" plain>重置</el-button> -->
          <el-button
            type="primary"
            size="mini"
            plain
            :disabled="isFormDisabled"
            @click="add()"
            >新增明细
          </el-button>
          <el-button plain size="mini" @click="handleCancel">返回</el-button>
        </div>
      </div>
    </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"
          class="form-container"
        >
          <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('in_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 == null"
                  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 == null"
                  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 == null"
                  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 == null"
                  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 == null"
                  reserve-keyword
                  placeholder="请输入源单编号"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @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 v-if="formData.businessType === '9'" :span="12">
              <el-form-item label="扣料仓库" prop="originStockCode">
                <el-select
                  v-model="formData.originStockCode"
                  :disabled="isFormDisabled || formData.businessType == null"
                  placeholder="请选择扣料仓库"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.erpId"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col v-if="formData.businessType === '9'" :span="12">
              <el-form-item label="委外发料单" prop="relatedOrder">
                <el-select
                  v-model="formData.relatedOrder"
                  filterable
                  remote
                  :disabled="isFormDisabled"
                  reserve-keyword
                  placeholder="请输入委外发料单号"
                  :remote-method="remoteRelatedOrder"
                  :loading="loading"
                >
                  <el-option
                    v-for="item in relatedOrderList"
                    :key="item.requestNo"
                    :label="item.requestNo"
                    :value="item.requestNo"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="12">
              <el-form-item label="源单编号" prop="sourceOrderNo">
                <el-select
                  v-model="formData.sourceOrderNo"
                  :disabled="isFormDisabled || formData.businessType == null"
                  placeholder="请选择源单编号"
                  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 == null"
                  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 == null"
                  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 == null"
                  reserve-keyword
                  placeholder="请输入存储地点"
                  :remote-method="remoteWarehouse"
                  :loading="loading"
                >
                  <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="存储地点" 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 :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="12">
              <el-form-item label="仓管员" prop="receivePerson">
                <el-select
                  v-model="formData.receivePerson"
                  filterable
                  :disabled="isFormDisabled || formData.businessType == null"
                  placeholder="请输入仓管员"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in users"
                    :key="parseInt(item.id)"
                    :label="`${item.nickname}(${item.deptName || ''} ${
                      item.postName || ''
                    })`"
                    :value="parseInt(item.id)"
                  />
                </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
                placeholder="请选择物料编码"
                :remote-method="
                  (query) => remoteMaterialSearch(query, 'code', scope.$index)
                "
                :loading="loading"
                @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
                placeholder="请选择物料名称"
                :remote-method="
                  (query) => remoteMaterialSearch(query, 'name', scope.$index)
                "
                :loading="loading"
                @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="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"
          :receive-person="formData.receivePerson"
        />
        <div v-else class="isNotApproval">暂未开启工作流</div>
      </el-tab-pane>
    </el-tabs>

    <!-- 附件上传 -->
    <AttachmentUpload ref="attachmentUpload" @files="getFileList" />
  </div>
</template>

<script>
import * as InRequestApi from "@/api/wms/output/inrequest";
import DepartMentSelect from "./components/DepartMentSelect.vue";
import AttachmentUpload from "../../wms/incoming/register/components/AttachmentUpload.vue";
// 审批任务
import ApprovalTask from "../../wms/quality/iqcInspection/components/ApprovalTaskNew2.vue";
import { getFilesById } from "@/api/wms/incoming/register";
import { getUserList } from "@/api/system/user";
export default {
  name: "InRequestForm",
  components: {
    DepartMentSelect,
    ApprovalTask,
    AttachmentUpload,
  },
  data() {
    return {
      activeName: "detail",
      materialNameList: [],
      materialNoList: [],
      sourceOrderNoList: [],
      allSourceOrderNoList: [],
      supplierList: [],
      supplierOptions: [],
      customerList: [],
      businessDescribeList: [],
      warehouseList: [],
      uploadFiles: [], // 上传的文件
      users: [],
      loading: false,
      relatedOrderList: [], // 委外发料单列表
      allRelatedOrderList: [], // 全部委外发料单（用于本地过滤）
      // 页面标题
      dialogTitle: "",
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 记录当前业务类型下选中的业务分类名称
      selectedBusinessDescribe: "",
      // 保存当前选中的业务类型整行字典数据
      currentBusinessTypeRow: null,
      // 保存当前选中的业务分类整行数据
      currentBusinessDescribeRow: null,
      // 表单参数
      formData: {
        relatedOrder: undefined, // 委外发料单号
        departmentNo: undefined,
        deptCode: undefined,
        deptName: undefined,
        id: undefined,
        requestNo: undefined,
        requestType: undefined,
        businessType: undefined,
        businessCategory: undefined,
        businessDescribe: undefined,
        businessSubType: undefined,
        status: undefined,
        originStockCode: 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,
      },
      // 表单校验
      formRules: {
        businessType: [
          {
            required: true,
            message: "业务类型不能为空",
            trigger: "blur",
          },
        ],
        priority: [
          {
            required: true,
            message: "优先级不能为空",
            trigger: "blur",
          },
        ],
        expectedTime: [
          { required: true, message: "预计入库时间不能为空", trigger: "blur" },
        ],
        receivePerson: [
          {
            required: true,
            message: "仓管员不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    isFormDisabled() {
      // 当路径有id且status>=1时禁用表单
      const status = parseInt(this.formData.status || "0");
      return status >= 1;
    },
    // 计算属性判断修改状态下是否可编辑
    isEditable() {
      // 有 id 表示是编辑模式，不可编辑
      // 没有 id 表示是新增模式，可编辑
      return (
        this.formData.id === undefined ||
        this.formData.id === null ||
        this.formData.id === ""
      );
    },
    // 动态获取部门标签
    getDeptLabel() {
      const businessType = this.formData.businessType;
      if (businessType === "9") {
        // 委外入库
        return "收货部门";
      } else if (businessType === "8") {
        // 委外退料
        return "退货部门";
      } else if (businessType === "3") {
        // 生产退料
        return "发料部门";
      }
      return "部门";
    },
    // 动态获取部门占位符
    getDeptPlaceholder() {
      const businessType = this.formData.businessType;
      if (businessType === "9") {
        // 委外入库
        return "请选择收货部门";
      } else if (businessType === "8") {
        // 委外退料
        return "请选择退货部门";
      } else if (businessType === "3") {
        // 生产退料
        return "请选择发料部门";
      }
      return "请选择部门";
    },
    // 动态生成表单验证规则
    dynamicFormRules() {
      // 从原始规则中只保留业务类型、优先级、预计出入库时间、仓管员
      const baseRules = {
        businessType: this.formRules.businessType,
        priority: this.formRules.priority,
        expectedTime: this.formRules.expectedTime,
        receivePerson: this.formRules.receivePerson,
      };

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

      // 只有选择了业务类型后，才添加其他字段的验证规则
      if (businessType) {
        // 委外入库(9)和委外退料(8)需要的必填字段
        if (businessType === "9" || businessType === "8") {
          rules.deptCode = [
            {
              required: true,
              message: this.getDeptLabel + "不能为空",
              trigger: "blur",
            },
          ];
          rules.businessDescribe = [
            {
              required: true,
              message: "业务分类名称不能为空",
              trigger: "blur",
            },
          ];
          rules.supplierCode = [
            { required: true, message: "供应商不能为空", trigger: "blur" },
          ];
          rules.sourceOrderNo = [
            { required: true, message: "源单编号不能为空", trigger: "blur" },
          ];
          if (businessType === "9") {
            rules.originStockCode = [
              { required: true, message: "扣料仓库不能为空", trigger: "blur" },
            ];
          }
          // rules.relatedOrder = [
          //   { required: true, message: "委外发料单不能为空", trigger: "blur" },
          // ];
        }
        // 生产退料(3)需要的必填字段
        else if (businessType === "3") {
          rules.deptCode = [
            {
              required: true,
              message: this.getDeptLabel + "不能为空",
              trigger: "blur",
            },
          ];
          rules.businessDescribe = [
            {
              required: true,
              message: "业务分类名称不能为空",
              trigger: "blur",
            },
          ];
          rules.sourceOrderNo = [
            { required: true, message: "源单编号不能为空", trigger: "blur" },
          ];
        }
        // 其他业务类型不需要必填部门字段
        else {
          // 移除部门字段的必填规则
          delete rules.deptCode;
        }
      }

      return rules;
    },
  },
  watch: {
    "$route.query.id": {
      immediate: true,
      handler(newId) {
        // 只有当前路由路径包含"/inStorageManage/in-request/InRequestForm"时才处理，避免标签跳转时错误调用API
        if (
          this.$route.path.includes("/inStorageManage/in-request/InRequestForm")
        ) {
          if (newId) {
            this.initData(newId);
          } else {
            this.reset();
          }
        }
      },
    },
  },
  created() {
    // 从路由参数获取ID
    const id = this.$route.query.id;
    // 一次性获取全部仓管员
    getUserList().then((response) => {
      this.users = response.data;
    });
    // 一次性获取全部仓库
    InRequestApi.getStockPage({ pageSize: 9999 }).then(({ data }) => {
      this.warehouseList = data.list || [];
    });
    // 一次性获取全部供应商
    InRequestApi.getSupplierPage({ pageSize: 9999 }).then(({ data }) => {
      this.supplierList = data.list || [];
      this.supplierOptions = this.supplierList;
    });
    // 一次性获取全部客户编码
    InRequestApi.getCustomerPage({ pageSize: 9999 }).then(({ data }) => {
      this.customerList = data.list || [];
    });

    if (id) {
      this.dialogTitle = "修改";
      // this.initData(id)
    } else {
      this.dialogTitle = "新增";
    }
  },
  methods: {
    // 通用的判断函数判断按钮是否可点击
    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;
      }
    },
    // 标签页切换处理
    handleClick(tab, event) {
      // 可以在这里添加标签切换时的逻辑
      console.log(tab, event);
    },
    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.loading = true;
        setTimeout(async () => {
          this.loading = false;
          const params = {
            pageSize: 999,
          };
          // 根据搜索类型设置参数
          if (type === "code") {
            params.code = query;
          } else {
            params.name = query;
          }
          try {
            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 = [];
            }
          }
        }, 200);
      } else {
        // 清空对应的列表
        if (type === "code") {
          this.materialNoList = [];
        } else {
          this.materialNameList = [];
        }
      }
    },
    async remoteRelatedOrder(query) {
      if (query !== "") {
        this.loading = true;
        try {
          const { data } = await InRequestApi.getInRequestPage({
            pageNo: 1,
            pageSize: 100,
            businessType: 7,
            requestNo: query,
          });
          this.relatedOrderList = data?.list || [];
        } finally {
          this.loading = false;
        }
      } else {
        this.relatedOrderList = this.allRelatedOrderList;
      }
    },
    remoteMethod(query) {
      if (query !== "") {
        this.sourceOrderNoList = this.allSourceOrderNoList.filter((item) =>
          item.sourceOrderNo.toLowerCase().includes(query.toLowerCase())
        );
      } else {
        this.sourceOrderNoList = this.allSourceOrderNoList;
      }
    },
    add() {
      if (!this.formData.businessType) {
        return this.$message.error("请先选择业务类型");
      }
      this.formData.list = this.formData.list || [];
      this.formData.list.push({});
      this.formData = { ...this.formData };
    },
    // remoteWarehouse(query) {
    //   if (query !== "") {
    //     const that = this;
    //     this.loading = true;
    //     setTimeout(async () => {
    //       this.loading = 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;
        }
      });
    },
    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);

        // 强制更新列表，确保页面正常展示
        this.formData.list = [...this.formData.list];
      }
    },
    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.loading = true;
        try {
          const { data } = await InRequestApi.getSourceOrder({
            businessType: this.formData.businessType,
            businessDescribe: this.selectedBusinessDescribe,
            businessCategory: selectedRow?.value,
            pageSize: 999,
          });
          this.allSourceOrderNoList = data || [];
          this.sourceOrderNoList = this.allSourceOrderNoList;
        } finally {
          this.loading = false;
        }
      }
    },
    async changeBusinessType(value) {
      // 1. 先拿到业务类型对应的整条字典
      const dictRow =
        this.getDictDatas("in_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;
      // 委外入库时加载委外发料单列表
      if (value === "9") {
        this.loading = true;
        try {
          const { data } = await InRequestApi.getInRequestPage({
            pageNo: 1,
            pageSize: 100,
            businessType: 7,
          });
          this.allRelatedOrderList = data?.list || [];
          this.relatedOrderList = this.allRelatedOrderList;
        } finally {
          this.loading = false;
        }
      } else {
        // 非委外入库时清空
        this.allRelatedOrderList = [];
        this.relatedOrderList = [];
        this.formData.relatedOrder = undefined;
      }
    },
    /** 初始化数据 */
    async initData(id) {
      this.formLoading = true;
      try {
        /* 1. 拿主表数据 */
        const res = await InRequestApi.getRequest(id);
        const data = res.data;

        /* 2. 把 number 字段统一转字符串 */
        data.businessType && (data.businessType = String(data.businessType));
        data.businessDescribe &&
          (data.businessDescribe = String(data.businessDescribe));
        data.priority && (data.priority = String(data.priority));
        data.status && (data.status = String(data.status));
        data.receivePerson && (data.receivePerson = Number(data.receivePerson));
        data.list = data.list || [];

        /* 3. 补业务分类下拉数据 */
        if (data.businessType) {
          const { data: describeList } = await InRequestApi.getDictByOrderType({
            orderType: data.businessType,
          });
          this.businessDescribeList = describeList || [];
        }

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

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

        /* 5. 回填表单 */
        this.formData = data;
        // 委外入库时加载委外发料单列表
        if (data.businessType === "9") {
          this.loading = true;
          try {
            const { data: relatedList } = await InRequestApi.getInRequestPage({
              pageNo: 1,
              pageSize: 100,
              businessType: 7,
            });
            this.allRelatedOrderList = relatedList?.list || [];
            this.relatedOrderList = this.allRelatedOrderList;
          } finally {
            this.loading = false;
          }
        } else {
          this.allRelatedOrderList = [];
          this.relatedOrderList = [];
        }
        /* 6. 附件列表 */
        this.uploadFiles = data.filesListVos || [];
      } finally {
        this.formLoading = false;
      }
    },
    /** 保存按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        // /* 1. 深拷贝一份，避免污染页面数据 */
        // const data = JSON.parse(JSON.stringify(this.formData));
        // /* 2. 把仓管员转回字符串 */
        // data.receivePerson =
        //   data.receivePerson != null ? String(data.receivePerson) : "";
        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(",");

        // 修改的提交
        if (data.id) {
          await InRequestApi.updateRequest(data);
          this.$modal.msgSuccess("修改成功");
          // 提交成功后刷新数据
          await this.initData(data.id);
          return;
        }
        // 添加的提交
        await InRequestApi.createRequest(data);
        this.$modal.msgSuccess("新增成功");
        this.$router.push({
          path: "/inStorageManage/in-request",
        });
      } finally {
        this.formLoading = false;
      }
    },
    /** 提交按钮 */
    async commit() {
      console.log("打印一下仓管员信息", this.formData.receivePerson);
      if (!this.formData.receivePerson) {
        this.$modal.msgWarning("请先添加仓管员");
        return;
      }
      const menuId = this.$route.meta.id;

      // 只提取需要的字段
      const requestData = {
        id: this.formData.id,
        menuId: menuId,
      };

      // 接口调用
      await InRequestApi.commitInRequest(requestData);
      this.$modal.msgSuccess("提交成功");
      // 提交成功后刷新数据
      await this.initData(this.formData.id);
      // 状态变化
      this.$set(this.formData, "status", "1");

      // 重新获取数据
      const res = await InRequestApi.getRequest(this.formData.id);
      this.formData.bpmInstanceId = res.data.bpmInstanceId;
    },
    /** 撤销按钮 */
    async cancel() {
      const data = this.formData;
      // 接口调用
      await InRequestApi.cancelInRequest(data);
      this.$modal.msgSuccess("撤销成功");
      // 状态变化
      this.$set(this.formData, "status", "0");

      // 跳转到明细信息tab
      this.activeName = "detail";
      // 刷新明细信息
      await this.initData(this.formData.id);
    },
    /** 审核按钮 */
    async audit() {
      // 检查是否存在工作流实例ID
      if (this.formData.bpmInstanceId) {
        // 如果存在工作流实例，跳转到审批任务tab页
        this.activeName = "approvalTask";
        this.$modal.msgWarning("请在审批任务页面完成审核！");
        return;
      }

      const data = this.formData;
      // 接口调用
      await InRequestApi.auditInRequest(data);
      this.$modal.msgSuccess("审核成功");
      // 状态变化
      this.$set(this.formData, "status", "2");
    },
    /** 反审核按钮 */
    async antiAudit() {
      const data = this.formData;
      // 接口调用
      await InRequestApi.antiAuditInRequest(data);
      this.$modal.msgSuccess("反审核成功");
      // 状态变化
      this.$set(this.formData, "status", "0");

      // 跳转到明细信息tab
      this.activeName = "detail";
      // 刷新明细信息
      await this.initData(this.formData.id);
    },
    /** 返回按钮 */
    handleCancel() {
      this.reset();
      this.$router.push({
        path: "/inStorageManage/in-request",
      });
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        // list: [],
        originStockCode: undefined,
        relatedOrder: 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: [],
      };
      this.resetForm("formRef");
    },
    deliverChange(val) {
      // 这里可以写“本次出入数量”变化后的校验或计算逻辑
      console.log("deliverChange", val);
    },
    // 附件上传
    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>
.page-header {
  margin-bottom: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.header-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.breadcrumb {
  margin-bottom: 15px;
}

.header-buttons {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.header-buttons .el-button {
  margin-right: 10px;
}

.form-container {
  margin-bottom: 20px;
}
.app-container {
  min-width: 900px;
  margin: 0 auto;
  overflow-x: auto;
}
</style>
