<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"
                  :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)
                  "
                  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-input
                  v-model="formData.supplierCode"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  placeholder="请输入供应商编码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户编码" prop="customerCode">
                <el-input
                  v-model="formData.customerCode"
                  :disabled="
                    isFormDisabled || (formData.businessType ? false : true)
                  "
                  placeholder="请输入客户编码"
                />
              </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="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="状态" 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="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: [],
      businessDescribeList: [],
      warehouseList: [],
      loadingMaterial: false,
      loadingSourceOrder: false,
      loadingWarehouse: false,
      uploadFiles: [], // 上传的文件
      // 页面标题
      dialogTitle: "",
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      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,
      },
      // 表单校验
      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 === ""
      );
    },
    // 动态获取部门标签
    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.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" },
          ];
        }
      }

      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();
            }
          }
        }
      },
    },
  },
  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;
      }
    },
    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 !== "") {
        const that = this;
        this.loadingSourceOrder = true;
        setTimeout(async () => {
          this.loadingSourceOrder = false;
          const { data } = await InRequestApi.getSourceOrder({
            businessType: that.formData.businessType,
            sourceOrderNo: query,
          });
          this.sourceOrderNoList = data || [];
        }, 200);
      } else {
        this.sourceOrderNoList = [];
      }
    },
    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;
    //     }
    //   });
    // },
    changeBusinessDescribe(e) {
      (this.businessDescribeList || []).forEach((v) => {
        if (v.label === e) {
          this.formData.businessCategory = v.value;
        }
      });
    },
    async changeBusinessType(value) {
      // 只更新businessType字段，避免覆盖整个formData
      this.formData.businessType = value;
      // 重置表单校验状态
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
      const { data } = await InRequestApi.getDictByOrderType({
        orderType: value,
      });
      this.businessDescribeList = data;
    },
    /** 初始化数据 */
    async open(id) {
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          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.list = res.data.list || [];
          this.formData = res.data;
          this.dialogTitle = "修改";
          // 附件列表
          this.uploadFiles = this.formData.filesListVos;
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增";
        this.formData.list = [];
      }
    },
    /** 保存按钮 */
    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(",");

        // 修改的提交;
        if (data.id) {
          await InRequestApi.updateInRequest(data);
          this.$modal.msgSuccess("修改成功");
          // this.$router.back();//修改时停留在当前页面
          return;
        }
        // 添加的提交
        await InRequestApi.createInRequest(data);
        this.$modal.msgSuccess("新增成功");
        this.$router.back();
      } finally {
        this.formLoading = false;
      }
    },
    /** 提交按钮 */
    async commit() {
      const menuId = this.$route.meta.id;

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

      // 重新获取数据
      const res = await InRequestApi.getInRequest(this.formData.id);
      this.formData.bpmInstanceId = res.data.bpmInstanceId;
    },
    /** 撤销按钮 */
    async cancel() {
      const requestData = {
        id: this.formData.id,
      };
      // 接口调用
      await InRequestApi.cancelOutRequest(requestData);
      this.$modal.msgSuccess("撤销成功");
      // 状态变化
      this.$set(this.formData, "status", "0");
    },
    /** 审核按钮 */
    async audit() {
      // 检查是否存在工作流实例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() {
      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: [],
      };
      this.resetForm("formRef");
    },
    // 标签页切换处理
    handleClick(tab, event) {
      // 可以在这里添加标签切换时的逻辑
      console.log(tab, event);
    },
    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;
    },
  },
};
</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>
