<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="isFormDisabled"
                >提交</el-dropdown-item
              >
              <el-dropdown-item :disabled="isFormDisabled"
                >撤销</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="isFormDisabled"
                >审核</el-dropdown-item
              >
              <el-dropdown-item>反审核</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-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      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="isFormDisabled"
              @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="departmentNo">
            <DepartMentSelect
              ref="departMentSelect"
              v-model="formData.departmentNo"
              :disabled="isFormDisabled || !formData.businessType"
              placeholder="请选择部门"
              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"
              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"
              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"
              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"
              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"
              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 :span="12">
          <el-form-item label="预计出入库时间" prop="expectedTime">
            <el-date-picker
              v-model="formData.expectedTime"
              :disabled="isFormDisabled || !formData.businessType"
              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="isFormDisabled || !formData.businessType"
              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"
              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"
              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="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-row>
    </el-form>

    <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="requireQty"
        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>
  </div>
</template>

<script>
import * as InRequestApi from "@/api/wms/output/inrequest";
import DepartMentSelect from "./components/DepartMentSelect.vue";
// import ShipmentNotification from "./ShipmentNotification.vue";
export default {
  name: "InRequestForm",
  components: {
    // ShipmentNotification,
    DepartMentSelect,
  },
  data() {
    return {
      materialNameList: [],
      materialNoList: [],
      sourceOrderNoList: [],
      businessDescribeList: [],
      warehouseList: [],
      loading: false,
      // 页面标题
      dialogTitle: "",
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        departmentNo: 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: [],
      },
      // 表单校验
      formRules: {
        departmentNo: [
          { required: true, message: "请选择部门", trigger: "blur" },
        ],
        requestNo: [
          { required: true, message: "申请单号不能为空", trigger: "blur" },
        ],
        expectedTime: [
          { required: true, message: "预计入库时间不能为空", trigger: "blur" },
        ],
        requestType: [
          {
            required: true,
            message: "申请类型(0入库 1出库)不能为空",
            trigger: "change",
          },
        ],
        businessType: [
          {
            required: true,
            message:
              "业务类型(0采购入库 3生产退料 4成品入库 6销售退货 8委外退料 9委外入库 11其他入库 13转移调拨 14仓库盘点)不能为空",
            trigger: "change",
          },
        ],
        businessSubType: [
          {
            required: true,
            message: "业务子类型(0正常 1补料)不能为空",
            trigger: "change",
          },
        ],
        status: [
          {
            required: false,
            message:
              "状态(0草稿 1已提交 2已审核 3执行中 4已完成 5已取消)不能为空",
            trigger: "blur",
          },
        ],
        priority: [
          {
            required: true,
            message: "优先级(0普通 1紧急 2加急)不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    isFormDisabled() {
      // 当路径有id且status>=2时禁用表单
      const hasId = this.$route.query.id;
      const status = parseInt(this.formData.status || "0");
      return hasId && status >= 2;
    },
  },
  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;
    if (id) {
      this.dialogTitle = "修改";
      // this.initData(id)
    } else {
      this.dialogTitle = "新增";
    }
  },
  methods: {
    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 = [];
        }
      }
    },
    remoteMethod(query) {
      if (query !== "") {
        const that = this;
        this.loading = true;
        setTimeout(async () => {
          this.loading = false;
          const { data } = await InRequestApi.getSourceOrder({
            businessType: that.formData.businessType,
            sourceOrderNo: query,
            pageSize: 999,
          });
          this.sourceOrderNoList = data || [];
        }, 200);
      } else {
        this.sourceOrderNoList = [];
      }
    },
    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];
      }
    },
    changeBusinessDescribe(e) {
      this.businessDescribeList.map((v) => {
        if (v.label == e) {
          this.formData.businessCategory = v.value;
        }
      });
    },
    async changeBusinessType(value) {
      this.formData.businessType = value;
      this.formData.businessDescribe = "";
      this.formData.businessCategory = "";
      const { data } = await InRequestApi.getDictByOrderType({
        orderType: value,
      });
      this.businessDescribeList = data;
    },
    /** 初始化数据 */
    async initData(id) {
      this.formLoading = true;
      try {
        const res = await InRequestApi.getRequest(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;
      } 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
          );

        // 修改的提交
        if (data.id) {
          await InRequestApi.updateRequest(data);
          this.$modal.msgSuccess("修改成功");
          this.$router.push({
            path: "/inStorageManage/in-request",
          });
          return;
        }
        // 添加的提交
        await InRequestApi.createRequest(data);
        this.$modal.msgSuccess("新增成功");
        this.$router.push({
          path: "/inStorageManage/in-request",
        });
      } finally {
        this.formLoading = false;
      }
    },
    /** 返回按钮 */
    handleCancel() {
      this.reset();
      this.$router.push({
        path: "/inStorageManage/in-request",
      });
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        // list: [],
        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);
    },
  },
};
</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;
}
</style>
