<template>
  <ContainerTit class="AddInventoryInfo">
    <div style="position: relative">
      <div class="btn-top-div">
        <el-button v-if="!$route.params.id" @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_data" size="small" :rules="rules">
        <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="!!no"
                class="form"
                :span="6"
                style="margin-bottom: 0"
              >
                <el-form-item label="单据编号:">
                  {{ no }}
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item label="所属仓库:" prop="warehouseId">
                  <el-input
                    v-model="fromWarehouse"
                    placeholder="所属仓库"
                    readonly
                  >
                    <i
                      slot="suffix"
                      class="el-input__icon el-icon-search"
                      @click="warehouse_show = true"
                    ></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item label="盘点日期:" prop="stocktakingTime">
                  <el-date-picker
                    v-model="form_data.stocktakingTime"
                    type="date"
                    placeholder="选择日期"
                    value-format="timestamp"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6">
                <el-form-item label="制单人员:">
                  {{ form_data.operatorName }}
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6">
                <el-form-item label="制单时间:">
                  <span>{{ $_common.formatDate(createTime) }}</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"
            type="primary"
            size="small"
            :disabled="!fromWarehouse"
            @click="show_selgoods = true"
          >
            选择商品
          </el-button>
          <div class="Enunciate">
            <div class="Enunciate_cont clearfix">
              <div class="float_left">
                有 {{ plus_goods }} 款商品共计
                <span>{{ plus_num }}</span>
                件盘盈，有 {{ diff_goods }} 款商品共计
                <span>{{ diff_num }}</span>
                件盘亏
              </div>
            </div>
          </div>
          <vxe-table
            border="inner"
            resizable
            show-footer
            show-overflow
            :data="goods_list"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
            :footer-method="objectSpanMethod"
            @edit-closed="editNumChange"
          >
            <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="documentInventoryNum" title="账面库存">
              <template #default="{ row }">
                {{ $_common.formatNub(row.documentInventoryNum) }}
              </template>
            </vxe-table-column>
            <vxe-table-column
              v-if="enableLocationManagement === 5"
              field="storageLocationName"
              title="库区库位"
            >
              <template #default="{ row, rowIndex }">
                <vxe-input
                  v-model="row.storageLocationName"
                  placeholder="库区库位"
                >
                  <template #suffix>
                    <i
                      class="el-input__icon el-icon-search"
                      @click="storageShow(row, rowIndex)"
                    ></i>
                  </template>
                </vxe-input>
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="currentInventoryNum"
              title="实盘库存"
              :edit-render="{
                name: '$input',
                props: { type: 'float', digits: 2, min: 0 },
              }"
            ></vxe-table-column>
            <vxe-table-column
              field="otherNum"
              title="其他单位"
              :edit-render="{
                name: '$input',
                props: { type: 'float', digits: 2, min: 0 },
              }"
            ></vxe-table-column>
            <vxe-table-column field="diffNum" title="盈亏数量">
              <template #default="{ row }">
                <span
                  class="diff-num"
                  :class="[row.diffNum < 0 ? 'jian-num' : '']"
                >
                  {{ row.diffNum > 0 ? "+" : "" }}{{ row.diffNum }}
                </span>
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="remark"
              title="备注"
              :edit-render="{
                name: 'input',
                placeholder: '说点什么吧',
                attrs: { type: 'text' },
              }"
            ></vxe-table-column>
            <vxe-table-column width="80" title="操作">
              <template #default="{ row, rowIndex }">
                <el-button
                  type="text"
                  size="mini"
                  @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_data.remark"
                  style="width: 360px"
                  placeholder="备注"
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <AllocateGoodsList
      v-if="show_selgoods"
      :is-show="show_selgoods"
      :warehouse-id="form_data.warehouseId"
      @cancel="show_selgoods = false"
      @confirm="selMoreGoods"
    ></AllocateGoodsList>
    <!--    选择仓库-->
    <WarehouseModel
      v-if="warehouse_show"
      :is-check="false"
      :is-show="warehouse_show"
      @confirm="selWarehouse"
      @cancel="warehouse_show = false"
    />
    <!--    库区库位-->
    <CallInLocation
      v-if="storage_show"
      :is-check="false"
      :is-show="storage_show"
      :warehouse-id="form_data.warehouseId"
      :sku-id="skuId"
      :materiel-id="materielId"
      @confirm="selStorage"
      @cancel="storage_show = false"
    />
  </ContainerTit>
