<!--新增调拨单-->
<template>
  <ContainerTit class="AddAllocationForm">
    <div style="position: relative">
      <div v-if="$route.name !== 'DetailAllocationForm'" class="btn-top-div">
        <el-button
          v-if="!$route.params.id"
          :loading="loading"
          @click="delPauseSave(1)"
        >
          清除暂存
        </el-button>
        <el-button
          v-if="!$route.params.id"
          :loading="loading"
          @click="addPauseSave"
        >
          暂存
        </el-button>
        <el-button type="primary" :loading="loading" @click="addPurchaseOrder">
          保存
        </el-button>
      </div>
    </div>
    <div>
      <el-form
        ref="form"
        inline
        :model="form"
        size="small"
        :rules="rules"
        :disabled="$route.name === 'DetailAllocationForm'"
      >
        <el-tabs v-model="activeName">
          <el-tab-pane label="新增调拨单" name="one">
            <el-row style="padding-bottom: 13px">
              <el-col :span="24">
                <p
                  style="padding-left: 20px"
                  class="order_midden_left_text el-icon-arrow-right"
                >
                  调拨单信息
                </p>
              </el-col>
              <el-col
                v-if="allData.no"
                class="form"
                :span="6"
                style="margin-bottom: 0"
              >
                <el-form-item label="单据编号：">
                  {{ allData.no }}
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item label="调出仓库:" prop="fromWarehouse">
                  <el-input
                    v-model="form.fromWarehouse"
                    placeholder="调出仓库"
                    readonly
                  >
                    <i
                      slot="suffix"
                      class="el-input__icon el-icon-search"
                      @click="openWarehouse('from')"
                    ></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item label="调入仓库:" prop="targetWarehouse">
                  <el-input
                    v-model="form.targetWarehouse"
                    :disabled="!form.fromWarehouse"
                    readonly
                    placeholder="调入仓库"
                  >
                    <i
                      slot="suffix"
                      class="el-input__icon el-icon-search"
                      @click="openWarehouse('target')"
                    ></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6">
                <el-form-item label="制单人员:">
                  {{ form.operatorName }}
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6">
                <el-form-item label="制单时间:">
                  <span>{{ createTime }}</span>
                </el-form-item>
              </el-col>
              <el-col v-if="allData.auditStatus === 2" class="form" :span="6">
                <el-form-item label="审核人员:">
                  {{ form.operatorName }}
                </el-form-item>
              </el-col>
              <el-col v-if="allData.auditStatus === 2" class="form" :span="6">
                <el-form-item label="审核时间:">
                  <span>{{ $_common.formatDate(allData.auditTime) }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <div class="order_bottom">
          <p class="text">商品清单</p>
          <el-button
            class="order_bottom_btn"
            :disabled="!form.fromWarehouse"
            type="primary"
            size="mini"
            @click="choosegoods"
          >
            选择商品
          </el-button>
          <vxe-table
            border="inner"
            resizable
            show-footer
            show-overflow
            :data="goods_list"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
            :footer-method="objectSpanMethod"
            @edit-actived="editActivedEvent"
          >
            <vxe-table-column type="seq" width="60"></vxe-table-column>
            <vxe-table-column
              field="materielCode"
              title="商品编码"
            ></vxe-table-column>
            <vxe-table-column
              field="materielName"
              title="商品名称"
            ></vxe-table-column>
            <vxe-table-column field="unitName" title="规格">
              <template #default="{ row }">
                {{ row.unitName }};{{ row.skuName }}
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="warehouseName"
              title="所属仓库"
            ></vxe-table-column>
            <vxe-table-column
              v-if="enableLocationManagement === 5"
              title="调出库区库位"
            >
              <template #default="{ row, rowIndex }">
                <el-input
                  v-model="row.inStorageLocationName"
                  placeholder="库区库位"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="calloutShow(row, rowIndex)"
                  ></i>
                </el-input>
              </template>
            </vxe-table-column>
            <vxe-table-column
              v-if="enableLocationManagement === 5"
              title="调入库区库位"
            >
              <template #default="{ row, rowIndex }">
                <el-input
                  v-model="row.outStorageLocationName"
                  placeholder="库区库位"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="foldShow(row, rowIndex)"
                  ></i>
                </el-input>
              </template>
            </vxe-table-column>
            <vxe-table-column field="inventoryNum" title="可售库存">
              <template #default="{ row }">
                {{ $_common.formatNub(row.inventoryNum) }}
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="num"
              title="调拨数量"
              :edit-render="{
                name: '$input',
                props: {
                  type: 'float',
                  digits: 2,
                  min: 0,
                  max: inventoryNum,
                },
              }"
            ></vxe-table-column>
            <vxe-table-column
              field="otherNum"
              title="其他单位"
              :edit-render="{
                name: '$input',
                props: {
                  type: 'float',
                  digits: 2,
                  min: 0,
                  disabled: other_disables,
                },
              }"
            ></vxe-table-column>
            <vxe-table-column title="调入仓库">
              <template #default="{ $rowIndex }">
                <span v-if="false">{{ $rowIndex }}</span>
                {{ form.targetWarehouse }}
              </template>
            </vxe-table-column>
            <vxe-table-column width="80" title="操作">
              <template #default="{ row, $rowIndex }">
                <el-button type="text" @click="delData($rowIndex, row)">
                  删除
                </el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
          <div class="clearfix other-price-view">
            <div class="float_left">
              <el-form-item label="备注:">
                <el-input
                  v-model="form.remark"
                  style="width: 360px"
                  placeholder="备注"
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <!--    选择仓库-->
    <WarehouseModel
      v-if="warehouse_show"
      :not-id="notId"
      :is-check="false"
      :is-show="warehouse_show"
      @confirm="selWarehouse"
      @cancel="warehouse_show = false"
    />
    <!--    选择商品-->
    <AllocateGoodsList
      v-if="show_selgoods"
      :is-show="show_selgoods"
      :warehouse-id="form.fromWarehouseId"
      @cancel="show_selgoods = false"
      @confirm="selMoreGoods"
    ></AllocateGoodsList>
    <CalloutStorageLocation
      v-if="callout_show"
      :show="callout_show"
      :warehouse-id="form.fromWarehouseId"
      :goods-data="batch_goods"
      @cancel="callout_show = false"
      @confirm="timeEditConfirm"
    ></CalloutStorageLocation>
    <StorageLocation
      v-if="fold_show"
      :is-check="false"
      :is-show="fold_show"
      :warehouse-id="warehouse_id2"
      @confirm="selFold"
      @cancel="fold_show = false"
    />
  </ContainerTit>
