<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      v-dialogDrag
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="75%"
      append-to-body
    >
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="150px"
      >
        <el-col :span="12"
          ><el-form-item label="业务类型" prop="businessType">
            <el-select
              v-model="formData.businessType"
              @change="changeBusinessType"
              placeholder="请选择业务类型"
            >
              <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="businessDescribe">
            <el-select
              v-model="formData.businessDescribe"
              :disabled="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="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="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="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="formData.businessType ? false : true"
              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-option>
            </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="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="formData.businessType ? false : 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="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="formData.businessType ? false : true"
              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-option>
            </el-select>
          </el-form-item>
        </el-col>
      </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="materialNo"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名称"
          align="center"
          prop="materialName"
          width="150"
          show-overflow-tooltip
        />
        <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"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.nowDeliveredQty"
              @change="deliverChange"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="已出货数量"
          align="center"
          prop="deliveredQty"
          width="120"
        />
        <el-table-column
          label="应出货数量"
          align="center"
          prop="shouldDeliveredQty"
          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">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="formLoading" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as InRequestApi from "@/api/wms/output/inrequest";
// import ShipmentNotification from "./ShipmentNotification.vue";
export default {
  name: "InRequestForm",
  components: {
    // ShipmentNotification,
  },
  data() {
    return {
      sourceOrderNoList: [],
      businessDescribeList: [],
      warehouseList: [],
      loading: false,
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      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: [],
      },
      // 表单校验
      formRules: {
        requestNo: [
          { 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: true,
            message:
              "状态(0草稿 1已提交 2已审核 3执行中 4已完成 5已取消)不能为空",
            trigger: "blur",
          },
        ],
        priority: [
          {
            required: true,
            message: "优先级(0普通 1紧急 2加急)不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    remoteMethod(query) {
      if (query !== "") {
        let that = this;
        this.loading = true;
        setTimeout(async () => {
          this.loading = false;
          let { data } = await InRequestApi.getSourceOrder({
            businessType: that.formData.businessType,
            sourceOrderNo: query,
          });
          this.sourceOrderNoList = data || [];
        }, 200);
      } else {
        this.sourceOrderNoList = [];
      }
    },
    remoteWarehouse(query) {
      if (query !== "") {
        let that = this;
        this.loading = true;
        setTimeout(async () => {
          this.loading = false;
          let {
            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;
        }
      });
    },
    changeBusinessDescribe(e) {
      this.businessDescribeList.map((v) => {
        if (v.label == e) {
          this.formData.businessCategory = v.value;
        }
      });
    },
    async changeBusinessType(value) {
      this.formData = {
        id: this.formData.id,
        businessType: this.formData.businessType,
      };
      this.formData = { ...this.formData };
      let { data } = await InRequestApi.getDictByOrderType({
        orderType: this.formData.businessType,
      });
      this.businessDescribeList = data;
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      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";
          this.formData = res.data;
          this.dialogTitle = "修改";
        } finally {
          this.formLoading = false;
        }
      }
      this.dialogTitle = "新增";
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        // this.$refs.shipmentNotification.open = true;
        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
          );
        // let arr = [];
        // data.list.filter((v) => {
        //   if (v.nowDeliveredQty) {
        //     arr.push(v);
        //   }
        // });
        // data.list = arr;
        // 修改的提交;
        if (data.id) {
          await InRequestApi.updateInRequest(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit("success");
          return;
        }
        // 添加的提交
        await InRequestApi.createInRequest(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit("success");
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    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,
      };
      this.resetForm("formRef");
    },
  },
};
</script>
