<template>
  <ContainerTit class="storageInfo">
    <div style="position: relative">
      <div class="btn-top-div">
        <el-button
          v-if="
            $accessCheck($Access.storageUpdatePurchaseInStatus) &&
            orderInfo.auditStatus === 1
          "
          type="primary"
          :loading="audit_loading"
          @click="updatePurchaseInStatus"
        >
          入库审核
        </el-button>
        <el-button
          v-if="
            $accessCheck($Access.storageUpdatePurchaseInStatus) &&
            orderInfo.auditStatus === 1 &&
            ['采购入库', '商户入库'].includes(orderInfo.typeName)
          "
          type="warning"
          :loading="audit_loading"
          @click="rejectInventoryTip"
        >
          驳回
        </el-button>
      </div>
    </div>
    <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 class="form" :span="6">
            <span class="form_left">单据编号</span>
            <span class="form_right">{{ orderInfo.no }}</span>
          </el-col>
          <el-col class="form" :span="6">
            <span class="form_left">审核状态</span>
            <span class="form_right">
              <span v-if="orderInfo.auditStatus === 2" class="success-status">
                已审核
              </span>
              <span v-else class="warning-status">待审核</span>
            </span>
          </el-col>
          <el-col class="form" :span="6">
            <span class="form_left">入库类型</span>
            <span class="form_right">{{ orderInfo.typeName }}</span>
          </el-col>
          <el-col v-if="orderInfo.type === 12" class="form" :span="6">
            <span class="form_left">调出仓库</span>
            <span class="form_right">{{ orderInfo.outWarehouseName }}</span>
          </el-col>
          <el-col v-if="orderInfo.type === 12" class="form" :span="6">
            <span class="form_left">调入仓库</span>
            <span class="form_right">{{ orderInfo.inWarehouseName }}</span>
          </el-col>
          <el-col v-if="orderInfo.operatorId" class="form" :span="6">
            <span class="form_left">审核人员</span>
            <span class="form_right">{{ orderInfo.auditName || "--" }}</span>
          </el-col>
          <el-col v-if="orderInfo.operatorId" class="form" :span="6">
            <span class="form_left">审核时间</span>
            <span class="form_right">
              {{
                orderInfo.auditTime
                  ? $_common.formatDate(orderInfo.auditTime)
                  : "---"
              }}
            </span>
          </el-col>
          <el-col
            v-if="orderInfo.operatorId && orderInfo.typeName === '商户入库'"
            class="form"
            :span="6"
          >
            <span class="form_left">商户名称</span>
            <span class="form_right">{{ orderInfo.merchantName || "--" }}</span>
          </el-col>
          <el-col class="form" :span="6">
            <span class="form_left">制单人员</span>
            <span class="form_right">{{ orderInfo.operatorName }}</span>
          </el-col>
          <el-col class="form" :span="6">
            <span class="form_left">制单时间</span>
            <span class="form_right">
              {{
                orderInfo.createTime
                  ? $_common.formatDate(orderInfo.createTime)
                  : "---"
              }}
            </span>
          </el-col>
          <el-col class="form" :span="6">
            <span class="form_left">入库仓库</span>
            <span class="form_right">
              {{ orderInfo.warehouseName }}
            </span>
          </el-col>
          <el-col v-if="orderInfo.auditStatus === 2" class="form" :span="24">
            <span class="form_left">备注说明</span>
            <span class="form_right">
              {{ orderInfo.remark || "无" }}
            </span>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <div class="order_bottom">
      <p class="text">商品清单</p>
      <el-table :summary-method="getSummaries" show-summary :data="queryData">
        <el-table-column
          prop="materielName"
          min-width="180"
          show-overflow-tooltip
          label="商品名称"
        ></el-table-column>
        <el-table-column
          prop="materielCode"
          label="商品编码"
          width="160"
        ></el-table-column>
        <el-table-column prop="unitName" label="规格" min-width="140">
          <template slot-scope="scope">
            {{ scope.row.unitName }};{{ scope.row.skuName }}
          </template>
        </el-table-column>

        <el-table-column
          :label="orderInfo.type === 3 ? '采购数量' : '数量'"
          min-width="120"
          prop="num"
        >
          <template slot-scope="scope">
            {{ $_common.formatNub(scope.row.num) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="orderInfo.type !== 15"
          prop="unitPrice"
          :label="
            orderInfo.type === 3
              ? '采购成本'
              : orderInfo.type === 12
              ? '调拨成本'
              : '退货成本'
              ? '采购成本'
              : '退货单价'
          "
          min-width="140"
        >
          <template slot-scope="scope">
            {{ $_common.formattedNumber(scope.row.unitPrice) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="orderInfo.type !== 15"
          prop="totalPrice"
          :label="
            orderInfo.type === 3
              ? '采购总成本'
              : orderInfo.type === 12
              ? '调拨总成本'
              : '退货总成本'
              ? '采购总成本'
              : '退货总金额'
          "
          min-width="140"
        >
          <template slot-scope="scope">
            {{ $_common.formattedNumber(scope.row.totalPrice) }}
          </template>
        </el-table-column>
        <el-table-column min-width="120" prop="inNum" label="入库数量">
          <template slot-scope="scope">
            <span v-if="orderInfo.auditStatus === 2">
              {{ $_common.formatNub(scope.row.inNum) }}
            </span>
            <el-input-number
              v-else
              v-model="scope.row.inNum"
              size="small"
              style="width: 100%"
              :min="1"
              :controls="false"
              @blur="inNumBlur(scope.$index)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column min-width="120" prop="otherNum" label="其他单位">
          <template slot-scope="scope">
            <span v-if="orderInfo.auditStatus === 2">
              {{
                scope.row.isEq === 5
                  ? $_common.formatNub(scope.row.otherNum)
                  : "--"
              }}
            </span>
            <el-input-number
              v-else-if="scope.row.isEq === 5"
              v-model="scope.row.otherNum"
              style="width: 100%"
              :min="0"
              :controls="false"
            ></el-input-number>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="orderInfo.type === 3 ? '入库成本' : '入库单价'"
          prop="unitPrice"
          min-width="140"
        >
          <template slot-scope="scope">
            <span v-if="orderInfo.auditStatus === 2">
              {{ $_common.formattedNumber(scope.row.inCost) }}
            </span>
            <el-input-number
              v-else
              v-model="scope.row.inCost"
              style="width: 100%"
              :min="0"
              :controls="false"
              @blur="inNumBlur(scope.$index)"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="totalPrice"
          :label="orderInfo.type === 3 ? '入库总成本' : '入库总金额'"
          min-width="140"
        >
          <template slot-scope="scope">
            <span v-if="orderInfo.auditStatus === 2">
              {{ $_common.formattedNumber(scope.row.inCostTotal) }}
            </span>
            <el-input-number
              v-else
              v-model="scope.row.inCostTotal"
              style="width: 100%"
              :min="0"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <!--          // 开启保质期设置，进行保质期验证-->
        <el-table-column
          v-if="shelfLifeSetUp === 5"
          prop="num"
          label="生产日期"
          min-width="140"
        >
          <template slot-scope="scope">
            <div
              v-if="orderInfo.auditStatus !== 2"
              style="cursor: pointer"
              @click="openTimeShow(scope.row)"
            >
              <el-input
                :value="
                  $_common.formatDate(scope.row.productionData, 'yyyy-MM-dd')
                "
                readonly
                placeholder="请选择生产日期"
                suffix-icon="el-icon-date"
              ></el-input>
            </div>
            <div v-else>
              {{ $_common.formatDate(scope.row.productionData, "yyyy-MM-dd") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="enableLocationManagement === 5"
          label="库区库位"
          min-width="160"
        >
          <template slot-scope="scope">
            <div v-if="orderInfo.auditStatus !== 2" style="cursor: pointer">
              <el-input
                v-model="scope.row.storageLocationName"
                placeholder="库区库位"
                style="width: 150px"
                clearable
                readonly
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="storageShow(scope.row, scope.$index)"
                ></i>
              </el-input>
            </div>
            <div v-else>{{ scope.row.storageLocationName || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="barCode"
          label="商品条码"
          min-width="140"
        ></el-table-column>
        <el-table-column
          prop="storage"
          label="货架编码"
          min-width="120"
        ></el-table-column>
        <el-table-column
          v-if="orderInfo.auditStatus !== 2 && [3, 30].includes(orderInfo.type)"
          fixed="right"
          label="操作"
          width="80"
        >
          <template slot-scope="scope">
            <el-button
              :disabled="queryData.length === 1"
              type="text"
              @click="delGoods(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="orderInfo.auditStatus !== 2" class="order_bottom">
      <p class="text">备注说明</p>
      <div style="margin-bottom: 10px">
        <el-input
          v-model="orderInfo.remark"
          :readonly="orderInfo.auditStatus === 2"
          type="textarea"
          placeholder="备注说明"
        ></el-input>
      </div>
    </div>
    <div v-if="orderInfo.auditStatus !== 2" class="order_bottom">
      <p class="text">分摊</p>
      <div style="margin-left: 30px">
        <el-form :inline="true">
          <el-form-item label="分摊方式:">
            <el-select
              v-model="orderInfo.costAllocationType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="费用金额:">
            <el-input-number
              v-model="orderInfo.costAllocation"
              size="small"
              :controls="false"
              :min="0"
              placeholder="请输入费用金额"
            ></el-input-number>
          </el-form-item>
          <el-button
            type="primary"
            :disabled="is_count"
            :loading="loading"
            @click="countPurchaseCost"
          >
            确定分摊
          </el-button>
          <el-button type="warning" @click="delCountPurchaseCost">
            取消分摊
          </el-button>
        </el-form>
      </div>
    </div>
    <ProductionData
      v-if="time_show"
      :show="time_show"
      :goods-data="batch_goods"
      @cancel="time_show = false"
      @confirm="timeEditConfirm"
    ></ProductionData>
    <!--    选择库位-->
    <StorageLocation
      v-if="storage_show"
      :is-check="false"
      :is-show="storage_show"
      :warehouse-id="warehouse_id"
      @confirm="selStorage"
      @cancel="storage_show = false"
    />
  </ContainerTit>
</template>

<script>
  import StorageLocation from "@/component/common/StorageLocation";
  import {
    getPurchaseInInfo,
    updatePurchaseInStatus,
    countPurchaseCost,
    deleteDetailByInventoryInId,
    rejectInventory,
  } from "@/api/Stock";
  import ProductionData from "../component/ProductionData.vue";
  import { mapGetters } from "vuex";
  const goods = {};
  export default {
    name: "StorageInfo",
    components: { ProductionData, StorageLocation },
    data() {
      return {
        sheetCode: "",
        createTime: "", // 制单时间
        operatorId: "", // 人
        warehouseId: "", // 店ID
        mark: "", // 备注
        orderInfo: {
          costAllocationType: 5,
          costAllocation: "",
        },
        queryData: [],
        audit_loading: false,
        is_count: false, // 是否点击过均摊按钮
        options: [
          { value: 4, label: "按数量" },
          { value: 5, label: "按金额" },
        ],

        skuData: [],
        loading: false,
        delete_ids: [],
        time_show: false,
        batch_goods: {},
        storage_show: false,
        warehouse_id: "",
        index: "",
        activeName: "one",
      };
    },
    created() {
      this.getPurchaseInInfo();
    },
    // eslint-disable-next-line vue/order-in-components
    computed: {
      ...mapGetters({
        enableLocationManagement: "MUser/enableLocationManagement",
      }),
    },
    methods: {
      // 入库数量失去焦点
      inNumBlur(index) {
        const list = this.$_common.deepClone(this.queryData);
        list[index].inCostTotal = this.$NP.times(
          list[index].inCost,
          list[index].inNum
        );
        this.queryData = list;
      },
      // 获取详情
      async getPurchaseInInfo() {
        if (!this.$route.params.id) {
          return;
        }
        const data = await getPurchaseInInfo(this.$route.params.id);
        this.orderInfo = data.data;
        this.queryData = data.data.details.map((item) => {
          let inNum = 0;
          if (this.orderInfo.auditStatus === 2) {
            inNum = item.inNum;
          } else {
            inNum = Number(item.inNum) ? Number(item.inNum) : Number(item.num);
          }
          return {
            ...item,
            inCost: Number(item.inCost) || item.unitPrice,
            inCostTotal:
              Number(item.inCostTotal) || this.$NP.times(inNum, item.unitPrice),
            inNum: inNum,
            productionData: item.productionData
              ? item.productionData * 1000
              : new Date().getTime(),
            areaId: item.areaId || "",
            areaName: item.areaName || "",
            areaCode: item.areaCode || "",
            storageLocationId: item.storageLocationId || "",
            storageLocationName: item.storageLocationName || "",
            storageLocationCode: item.storageLocationCode || "",
          };
        });
        console.log(this.queryData);
      },
      //审核入库单
      updatePurchaseInStatus() {
        if (!this.queryData.length) {
          this.$message.warning("没有要入库的商品");
          return;
        }
        // 开启保质期设置，进行保质期验证
        if (this.shelfLifeSetUp === 5) {
          let gindex = 0;
          let gdate = false;
          for (let i in this.queryData) {
            let item = this.queryData[i];
            if (!item.productionData) {
              gindex = i;
              gdate = true;
              break;
            }
          }
          if (gdate) {
            this.$message.warning(`请选择第${Number(gindex) + 1}行的生产日期`);
            return;
          }
        }
        // 判断商品入库数量是否大于采购数量
        let numobj = {};
        for (let i in this.queryData) {
          let item = this.queryData[i];
          if (!numobj[item.skuId]) {
            numobj[item.skuId] = {
              inNum: item.inNum,
              num: Number(item.num),
              materielName: item.materielName,
              skuName: item.unitName + ";" + item.skuName,
            };
          } else {
            numobj[item.skuId].inNum += item.inNum;
          }
        }
        const ismore = Object.values(numobj).some(
          (item) => item.inNum > item.num
        );
        let tip = "确定要审核该入库单吗？";
        if (ismore) {
          tip = "商品的入库数量大于了采购数量，确定要入库吗？";
        }

        this.$confirm(tip, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          let details = this.queryData.map((item) => {
            // let obj = {
            //   id: item.id,
            //   inNum: Number(item.inNum),
            //   inCost: item.inCost,
            //   inCostTotal: item.inCostTotal,
            //   otherNum: item.otherNum,
            // };
            // 开启保质期设置，进行保质期验证
            if (this.shelfLifeSetUp === 5) {
              item.productionData = parseInt(item.productionData / 1000);
            }
            return item;
          });
          let params = {
            id: this.$route.params.id,
            auditName: this.userName,
            remark: this.orderInfo.remark,
            details: details,
            costAllocationType: this.orderInfo.costAllocationType,
            costAllocation: Number(this.orderInfo.costAllocation),
          };
          this.audit_loading = true;
          await this.deleteDetailByInventoryInId();
          try {
            const data = await updatePurchaseInStatus(params);
            this.audit_loading = false;
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            await this.getPurchaseInInfo();
          } catch (e) {
            this.audit_loading = false;
          }
        });
      },
      //确定分摊
      async countPurchaseCost() {
        if (!this.orderInfo.costAllocationType) {
          this.$message.warning("请先选择分摊方式");
          return;
        }
        if (!Number(this.orderInfo.costAllocation)) {
          this.$message.warning("费用金额须大于0");
          return;
        }
        this.skuData = this.queryData.map((item) => {
          return {
            skuId: item.skuId,
            num: Number(item.inNum),
            cost: Number(item.unitPrice),
            money: Number(item.inCostTotal),
          };
        });
        this.loading = true;
        try {
          const { data } = await countPurchaseCost({
            money: this.orderInfo.costAllocation,
            type: this.orderInfo.costAllocationType,
            skuData: this.skuData,
          });
          // 分摊成功
          this.is_count = true;
          this.queryData = this.queryData.map((item) => {
            item.inCost = data[item.skuId].cost;
            item.inCostTotal = data[item.skuId].money;
            return item;
          });
          this.loading = false;
          this.$message.success("分摊成功");
        } catch {
          this.loading = false;
        }
      },
      //取消分摊
      delCountPurchaseCost() {
        // 取消分摊成功
        this.is_count = false;
        this.orderInfo.costAllocation = "";
        this.$message.success("取消分摊成功");
        this.getPurchaseInInfo();
      },
      // 删除商品
      delGoods(index, row) {
        if (row.id) {
          this.delete_ids.push(row.id);
        }
        this.queryData.splice(index, 1);
      },
      async deleteDetailByInventoryInId() {
        if (!this.delete_ids.length) return;
        const { data } = await deleteDetailByInventoryInId({
          inventoryInId: this.$route.params.id,
          inventoryInDetailIds: this.delete_ids,
        });
      },
      openTimeShow(row) {
        this.batch_goods = row;
        this.time_show = true;
      },
      // 分批次入库
      timeEditConfirm(arr) {
        if (!arr.length) {
          return;
        }
        const index = this.queryData.findIndex(
          (item) =>
            item.skuId === arr[0].skuId &&
            item.materielCode === arr[0].materielCode
        );
        if (index > -1) {
          if (this.queryData[index].id) {
            arr[0].id = this.queryData[index].id;
          }
          this.queryData.splice(index, 1);
        }

        this.queryData = this.queryData.concat(arr);
      },
      // 驳回提示
      rejectInventoryTip() {
        this.$confirm("确定要驳回该入库单吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const inventoryInDetailIds = this.queryData.map((item) => {
            return item.id;
          });
          const data = await rejectInventory({
            inventoryInId: this.$route.params.id,
            inventoryInDetailIds: inventoryInDetailIds,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$closeCurrentGoEdit("/stock/OutIn/storage");
        });
      },
      selStorage(e) {
        const target = this.$_common.deepClone(this.queryData);
        target[this.index] = {
          ...target[this.index],
          areaId: e[0].areaId,
          areaName: e[0].areaName,
          areaCode: e[0].areaCode,
          storageLocationId: e[0].id,
          storageLocationName: e[0].name,
          storageLocationCode: e[0].code,
        };
        this.queryData = target;
      },
      storageShow(row, index) {
        this.index = index;
        this.storage_show = true;
        this.warehouse_id = this.orderInfo.warehouseId;
      },
      // 合计
      getSummaries(param) {
        const textPMoney =
          this.orderInfo.type === 3
            ? "采购总成本"
            : this.orderInfo.type === 12
            ? "调拨总成本"
            : "退货总成本"
            ? "采购总成本"
            : "退货总金额";
        const textIMoney =
          this.orderInfo.type === 3 ? "入库总成本" : "入库总金额";
        return this.$_common.getSummaries(param, [
          "采购数量",
          "入库数量",
          textPMoney,
          textIMoney,
        ]);
      },
    },
  };
</script>

<style lang="scss" scoped>
  .table-list-box .goods-info-box p {
    text-align: left;
  }
  .order_bottom {
    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_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>
  .storageInfo {
    background-color: #fff;
  }
  .storageInfo .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .storageInfo .is-active {
    font-weight: 700;
    color: #000;
  }
  .storageInfo .el-tabs__nav {
    margin-left: 24px;
  }
</style>