</template>

<script>
  import CalloutStorageLocation from "@/component/common/CalloutStorageLocation";
  import StorageLocation from "@/component/common/StorageLocation";
  import AllocateGoodsList from "@/component/goods/AllocateGoodsList.vue";
  import WarehouseModel from "@/component/common/WarehouseModel.vue";
  import { delPauseSave, getPauseSave, addPauseSave } from "@/api/common";
  import {
    getBatchByIds,
    updateAllocate,
    addAllocate,
    getAllocateInfo,
    getAreaDateBySkuId,
  } from "@/api/Stock";
  import { mapGetters } from "vuex";
  export default {
    name: "PurchaseOrderAdd",
    components: {
      WarehouseModel,
      AllocateGoodsList,
      StorageLocation,
      CalloutStorageLocation,
    },
    data() {
      const validateFrom = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择所属仓库"));
        } else {
          callback();
        }
      };
      const validateTarget = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择目标仓库"));
        } else {
          callback();
        }
      };
      return {
        inventoryNum: "",
        loading: false,
        other_disables: false,
        batch_data: [],
        createTime: "",
        Allocat_id: "", // 调拨id
        warehouse_show: false,
        show_selgoods: false,
        form: {
          fromWarehouse: "", // 仓库名称
          targetWarehouse: "",
          fromWarehouseId: "", // 所属仓库id
          targetWarehouseId: "",
          operatorName: "",
          couponAmount: "",
          otherAmount: "",
          remark: "",
        },
        rules: {
          fromWarehouse: [{ required: true, validator: validateFrom }],
          targetWarehouse: [{ required: true, validator: validateTarget }],
        },
        deleteStatus: [],
        goods_list: [],
        warehouse_tag: "",
        notId: 0,
        allData: {},
        no: "",
        look_path: "",
        callout_show: false,
        fold_show: false,
        warehouse_id: "",
        warehouse_id2: "",
        batch_goods: "",
        index: "",
        activeName: "one",
      };
    },
    computed: {
      ...mapGetters({
        enableLocationManagement: "MUser/enableLocationManagement",
      }),
    },
    created() {
      this.look_path = this.$route.name;
      this.createTime = this.$_common.formatDate(new Date().getTime());
      if (this.$route.params.id) {
        this.Allocat_id = this.$route.params.id;
        this.getAllocateInfo();
      } else {
        this.form.operatorName = this.userName;
        this.getPauseSave();
      }
    },
    methods: {
      // 查询物料批次数据
      async getBatch(row) {
        const data = await getBatchByIds({
          warehouseId: this.form.fromWarehouseId,
          materielId: row.materielId,
        });

        this.batch_data = data.data;
      },
      // 选择商品
      choosegoods() {
        if (this.form.fromWarehouseId) {
          this.show_selgoods = true;
        }
      },
      openWarehouse(tag) {
        if (this.$route.name === "DetailAllocationForm") {
          return;
        }
        if (tag === "from") {
          this.notId = 0;
        } else {
          this.notId = this.form.fromWarehouseId || 0;
          if (!this.form.fromWarehouse) {
            this.$message.warning("请选择调出仓库");
            return;
          }
        }

        this.warehouse_tag = tag;
        this.warehouse_show = true;
      },
      // 选择仓库
      selWarehouse(row) {
        switch (this.warehouse_tag) {
          case "from":
            this.form.fromWarehouse = row[0].warehouseName;
            this.form.fromWarehouseId = row[0].id;
            this.goods_list = [];
            if (row[0].warehouseName === this.form.targetWarehouse) {
              this.form.targetWarehouse = "";
              this.form.targetWarehouseId = "";
            }
            break;
          case "target":
            this.form.targetWarehouse = row[0].warehouseName;
            this.form.targetWarehouseId = row[0].id;
            let target = this.$_common.deepClone(this.goods_list);
            target = target.map((item) => {
              return {
                ...item,
                inwarehouseName: row[0].warehouseName,
              };
            });
            this.goods_list = target;
            break;
        }
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.look_path,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$baseEventBus.$emit("reloadRouterView");
        }
      },
      // 暂存详情
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.look_path,
        });

        if (JSON.stringify(data) === "{}") return;
        this.allData = data;
        this.no = data.no;
        this.form.fromWarehouse = data.warehouseName;
        this.form.fromWarehouseId = data.warehouseId;
        this.form.targetWarehouse = data.inWarehouseName;
        this.form.targetWarehouseId = data.inWarehouseId;
        this.form.operatorName = data.operatorName;
        this.form.remark = data.remark;
        this.goods_list = data.details.map((item) => {
          return {
            ...item,
            warehouseName: this.form.fromWarehouse,
            inwarehouseName: this.form.targetWarehouse,
          };
        });
      },
      async addPauseSave() {
        const params = {
          createTime: this.createTime,
          no: this.no,
          warehouseId: this.form.fromWarehouseId,
          inWarehouseId: this.form.targetWarehouseId,
          inWarehouseName: this.form.targetWarehouse,
          warehouseName: this.form.fromWarehouse,
          operatorName: this.form.operatorName,
          remark: this.form.remark,
          details: this.goods_list.map((item) => {
            return {
              id: item.id,
              isEq: item.isEq,
              materielId: item.materielId,
              materielName: item.materielName,
              materielCode: item.materielCode,
              skuId: item.skuId,
              num: item.num,
              skuName: item.skuName,
              costUnitPrice: item.costUnitPrice,
              otherNum: item.otherNum,
            };
          }),
        };
        this.loading = true;
        const data = await addPauseSave({
          key: this.look_path,
          data: params,
        });
        this.loading = false;

        this.$message({
          type: "success",
          message: "暂存成功",
        });
        if (this.systemType === 2) {
          this.$closeCurrentGoEdit(
            "/SingleStore/Inventory/InventoryAllocation"
          );
        } else {
          this.$closeCurrentGoEdit(
            "/stock/WarehouseManagement/AddAllocationForm"
          );
        }
      },
      //  添加调拨单 addPurchaseOut
      async addPurchaseOrder() {
        let flag = false;
        this.goods_list.forEach((item) => {
          if (Number(item.inventoryNum) === 0) {
            flag = true;
          }
        });
        if (flag) {
          this.$message.warning("可售库存为空，无法调拨");
          return;
        }
        let numobj = {};
        for (let i in this.goods_list) {
          let item = this.goods_list[i];
          if (!numobj[item.skuId]) {
            numobj[item.skuId] = {
              inventoryNum: Number(item.inventoryNum),
              num: Number(item.num),
            };
          } else {
            numobj[item.skuId].num += Number(item.num);
          }
        }
        const ismore = Object.values(numobj).some(
          (item) => item.num > item.inventoryNum
        );
        if (ismore) {
          this.$message.warning("调拨数量大于可售库存，无法调拨");
          return;
        }
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            const params = {
              no: this.no,
              warehouseId: this.form.fromWarehouseId,
              inWarehouseId: this.form.targetWarehouseId,
              warehouseName: this.form.fromWarehouse,
              inWarehouseName: this.form.targetWarehouse,
              operatorName: this.form.operatorName,
              remark: this.form.remark,
              details: this.goods_list.map((item) => {
                return {
                  id: item.id,
                  isEq: item.isEq,
                  materielId: item.materielId,
                  materielName: item.materielName,
                  materielCode: item.materielCode,
                  skuId: item.skuId,
                  unitName: item.unitName,
                  skuName: item.skuName,
                  num: item.num,
                  costUnitPrice: item.costUnitPrice,
                  otherNum: item.otherNum,
                  inAreaId: item.inAreaId,
                  inAreaName: item.inAreaName,
                  inAreaCode: item.inAreaCode,
                  inStorageLocationId: item.inStorageLocationId,
                  inStorageLocationName: item.inStorageLocationName,
                  inStorageLocationCode: item.inStorageLocationCode,
                  outAreaId: item.outAreaId,
                  outAreaName: item.outAreaName,
                  outAreaCode: item.outAreaCode,
                  outStorageLocationId: item.outStorageLocationId,
                  outStorageLocationName: item.outStorageLocationName,
                  outStorageLocationCode: item.outStorageLocationCode,
                };
              }),
            };
            let target = {};
            this.loading = true;
            if (this.Allocat_id) {
              params.deleteArray = this.deleteStatus;
              target = await updateAllocate(this.Allocat_id, params);
            } else {
              target = await addAllocate(params);
            }
            const data = target;
            this.loading = false;

            this.$message({
              type: "success",
              message: "提交成功",
            });
            await this.delPauseSave();
            if (this.systemType === 2) {
              this.$closeCurrentGoEdit(
                "/SingleStore/Inventory/InventoryAllocation"
              );
            } else {
              this.$closeCurrentGoEdit(
                "/stock/WarehouseManagement/AllocationForm"
              );
            }
          }
        });
      },
      //  获取详情
      async getAllocateInfo() {
        const { data } = await getAllocateInfo(this.Allocat_id);
        this.allData = data;
        this.no = data.no;
        this.createTime = this.$_common.formatDate(data.createTime);
        this.form.fromWarehouse = data.warehouseName;
        this.form.fromWarehouseId = data.warehouseId;
        this.form.targetWarehouse = data.inWarehouseName;
        this.form.targetWarehouseId = data.inWarehouseId;
        this.form.operatorName = data.operatorName;
        this.form.remark = data.remark;
        this.goods_list = data.details.map((item) => {
          return {
            ...item,
            otherNum: item.isEq === 5 ? item.otherNum : "",
            warehouseName: this.form.fromWarehouse,
            inwarehouseName: this.form.targetWarehouse,
          };
        });
      },
      //  选择商品goodData的数据
      selMoreGoods(val) {
        const goods = val.map((item) => {
          return {
            isEq: item.isEq,
            otherNum: item.isEq === 5 ? item.otherNum : "",
            materielId: item.materielId,
            materielCode: item.materielCode,
            materielName: item.materielName,
            warehouseName: item.warehouseName,
            inwarehouseName: this.targetWarehouse,
            skuName: item.skuName,
            skuId: item.skuId,
            unitName: item.unitName,
            inventoryNum: Number(item.allNum),
            num: Number(item.allNum),
            categoryTitle: item.categoryTitle,
            costUnitPrice: item.costPrice,
          };
        });
        if (
          this.goods_list.findIndex((item) => {
            return item.skuId === goods[0].skuId;
          }) !== -1
        ) {
          this.$message.warning("不能选同一件商品");
          return;
        }
        if (this.goods_list) {
          // this.goods_list = this.$_common.unique(
          //   this.goods_list.concat(goods),
          //   ["materielId", "skuId"]
          // );
          this.goods_list = this.$_common.unique(
            this.goods_list.concat(goods),
            []
          );
        } else {
          this.goods_list = goods;
        }
        console.log(this.goods_list);
      },
      //  删除
      delData(index, row) {
        this.$confirm("你确定删除此商品吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          if (row.id) {
            this.deleteStatus.push(row.id);
          }
          this.goods_list.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      },
      objectSpanMethod({ columns, data }) {
        const properties = ["otherNum"];
        return this.$_common.getSummariesVxe(columns, data, properties);
      },
      editActivedEvent({ row }) {
        this.other_disables = row.isEq === 4;
        this.inventoryNum = row.inventoryNum;
      },
      calloutShow(row, index) {
        this.batch_goods = row;
        this.callout_show = true;
      },
      foldShow(row, index) {
        if (!this.form.targetWarehouseId) {
          this.$message.warning("请先选择调入仓库");
          return;
        }
        this.index = index;
        this.fold_show = true;
        this.warehouse_id2 = this.form.targetWarehouseId;
      },
      selCallout() {},
      selFold(e) {
        this.goods_list[this.index].outAreaId = e[0].areaId;
        this.goods_list[this.index].outAreaName = e[0].areaName;
        this.goods_list[this.index].outAreaCode = e[0].areaCode;
        this.goods_list[this.index].outStorageLocationId = e[0].id;
        this.goods_list[this.index].outStorageLocationName = e[0].name;
        this.goods_list[this.index].outStorageLocationCode = e[0].code;
      },
      timeEditConfirm(arr) {
        if (!arr.length) {
          return;
        }
        const index = this.goods_list.findIndex(
          (item) =>
            item.inStorageLocationId === arr[0].inStorageLocationId &&
            item.inAreaId === arr[0].inAreaId &&
            item.skuId === arr[0].skuId
        );
        if (index > -1) {
          if (this.goods_list[index].id) {
            arr[0].id = this.goods_list[index].id;
          }
          this.goods_list.splice(index, 1);
        }
        this.goods_list = this.goods_list.concat(arr);
      },
    },
  };