</template>

<script>
  import AllocateGoodsList from "@/component/goods/AllocateGoodsList.vue";
  import WarehouseModel from "@/component/common/WarehouseModel.vue";
  import CallInLocation from "@/component/common/CallInLocation";
  import { addPauseSave, getPauseSave, delPauseSave } from "@/api/common";
  import {
    addStocktaking,
    updateStocktaking,
    getStocktakingInfo,
  } from "@/api/Stock";
  import { mapGetters } from "vuex";
  export default {
    name: "PurchaseOrderAdd",
    components: {
      AllocateGoodsList,
      WarehouseModel,
      CallInLocation,
    },
    data() {
      const validateWarehouse = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择仓库"));
        } else {
          callback();
        }
      };
      return {
        skuId: "",
        materielId: "",
        row_index: "",
        storage_show: false,
        loading: false,
        createTime: "",
        no: "",
        del_goods_id: [],
        form_data: {
          warehouseId: "",
          warehouseName: "",
          operatorName: "",
          remark: "",
          stocktakingTime: "",
          details: [],
        },
        fromWarehouse: "",
        rules: {
          warehouseId: [{ required: true, validator: validateWarehouse }],
        },
        warehouse_show: false,
        invenrory_id: "", // 盘点单id
        show_selgoods: false,
        goods_list: [],
        look_path: "",
        activeName: "one",
      };
    },
    computed: {
      plus_goods() {
        let num = 0;
        this.goods_list.forEach((item) => {
          if (item.diffNum > 0) {
            num++;
          }
        });
        return num;
      },
      plus_num() {
        let num = 0;
        this.goods_list.forEach((item) => {
          if (item.diffNum > 0) {
            num = num + Number(item.diffNum);
          }
        });
        return num;
      },
      diff_goods() {
        let num = 0;
        this.goods_list.forEach((item) => {
          if (item.diffNum < 0) {
            num++;
          }
        });
        return num;
      },
      diff_num() {
        let num = 0;
        this.goods_list.forEach((item) => {
          if (item.diffNum < 0) {
            num = num + Number(item.diffNum);
          }
        });
        return num;
      },
      ...mapGetters({
        enableLocationManagement: "MUser/enableLocationManagement",
      }),
    },
    created() {
      this.look_path = this.$route.name;
      if (this.$route.params.id) {
        this.invenrory_id = this.$route.params.id;
        this.getStocktakingInfo();
      } else {
        this.form_data.operatorName = this.userName;
        this.form_data.stocktakingTime = new Date().getTime();
        this.createTime = new Date().getTime();
        this.getPauseSave();
      }
    },
    methods: {
      // 选择仓库
      selWarehouse(val) {
        const row = val[0];
        this.fromWarehouse = row.warehouseName;
        this.form_data.warehouseId = row.id;
        this.form_data.warehouseName = row.warehouseName;
        this.goods_list = [];
      },
      // 新增暂存
      async addPauseSave() {
        const details = this.$_common.deepClone(this.goods_list).map((item) => {
          return item;
        });
        let params = {
          ...this.form_data,
          warehouseName: this.fromWarehouse,
          stocktakingTime: parseInt(this.form_data.stocktakingTime / 1000),
          details: details,
        };
        let target = {};
        this.loading = true;
        const data = await addPauseSave({
          key: this.look_path,
          data: params,
        });
        this.loading = false;

        await this.$message({
          type: "success",
          message: "暂存成功",
        });
        if (this.systemType === 2) {
          await this.$closeCurrentGoEdit(
            "/SingleStore/Inventory/InventoryCheck"
          );
        } else {
          await this.$closeCurrentGoEdit(
            "/stock/WarehouseManagement/inventoryInfo"
          );
        }
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.look_path,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form_data = {
          warehouseId: data.warehouseId,
          warehouseName: data.warehouseName,
          operatorName: data.operatorName,
          remark: data.remark,
          stocktakingTime: data.stocktakingTime,
          details: data.details,
        };
        this.no = data.no;
        this.form_data.stocktakingTime = data.stocktakingTime * 1000;
        // this.createTime = data.createTime * 1000
        this.fromWarehouse = data.warehouseName;
        this.goods_list = data.details.map((item) => {
          return {
            id: item.id,
            materielId: item.materielId,
            materielName: item.materielName,
            materielCode: item.materielCode,
            skuId: item.skuId,
            skuName: item.skuName,
            unitName: item.unitName,
            diffNum: item.diffNum,
            remark: item.remark,
            costUnitPrice: item.costUnitPrice || 0,
            documentInventoryNum: item.documentInventoryNum, // 账面库存
            currentInventoryNum: item.currentInventoryNum, // 实盘库存
            otherNum: item.otherNum, // 其他单位
            areaId: item.areaId,
            areaName: item.areaName,
            areaCode: item.areaCode,
            storageLocationName: item.storageLocationName,
            storageLocationId: item.storageLocationId,
            storageLocationCode: item.storageLocationCode,
          };
        });
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.look_path,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$baseEventBus.$emit("reloadRouterView");
        }
      },
      //  点击保存按钮
      async addPurchaseOrder() {
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            if (!this.goods_list.length) {
              this.$message.warning(`请选择盘点商品`);
              return;
            }
            let issub = true;
            for (let i in this.goods_list) {
              let item = this.goods_list[i];
              if (Number(item.documentInventoryNum) === 0) {
                this.$message.warning(
                  `第【${Number(i) + 1}】条数据，账面库存为0,无法保存`
                );
                issub = false;
                break;
              }
              // if (
              //   this.enableLocationManagement === 5 &&
              //   !item.storageLocationName
              // ) {
              //   issub = false;
              //   this.$message.warning(
              //     `第【${Number(i) + 1}】条数据，未选择库区库位`
              //   );
              //   break;
              // }
            }
            if (!issub) {
              return;
            }
            const details = this.$_common
              .deepClone(this.goods_list)
              .map((item) => {
                delete item.diffNum;
                return item;
              });
            let params = {
              ...this.form_data,
              stocktakingTime: parseInt(this.form_data.stocktakingTime / 1000),
              details: details,
            };
            try {
              this.loading = true;
              if (!this.invenrory_id) {
                // 添加
                const data = await addStocktaking(params);
              } else {
                // 编辑
                params.deleteArray = this.del_goods_id;
                const data = await updateStocktaking(this.invenrory_id, params);
              }
              this.loading = false;
              await this.$message({
                type: "success",
                message: "提交成功",
              });
              await this.delPauseSave();
              if (this.systemType === 2) {
                await this.$closeCurrentGoEdit(
                  "/SingleStore/Inventory/InventoryCheck"
                );
              } else {
                await this.$closeCurrentGoEdit(
                  "/stock/WarehouseManagement/inventoryInfo"
                );
              }
            } finally {
              this.loading = false;
            }
          }
        });
      },
      //  获取详情 getStocktakingInfo
      async getStocktakingInfo() {
        const { data } = await getStocktakingInfo(this.invenrory_id);

        this.form_data = {
          warehouseId: data.warehouseId,
          warehouseName: data.warehouseName,
          operatorName: data.operatorName,
          remark: data.remark,
          stocktakingTime: data.stocktakingTime,
          details: data.details,
        };
        this.no = data.no;
        this.form_data.stocktakingTime = data.stocktakingTime * 1000;
        this.createTime = data.createTime * 1000;
        this.fromWarehouse = data.warehouseName;
        this.goods_list = data.details.map((item) => {
          return {
            id: item.id,
            materielId: item.materielId,
            materielName: item.materielName,
            materielCode: item.materielCode,
            skuId: item.skuId,
            skuName: item.skuName,
            unitName: item.unitName,
            diffNum:
              item.differenceStatus === 4
                ? 0 - item.differenceNum
                : item.differenceNum - 0,
            remark: item.remark,
            costUnitPrice: item.costUnitPrice || 0,
            documentInventoryNum: item.documentInventoryNum, // 账面库存
            currentInventoryNum: item.currentInventoryNum, // 实盘库存
            otherNum: item.otherNum, // 其他单位
            areaId: item.areaId,
            areaName: item.areaName,
            areaCode: item.areaCode,
            storageLocationName: item.storageLocationName,
            storageLocationId: item.storageLocationId,
            storageLocationCode: item.storageLocationCode,
          };
        });
      },
      //  删除
      delData(index, row) {
        this.$confirm("请确认是否删除该商品?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          if (row.id) {
            this.del_goods_id.push(row.id);
          }
          this.goods_list.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      },
      // 改变数量
      editNumChange({ row, rowIndex }) {
        this.goods_list[rowIndex].diffNum = this.$NP.minus(
          row.currentInventoryNum,
          row.documentInventoryNum
        );
      },
      //  选择商品goodData的数据
      selMoreGoods(val) {
        const goodsData = val.map((item) => {
          return {
            isEq: item.isEq,
            otherNum: item.otherNum,
            materielId: item.materielId,
            materielName: item.materielName,
            materielCode: item.materielCode,
            skuId: item.skuId,
            skuName: item.skuName,
            unitName: item.unitName,
            diffNum: 0,
            remark: "",
            costUnitPrice: item.costPrice,
            documentInventoryNum: item.allNum, // 账面库存
            currentInventoryNum: item.inventoryNum, // 实盘库存
            areaId: "",
            areaName: "",
            areaCode: "",
            storageLocationName: "",
            storageLocationId: "",
            storageLocationCode: "",
          };
        });
        if (this.goods_list.length) {
          this.goods_list = this.$_common.unique(
            this.goods_list.concat(goodsData),
            ["materielId", "skuId"]
          );
        } else {
          this.goods_list = goodsData;
        }
      },
      // 合计
      getSummaries(param) {
        return this.$_common.getSummaries(param, ["实盘库存", "盈亏数量"]);
      },
      objectSpanMethod({ columns, data }) {
        const properties = [
          "materielName",
          "materielCode",
          "skuName",
          "unitName",
          "remark",
          "diffNum",
          "storageLocationName",
        ];
        return this.$_common.getSummariesVxe(columns, data, properties);
      },
      // 选择库区库位
      selStorage(e) {
        const target = this.$_common.deepClone(this.goods_list);
        target[this.row_index] = {
          ...target[this.row_index],
          areaId: e[0].areaId,
          areaName: e[0].areaName,
          areaCode: e[0].areaCode,
          storageLocationName: e[0].storageLocationName,
          storageLocationId: e[0].storageLocationId,
          storageLocationCode: e[0].storageLocationCode,
        };
        this.goods_list = target;
      },
      storageShow(row, rowIndex) {
        this.row_index = rowIndex;
        this.materielId = row.materielId;
        this.skuId = row.skuId;
        this.storage_show = true;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .width240 {
    width: 240px;
  }
  .other-price-view {
    padding: 10px 10px 0;
    border: 1px solid #ecf0f7;
    border-top: 0;
  }
  .diff-num {
    font-weight: bold;
    color: #36c1a0;
  }
  .jian-num {
    color: #e84960;
  }
  .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;
  }
  .Enunciate {
    width: 100%;
    height: 72px;
    color: #fff;
    font-size: 16px;
    line-height: 40px;
    padding: 16px 24px;
    border-top: 1px solid #dee2ee;
    .Enunciate_cont {
      background-color: #fa6400;
      border-radius: 3px;
      padding: 0 24px;
    }
  }
</style>
<style>
  .AddInventoryInfo {
    background-color: #fff;
  }
  .AddInventoryInfo .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .AddInventoryInfo .is-active {
    font-weight: 700;
    color: #000;
  }
  .AddInventoryInfo .el-tabs__nav {
    margin-left: 24px;
  }
</style>
