<template>
  <ContainerTit class="AddLossReport">
    <div style="position: relative">
      <div v-if="$route.name !== 'LossReportInfo'" 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="addLoss">
          保存
        </el-button>
      </div>
    </div>
    <div>
      <el-form
        ref="form"
        inline
        :model="form"
        size="small"
        :rules="rules"
        :disabled="$route.name === 'LossReportInfo'"
      >
        <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="warehouseName">
                  <el-input
                    v-model="form.warehouseName"
                    placeholder="报损仓库"
                    readonly
                  >
                    <i
                      slot="suffix"
                      class="el-input__icon el-icon-search"
                      @click="openWarehouse"
                    ></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.warehouseId"
            type="primary"
            size="mini"
            @click="choosegoods"
          >
            选择商品
          </el-button>
          <vxe-table
            border="inner"
            resizable
            :data="goods_list"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
            show-footer
            show-overflow
            :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="规格" min-width="80">
              <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"
              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="inventoryNum" title="账目库存">
              <template #default="{ row }">
                {{ $_common.formatNub(row.inventoryNum) }}
              </template>
            </vxe-table-column>
            <vxe-table-column field="inventoryNum" title="当前成本">
              <template #default="{ row }">
                {{ $_common.formatNub(row.lossAmount) }}
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="num"
              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,
                  disabled: other_disables,
                },
              }"
            ></vxe-table-column>
            <vxe-table-column title="报损金额">
              <template #default="{ row }">
                {{ $_common.formatNub($NP.times(row.lossAmount, row.num)) }}
              </template>
            </vxe-table-column>
            <vxe-table-column 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" style="padding: 0 10px">
              <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"
      :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.warehouseId"
      @cancel="show_selgoods = false"
      @confirm="selMoreGoods"
    ></AllocateGoodsList>
    <!--    库区库位-->
    <CallInLocation
      v-if="storage_show"
      :is-check="false"
      :is-show="storage_show"
      :warehouse-id="form.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 { addReportLoss, getReportLossInfo } from "@/api/Stock";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import { mapGetters } from "vuex";
  import CallInLocation from "@/component/common/CallInLocation";
  export default {
    name: "AddLossReport",
    components: {
      AllocateGoodsList,
      WarehouseModel,
      CallInLocation,
    },
    data() {
      const validateFrom = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择所属仓库"));
        } else {
          callback();
        }
      };
      return {
        skuId: "",
        materielId: "",
        row_index: "",
        createTime: "",
        storage_show: false,
        loading: false,
        form: {
          warehouseName: "",
          warehouseId: "",
          operatorName: "",
          remark: "",
        },
        allData: {},
        warehouse_show: false,
        show_selgoods: false,
        goods_list: [],
        rules: {
          warehouseName: [{ required: true, validator: validateFrom }],
        },
        Loss_id: "",
        other_disables: false,
        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.Loss_id = this.$route.params.id;
        this.getReportLossInfo();
      } else {
        this.form.operatorName = this.userName;
        this.getPauseSave();
      }
    },
    methods: {
      openWarehouse() {
        if (this.$route.name === "LossReportInfo") {
          return;
        }
        this.warehouse_show = true;
      },
      // 选择仓库
      selWarehouse(row) {
        this.form.warehouseName = row[0].warehouseName;
        this.form.warehouseId = row[0].id;
        this.goods_list = [];
      },
      //  选择商品goodData的数据
      selMoreGoods(val) {
        const goods = val.map((item) => {
          return {
            isEq: item.isEq,
            otherNum: 0,
            materielId: item.materielId,
            materielCode: item.materielCode,
            materielName: item.materielName,
            warehouseName: this.form.warehouseName,
            skuName: item.skuName,
            skuId: item.skuId,
            unitName: item.unitName,
            inventoryNum: this.$_common.formatNub(item.inventoryNum, 2),
            lossAmount: item.costPrice,
            num: 0,
            areaId: "",
            areaName: "",
            areaCode: "",
            storageLocationName: "",
            storageLocationId: "",
            storageLocationCode: "",
          };
        });
        if (this.goods_list) {
          this.goods_list = this.$_common.unique(
            this.goods_list.concat(goods),
            ["materielId", "skuId"]
          );
        } else {
          this.goods_list = goods;
        }
      },
      // 选择商品
      choosegoods() {
        if (this.form.warehouseId) {
          this.show_selgoods = true;
        }
      },
      // 合计
      getSummaries(param) {
        return this.$_common.getSummaries(param, ["报损数量", "报损金额"]);
      },
      //  删除
      delData(index, row) {
        this.$confirm("你确定删除此商品吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.goods_list.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      },
      //  获取详情
      async getReportLossInfo() {
        const { data } = await getReportLossInfo(this.Loss_id);

        this.allData = data;
        this.createTime = this.$_common.formatDate(data.createTime);
        this.form.warehouseName = data.warehouseName;
        this.form.warehouseId = data.warehouseId;
        this.form.operatorName = data.operatorName;
        this.form.remark = data.remark;
        this.goods_list = data.details.map((item) => {
          return {
            ...item,
            warehouseName: this.form.warehouseName,
          };
        });
      },
      addLoss() {
        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 (
            //     this.enableLocationManagement === 5 &&
            //     !item.storageLocationName
            //   ) {
            //     issub = false;
            //     this.$message.warning(
            //       `第【${Number(i) + 1}】条数据，未选择库区库位`
            //     );
            //     break;
            //   }
            // }
            // if (!issub) {
            //   return;
            // }
            const params = {
              warehouseId: this.form.warehouseId,
              warehouseName: this.form.warehouseName,
              operatorName: this.form.operatorName,
              remark: this.form.remark,
              details: this.goods_list.map((item) => {
                return {
                  materielId: item.materielId,
                  materielName: item.materielName,
                  materielCode: item.materielCode,
                  skuId: item.skuId,
                  unitName: item.unitName,
                  skuName: item.skuName,
                  num: item.num,
                  inventoryNum: item.inventoryNum,
                  lossAmount: item.lossAmount,
                  otherNum: item.otherNum,
                  areaId: item.areaId,
                  areaName: item.areaName,
                  areaCode: item.areaCode,
                  storageLocationName: item.storageLocationName,
                  storageLocationId: item.storageLocationId,
                  storageLocationCode: item.storageLocationCode,
                };
              }),
            };
            try {
              this.loading = true;
              const data = await addReportLoss(params);
              this.loading = false;

              this.$message({
                type: "success",
                message: "提交成功",
              });
              await this.delPauseSave();
              this.$closeCurrentGoEdit("/stock/WarehouseManagement/LossReport");
            } finally {
              this.loading = false;
            }
          }
        });
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.look_path,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/stock/WarehouseManagement/LossReport");
        }
      },
      // 金额变化
      moneyChange(index) {
        let target = this.$_common.deepClone(this.goods_list);
        let lossAmount = target[index].lossAmount;
        let num = target[index].num;
        target[index].lossAmount = this.$NP.times(num, lossAmount);
        this.goods_list = target;
      },
      // 暂存详情
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.look_path,
        });

        if (JSON.stringify(data) === "{}") return;
        this.allData = data;
        this.form.warehouseName = data.warehouseName;
        this.form.warehouseId = data.warehouseId;
        this.form.operatorName = data.operatorName;
        this.form.remark = data.remark;
        this.goods_list = data.details.map((item) => {
          return {
            ...item,
            warehouseName: this.form.warehouseName,
          };
        });
      },
      // 暂存
      async addPauseSave() {
        const params = {
          createTime: this.createTime,
          warehouseId: this.form.warehouseId,
          warehouseName: this.form.warehouseName,
          operatorName: this.form.operatorName,
          remark: this.form.remark,
          details: this.goods_list.map((item) => {
            return {
              materielId: item.materielId,
              materielName: item.materielName,
              materielCode: item.materielCode,
              skuId: item.skuId,
              unitName: item.unitName,
              skuName: item.skuName,
              num: item.num,
              inventoryNum: item.inventoryNum,
              lossAmount: item.lossAmount,
              otherNum: item.otherNum,
              areaId: item.areaId,
              areaName: item.areaName,
              areaCode: item.areaCode,
              storageLocationName: item.storageLocationName,
              storageLocationId: item.storageLocationId,
              storageLocationCode: item.storageLocationCode,
            };
          }),
        };
        try {
          this.loading = true;
          const data = await addPauseSave({
            key: this.look_path,
            data: params,
          });
          this.loading = false;

          this.$message({
            type: "success",
            message: "暂存成功",
          });
          this.$closeCurrentGoEdit("/stock/WarehouseManagement/LossReport");
        } finally {
          this.loading = false;
        }
      },
      objectSpanMethod({ columns, data }) {
        const properties = [
          "inventoryNum",
          "otherNum",
          "materielCode",
          "materielName",
          "unitName",
          "warehouseName",
          "storageLocationName",
        ];
        return this.$_common.getSummariesVxe(columns, data, properties);
      },
      editActivedEvent({ row }) {
        this.other_disables = row.isEq === 4;
      },
      // 选择库区库位
      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-top: 10px;
    border: 1px solid #ecf0f7;
    border-top: 0;
  }
  .order_bottom {
    position: relative;
    border-top: 16px solid #f6f8f9;
    width: 100%;
    background-color: #ffffff;
    border-radius: 3px;
    .order_bottom_btn {
      position: absolute;
      top: 15px;
      right: 20px;
    }
    .text {
      font-size: 16px;
      font-weight: 600;
      color: #2d405e;
      line-height: 64px;
      padding: 0px 24px;
    }
  }
  .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>
  .AddLossReport {
    background-color: #fff;
  }
  .AddLossReport .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .AddLossReport .is-active {
    font-weight: 700;
    color: #000;
  }
  .AddLossReport .el-tabs__nav {
    margin-left: 24px;
  }
</style>