</script>

<style lang="scss" scoped>
  .width240 {
    width: 240px;
  }
  .other-price-view {
    padding: 10px 10px 0;
    border: 1px solid #ecf0f7;
    border-top: 0;
  }
  .order_bottom {
    position: relative;
    border-top: 16px solid #f6f8f9;
    width: 100%;
    background-color: #ffffff;
    border-radius: 3px;
    .text {
      font-size: 16px;
      font-weight: 600;
      color: #2d405e;
      line-height: 64px;
      padding: 0px 24px;
    }
    .order_bottom_btn {
      position: absolute;
      top: 15px;
      right: 20px;
    }
  }
  .order_midden_left_text {
    font-weight: bold;
    font-size: 16px;
    margin: 0 0 27px 0;
  }
  .form {
    padding-left: 40px;
    font-size: 14px;
    margin-bottom: 19px;
    .form_left {
      margin-right: 32px;
      color: #62738e;
      font-weight: 400;
    }
    .form_right {
      color: #2d405e;
      font-weight: 500;
    }
  }
  .btn-top-div {
    position: absolute;
    right: 20px;
    top: 15px;
    z-index: 999;
  }
</style>
<style>
  .AddAllocationForm {
    background-color: #fff;
  }
  .AddAllocationForm .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .AddAllocationForm .is-active {
    font-weight: 700;
    color: #000;
  }
  .AddAllocationForm .el-tabs__nav {
    margin-left: 24px;
  }
</style>
