<template>
  <ContainerTit class="AddMerchantPurchase">
    <div style="position: relative">
      <div class="btn-top-div">
        <el-button
          v-if="look_path !== 'PurchaseOrderLook'"
          :loading="loading"
          :disabled="!!$route.params.id"
          @click="delPauseSave(1)"
        >
          清除暂存
        </el-button>
        <el-button
          v-if="look_path !== 'PurchaseOrderLook'"
          :loading="loading"
          :disabled="!!$route.params.id"
          @click="addPauseSave"
        >
          暂存
        </el-button>
        <el-button
          v-if="look_path !== 'PurchaseOrderLook'"
          type="primary"
          :loading="loading"
          @click="addPurchaseOrder"
        >
          保存
        </el-button>
        <el-button
          v-if="look_path === 'PurchaseOrderLook'"
          type="primary"
          :disabled="auditStatus === 2"
          :loading="loading"
          @click="updatePurchase"
        >
          审核
        </el-button>
      </div>
    </div>
    <div>
      <el-form
        ref="form"
        :inline="true"
        :rules="purchase_rules"
        :model="form"
        size="small"
        :disabled="look_path === 'PurchaseOrderLook'"
      >
        <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="!!$route.params.id"
                class="form"
                :span="6"
                style="margin-bottom: 0"
              >
                <el-form-item label="采购单号:" prop="code">
                  {{ form.code }}
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item label="采购仓库" prop="warehouseName">
                  <div v-if="look_path !== 'PurchaseOrderLook'">
                    <el-input
                      v-model="form.warehouseName"
                      placeholder="采购仓库"
                      readonly
                    >
                      <i
                        slot="suffix"
                        class="el-input__icon el-icon-search"
                        @click="openWarehouse()"
                      ></i>
                    </el-input>
                  </div>
                  <span v-else>{{ form.warehouseName }}</span>
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item
                  label="采购人员:"
                  prop="buyerId"
                  style="min-width: 400px"
                >
                  <div v-if="look_path !== 'PurchaseOrderLook'">
                    <el-input
                      v-model="form.buyerName"
                      placeholder="采购人员"
                      style="width: 210px"
                      readonly
                    >
                      <i
                        slot="suffix"
                        class="el-input__icon el-icon-search"
                        @click="staff_show = true"
                      ></i>
                    </el-input>
                    <el-button
                      type="text"
                      size="mini"
                      @click="add_staff = true"
                    >
                      【新建人员】
                    </el-button>
                  </div>
                  <span v-else>{{ form.buyerName }}</span>
                </el-form-item>
              </el-col>
              <el-col class="form" :span="6" style="margin-bottom: 0">
                <el-form-item v-if="systemType !== 3" label="商户:" prop="name">
                  <div v-if="look_path !== 'PurchaseOrderLook'">
                    <el-input
                      v-model="form.merchantName"
                      placeholder="请选择商户"
                      style="width: 210px"
                      readonly
                    >
                      <i
                        slot="suffix"
                        class="el-input__icon el-icon-search"
                        @click="mearchant_show = true"
                      ></i>
                    </el-input>
                  </div>
                  <span v-else>{{ name }}</span>
                </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>{{ $_common.formatDate(createTime) }}</span>
                </el-form-item>
              </el-col>
              <el-col v-if="auditStatus === 2" class="form" :span="6">
                <el-form-item label="审核人员：">
                  {{ auditName }}
                </el-form-item>
              </el-col>
              <el-col v-if="auditStatus === 2" class="form" :span="6">
                <el-form-item label="审核时间：">
                  <span>{{ $_common.formatDate(auditTime) }}</span>
                </el-form-item>
              </el-col>
              <el-col
                v-if="look_path === 'PurchaseOrderLook' && auditStatus === 2"
                class="form"
                :span="6"
              >
                <el-form-item label="审核状态：">
                  <el-tag
                    v-if="
                      look_path === 'PurchaseOrderLook' && auditStatus === 2
                    "
                    type="success"
                  >
                    已审核
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            <el-alert
              v-if="err_tip_list.length"
              title="采购数量换算提示"
              type="error"
              show-icon
              close-text="知道了"
            >
              <ul>
                <li v-for="(item, index) in err_tip_list" :key="index">
                  商品【{{ item.goodsName }}】，单位【{{
                    item.unitName
                  }}】，编码【{{ item.goodsCode }}】，数量换算有误：{{
                    item.title
                  }}
                </li>
              </ul>
            </el-alert>
          </el-tab-pane>
        </el-tabs>
        <div class="order_bottom">
          <p class="text">商品清单</p>
          <el-table
            :data="goods_list"
            show-summary
            size="mini"
            :summary-method="getSummaries"
          >
            <el-table-column
              label="#"
              width="60"
              type="index"
            ></el-table-column>
            <el-table-column
              label="商品编码"
              width="140"
              prop="goodsCode"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="goodsName" label="商品名称" min-width="180">
              <template slot-scope="scope">
                <span v-if="look_path !== 'MerchantPurchaseDetail'">
                  <ConditionSelGoods
                    v-model="scope.row.goodsName"
                    :merchant-id="form.merchantId"
                    :type="true"
                    :is-reveal-sku="4"
                    :enable-status="5"
                    :is-add-goods="5"
                    :spec-check="spec_check"
                    @selGoods="selGoods"
                    @goodsVisibleChange="
                      goodsVisibleChange($event, scope.$index)
                    "
                    @specSelConfirm="specSelConfirm"
                  />
                </span>
                <span v-else>
                  {{ scope.row.goodsName }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="specGropName" label="规格" min-width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.unitName">{{ scope.row.unitName }};</span>
                <span>{{ scope.row.specGropName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="buyerNum" label="采购数量" min-width="100">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.buyerNum"
                  style="width: 100%"
                  size="mini"
                  :min="0"
                  type="text"
                  placeholder="数量"
                  :controls="false"
                  @blur="editNumChange(scope.$index, 'buyerNum')"
                />
              </template>
            </el-table-column>
            <el-table-column prop="buyerNum" label="其他单位" min-width="100">
              <template slot-scope="scope">
                <el-input-number
                  v-if="scope.row.isEq === 5"
                  v-model="scope.row.otherNum"
                  style="width: 100%"
                  size="mini"
                  :min="0"
                  type="text"
                  placeholder="其他单位"
                  :controls="false"
                  @blur="editNumChange(scope.$index, 'buyerNum')"
                />
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="skuValue"
              label="换算比例数量"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="skuNum"
              label="转换数量"
              min-width="80"
            ></el-table-column>
            <el-table-column
              prop="buyerUnitPrice"
              label="采购单价"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.buyerUnitPrice"
                  size="mini"
                  style="width: 100%"
                  :controls="false"
                  :min="0"
                  type="text"
                  placeholder="单价"
                  @blur="editNumChange(scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="subtotalPrice"
              label="小计金额"
              min-width="100"
            >
              <template slot-scope="scope">
                {{ $_common.formattedNumber(scope.row.subtotalPrice) }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="look_path === 'PurchaseOrderLook'"
              prop="storage"
              label="货架编码"
              min-width="100"
            ></el-table-column>
            <el-table-column
              v-if="look_path === 'PurchaseOrderLook'"
              prop="barCode"
              label="商品条码"
              min-width="100"
            ></el-table-column>
            <el-table-column
              v-if="look_path !== 'PurchaseOrderLook'"
              label="管理"
              fixed="right"
              width="160"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  :disabled="goods_list.length === 1"
                  @click="delData(scope.$index, scope.row)"
                >
                  删除
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="otherSet(scope.$index, scope.row)"
                >
                  同步
                </el-button>
                <!--                <el-button-->
                <!--                  v-if="look_path !== 'PurchaseOrderLook'"-->
                <!--                  type="text"-->
                <!--                  size="mini"-->
                <!--                  @click="addListGoods"-->
                <!--                >-->
                <!--                  新增-->
                <!--                </el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <div v-if="look_path !== 'PurchaseOrderLook'" class="table-b-div">
            <div class="table-b-div-cont" @click="addListGoods">
              <el-button type="text" size="mini" @click="addListGoods">
                <i class="el-icon-plus"></i>
                新增
              </el-button>
            </div>
          </div>
          <div class="clearfix other-price-view">
            <div class="float_left">
              <el-form-item label="备注：">
                <el-input
                  v-model="form.remark"
                  style="width: 360px"
                  size="small"
                  placeholder="备注"
                ></el-input>
              </el-form-item>
            </div>
            <div class="float_right">
              <el-form-item label="其他金额：">
                <el-input-number
                  v-model="form.otherAmount"
                  style="width: 100px"
                  size="small"
                  :controls="false"
                  :min="0"
                  placeholder="其他金额"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="优惠金额：">
                <el-input-number
                  v-model="form.couponAmount"
                  style="width: 100px"
                  size="small"
                  :controls="false"
                  :min="0"
                  :max="purchaseAmount"
                  placeholder="优惠金额"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="采购金额：">
                <el-input
                  v-model="purchaseAmount"
                  style="width: 100px"
                  size="small"
                  placeholder="采购金额"
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <!--    新增员工-->
    <AddStaff
      v-if="add_staff"
      :visible="add_staff"
      @close="add_staff = false"
    />
    <StaffList
      v-if="staff_show"
      :is-show="staff_show"
      :is-check="false"
      :isserch="true"
      @cancel="staff_show = false"
      @confirm="staffSel"
    />
    <!--    新建商户-->
    <!--    <AddMearchantList-->
    <!--      v-if="add_merchant"-->
    <!--      :show="add_merchant"-->
    <!--      @close="add_merchant = false"-->
    <!--    />-->
    <!--    选择仓库-->
    <WarehouseModel
      v-if="warehouse_show"
      :is-check="false"
      :is-show="warehouse_show"
      @confirm="selWarehouse"
      @cancel="warehouse_show = false"
    />
    <!--    选择商户-->
    <MearchantList
      v-if="mearchant_show"
      :is-show="mearchant_show"
      @confirmMerchant="confirmMerchant"
      @cancelMerchant="mearchant_show = false"
    />

    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="选择属性"
      :visible.sync="spec_model"
      width="40%"
    >
      <el-checkbox
        v-model="check_all_spec"
        :indeterminate="is_spec_indeterminate"
        @change="checkAllSpecChange"
      >
        全选
      </el-checkbox>
      <div style="margin: 15px 0"></div>
      <el-checkbox-group v-model="spec_check" @change="specCheckChange">
        <el-checkbox
          v-for="(item, index) in spec_check_list"
          :key="index"
          style="padding-bottom: 5px"
          :label="item.id"
        >
          {{ item.specGropName }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="spec_model = false">取 消</el-button>
        <el-button type="primary" @click="specSelConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </ContainerTit>
</template>

<script>
  import { mapGetters } from "vuex";

  import MearchantList from "@/component/common/MearchantList.vue";
  // import AddMearchantList from "@/component/common/AddMerchantList";
  import WarehouseModel from "@/component/common/WarehouseModel.vue";
  // 新增员工
  import AddStaff from "@/component/SystemSettings/AddStaff";
  import StaffList from "@/component/common/staffListModal";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  import { getAllWarehouse, getMasterSkuNum } from "@/api/Stock";
  import {
    updatePurchaseStatus,
    getPurchaseInfoById,
    editPurchase,
    addPurchase,
  } from "@/api/Purchase";
  import {
    getMoneyPauseSave,
    addMoneyPauseSave,
    addPauseSave,
    getPauseSave,
    delPauseSave,
  } from "@/api/common";

  const goods = {
    basicGoodsId: "",
    goodsCode: "",
    goodsName: "",
    skuId: "",
    unitName: "",
    categoryId: "",
    categoryName: "",
    buyerNum: 0,
    buyerUnitPrice: 0,
    subtotalPrice: 0,
    couponAmount: 0,
    otherAmount: 0,
  };
  export default {
    name: "PurchaseOrderAdd",
    components: {
      // AddMearchantList,
      WarehouseModel,
      MearchantList,
      ConditionSelGoods,
      AddStaff, // 新增员工
      StaffList,
    },
    data() {
      const validateShop = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择采购仓库"));
        } else {
          callback();
        }
      };
      const validateSupplier = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择商户"));
        } else {
          callback();
        }
      };
      return {
        good_name: true,
        add_merchant: false,
        mearchant_show: false,
        err_tip_list: [], // 错误提示
        now_goods_data: {},
        spec_check: [],
        auditTime: "",
        spec_check_list: [],
        show_goods: false, // 选择商品弹窗
        select_loading: false,
        check_all_spec: false,
        is_spec_indeterminate: false,
        spec_model: false,
        add_staff: false, // 新增员工
        loading: false,
        createTime: new Date().getTime(),
        auditName: "",
        auditId: "",
        auditStatus: "",
        look_path: "",
        goods_options: [],
        del_goods_id: [],
        warehouse_list: [],
        form: {
          code: "",
          shopId: "",
          shopName: "",
          supplierId: "",
          supplierName: "",
          buyerId: "",
          buyerName: "",
          operatorName: "",
          couponAmount: 0,
          otherAmount: 0,
          remark: "",
          goodsData: [],
          warehouseName: "",
          warehouseId: "",
          merchantId: "",
          merchantName: "",
          purchaseType: 5,
        },
        supplier_show: false,
        purchase_list: [], // 采购人员列表
        purchase_rules: {
          warehouseName: [{ required: true, validator: validateShop }],
          supplierName: [{ required: true, validator: validateSupplier }],
          buyerId: [
            { required: true, message: "请选择采购人员", trigger: "change" },
          ],
        },
        goods_list: [],
        pusrchase_id: "",
        goods_index: 0,
        warehouse_show: false,
        staff_show: false,
        options: [
          { value: 1, label: "按数量" },
          { value: 2, label: "按金额" },
        ],
        options_value: "",
        contributions: "",
        apportionFlag: false,
        activeName: "one",
      };
    },
    computed: {
      purchaseAmount() {
        let sum = 0;
        if (this.goods_list.length > 1) {
          this.goods_list.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.subtotalPrice));
          });
        } else if (this.goods_list.length === 1) {
          sum = Number(this.goods_list[0].subtotalPrice);
        } else {
          sum = 0;
        }
        return (
          this.$NP.plus(
            sum,
            this.$NP.minus(this.form.otherAmount, this.form.couponAmount)
          ) || 0
        );
      },
      ...mapGetters({
        storeData: "MUser/storeData",
      }),
    },
    created() {
      if (this.systemType === 3) {
        this.form.merchantId = this.storeData.merchantData.id;
        this.form.merchantName = this.storeData.merchantData.name;
      }
      //  获取当前的路由，截取
      this.look_path = this.$route.name;
      if (this.$route.params.id) {
        this.pusrchase_id = this.$route.params.id;
        //    调用详情接口
        this.getPurchaseInfoById();
      } else {
        this.form.operatorName = this.userName;
        if ([2, 3].includes(this.systemType)) {
          this.form.shopId = this.storeData.id; // 店铺
          this.form.shopName = this.storeData.name; // 店铺
        }
        this.getPauseSave();
      }
      for (let i = 1; i <= 1; i++) {
        this.goods_list.push(this.$_common.deepClone(goods));
      }
    },
    methods: {
      // 选择商户确定
      confirmMerchant(row) {
        if (!!this.pusrchase_id) {
          this.del_goods_id = this.$_common
            .deepClone(this.goods_list)
            .map((item) => {
              return item.id;
            })
            .filter((item) => !!item);
        }
        this.goods_list = [];
        this.goods_list.push(this.$_common.deepClone(goods));
        this.form.merchantId = row.id;
        this.form.merchantName = row.name;
        if (this.form.merchantId !== "") {
          this.good_name = false;
        }
      },
      openWarehouse() {
        this.warehouse_show = true;
      },
      selWarehouse(row) {
        this.form.warehouseName = row[0].warehouseName;
        this.form.warehouseId = row[0].id;
      },
      staffSel(row) {
        this.form.buyerName = row[0].staffName;
        this.form.buyerId = row[0].id;
      },
      shopDefault(val, row) {
        this.form.shopId = val;
        this.form.shopName = row.name;
      },
      // 审核状态  updatePurchaseStatus
      async updatePurchase(row) {
        const params = {
          auditStatus: "2",
          auditName: this.userName,
        };
        this.$confirm("确定审核该订单", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await updatePurchaseStatus(this.pusrchase_id, params);

          this.$message({
            type: "success",
            message: "操作成功!",
          });
          await this.getPurchaseInfoById();
        });
      },
      specCheckChange(value) {
        let checkedCount = value.length;
        this.check_all_spec = checkedCount === this.spec_check_list.length;
        this.is_spec_indeterminate =
          checkedCount > 0 && checkedCount < this.spec_check_list.length;
      },
      checkAllSpecChange(val) {
        this.spec_check = val
          ? this.spec_check_list.map((item) => item.id)
          : [];
        this.is_spec_indeterminate = false;
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      //换算sku数量
      async getSkuNum() {
        const skuNum = this.goods_list
          .map((item) => {
            return {
              skuId: item.skuId,
              goodsBasicId: item.basicGoodsId,
              num: item.buyerNum || 1,
            };
          })
          .filter((item) => item.skuId);
        if (!skuNum.length) {
          return;
        }
        const { data } = await getMasterSkuNum(skuNum);
        this.goods_list = this.goods_list.map((item) => {
          let obj = {};
          if (data[item.skuId]) {
            obj = {
              title: data[item.skuId].title || "",
              buyerNum: data[item.skuId].num,
              skuValue: data[item.skuId].skuValue,
              skuNum: data[item.skuId].masterNum + data[item.skuId].masterName,
            };
          }
          return {
            ...item,
            ...obj,
          };
        });
        this.err_tip_list = this.goods_list.filter((item) => !!item.title);
        // 如果没有商品选择框则新增一个
        if (!this.goods_list.find((item) => !item.skuId)) {
          // 新增一个商品选择框
          this.addListGoods();
        }
      },
      // 多选商品确定
      selGoods(list) {
        let target = this.$_common.deepClone(this.goods_list);
        const goodsD = list.map((item) => {
          let specGropName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            spec_check_list: [],
            basicGoodsId: item.id,
            goodsCode: item.code,
            goodsName: item.title,
            skuId: item.skuId,
            specGropName: specGropName,
            unitName: item.unitName,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            buyerNum: 1,
            buyerUnitPrice: 0.1,
            subtotalPrice: 0.1,
            couponAmount: 0,
            otherAmount: 0,
            mearchantId: "",
          };
        });
        // 判断是否有内容
        const isBase = target.some((item) => {
          return item.basicGoodsId;
        });
        if (!isBase) {
          target = goodsD;
        } else {
          target = this.$_common.unique(target.concat(goodsD), [
            "basicGoodsId",
            "skuId",
          ]);
        }
        const skuIdArr = target.map((item) => {
          return item.skuId;
        });
        this.pricePauseSave(skuIdArr, target);
      },
      specSelConfirm(params) {
        if (!params.goodsD[0].skuId) {
          this.$message.warning("至少选择一项");
          return;
        }
        let target = this.$_common.deepClone(this.goods_list);
        const goodsD = params.goodsD.map((item) => {
          return {
            basicGoodsId: params.now_goods_data.id,
            goodsCode: params.now_goods_data.code,
            goodsName: params.now_goods_data.title,
            skuId: item.skuId,
            specGropName: item.spec.specGropName,
            unitName: item.spec.unitName,
            categoryId: params.now_goods_data.categoryId,
            categoryName: params.now_goods_data.categoryTitle,
            buyerNum: 1,
            buyerUnitPrice: 0.1,
            subtotalPrice: 0.1,
            couponAmount: 0,
            otherAmount: 0,
            mearchantId: this.mearchantId,
          };
        });
        if (!target[this.goods_index].skuId) {
          target.splice(this.goods_index, 1);
        }
        goodsD.forEach((item) => {
          const targetD = target.find((itemG) => itemG.skuId === item.skuId);
          if (!targetD) {
            target.push(item);
          }
        });
        const goodsData = this.$_common.unique(target, [
          "basicGoodsId",
          "skuId",
        ]);
        const skuIdArr = goodsData.map((item) => {
          return item.skuId;
        });
        this.pricePauseSave(skuIdArr, goodsData);
        this.spec_model = false;
      },
      // 价格暂存查询
      async pricePauseSave(skuId, goodsData) {
        goodsData = goodsData.filter((item) => item.skuId);
        const { data } = await getMoneyPauseSave({
          skuIds: skuId,
        });

        this.goods_list = goodsData.map((item) => {
          return {
            ...item,
            buyerUnitPrice:
              item.buyerUnitPrice > 0.1
                ? item.buyerUnitPrice
                : data[item.skuId] || 0.1,
            subtotalPrice:
              item.subtotalPrice > 0.1
                ? item.subtotalPrice
                : data[item.skuId] || 0.1,
          };
        });
        // 获取sku换算关系
        await this.getSkuNum();
      },
      // 价格暂存提交
      async addMoneyPauseSave(priceData) {
        const data = await addMoneyPauseSave({
          data: priceData,
        });
      },
      addListGoods() {
        this.goods_list.push(this.$_common.deepClone(goods));
      },
      // 改变数量
      editNumChange(index, tag) {
        const target = this.$_common.deepClone(this.goods_list);
        target[index].subtotalPrice = this.$NP.times(
          target[index].buyerNum || 1,
          target[index].buyerUnitPrice
        );
        this.goods_list = target;
        if (!target[index].skuId) return;
        if (tag === "buyerNum") {
          // 获取sku换算关系
          this.getSkuNum();
        }
      },
      // 一键批量设置
      otherSet(index, row) {
        const target = this.$_common.deepClone(this.goods_list);
        target.forEach((item) => {
          if (
            item.basicGoodsId === row.basicGoodsId &&
            item.unitName === row.unitName
          ) {
            item.buyerNum = row.buyerNum;
            item.subtotalPrice = row.subtotalPrice;
            item.buyerUnitPrice = row.buyerUnitPrice;
          }
        });
        this.goods_list = target;
        this.getSkuNum();
      },
      // 添加暂存
      async addPauseSave() {
        const params = {
          ...this.form,
          goodsData: this.goods_list,
        };
        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/purchase/purchaseList");
        } else {
          this.$closeCurrentGoEdit("/Purchase/ManageP/PurchaseOrder");
        }
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.look_path,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form = data;
        this.goods_list = data.goodsData;
        // 获取sku换算关系
        this.getSkuNum();
      },

      //  详情接口
      async getPurchaseInfoById() {
        const { data } = await getPurchaseInfoById(this.pusrchase_id);
        this.form.code = data.no;
        this.createTime = data.createTime;
        this.form.shopId = data.shopId;
        this.form.shopName = data.shopName;
        this.form.supplierId = data.supplierId;
        this.form.supplierName = data.supplierName;
        this.form.buyerId = data.buyerId;
        this.form.buyerName = data.buyerName;
        this.form.operatorName = data.operatorName;
        this.form.purchaseAmount = data.purchaseAmount;
        this.form.couponAmount = data.couponAmount;
        this.form.otherAmount = data.otherAmount;
        this.form.remark = data.remark;
        this.auditId = data.auditId;
        this.auditName = data.auditName;
        this.auditStatus = data.auditStatus;
        this.auditTime = data.auditTime;
        this.form.warehouseId = data.warehouseId;
        this.form.merchantId = data.merchantId;
        this.form.merchantName = data.merchantName;
        this.form.warehouseName = data.warehouseName;
        // 商品
        this.goods_list = data.details.map((item) => {
          return {
            ...item,
            skuId: item.skuId,
            specGropName: item.skuName,
          };
        });
        // 获取sku换算关系
        await this.getSkuNum();
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.look_path,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/Purchase/ManageP/PurchaseOrderAdd");
        }
      },
      // 添加
      async addPurchaseOrder() {
        // console.log(this.goods_list);
        if (this.form.couponAmount > this.purchaseAmount) {
          this.$message.warning("优惠金额不能大于采购金额 ");
          return;
        }
        if (!this.form.otherAmount) {
          this.form.otherAmount = 0;
        }
        if (!this.form.couponAmount) {
          this.form.couponAmount = 0;
        }
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            const goodsList = this.$_common
              .deepClone(this.goods_list)
              .filter((item) => item.skuId > 0);
            if (!goodsList.length) {
              this.$message.warning("请选择商品");
              return;
            }
            const isbuyerNum = goodsList.every((item) => item.buyerNum > 0);
            if (!isbuyerNum) {
              this.$message.warning("采购数量必须大于0");
              return;
            }
            const isbuyerUnitPrice = goodsList.every(
              (item) => item.buyerUnitPrice > 0
            );
            if (!isbuyerUnitPrice) {
              this.$message.warning("采购单价必须大于0");
              return;
            }
            let goodsData = goodsList.map((item) => {
              let goods = {
                basicGoodsId: item.basicGoodsId,
                goodsCode: item.goodsCode,
                goodsName: item.goodsName,
                skuId: item.skuId,
                unitName: item.unitName,
                skuName: item.specGropName,
                buyerNum: item.buyerNum,
                buyerUnitPrice: item.buyerUnitPrice,
                subtotalPrice: item.subtotalPrice,
                couponAmount: item.couponAmount - 0,
                otherAmount: item.otherAmount - 0,
                categoryId: item.categoryId,
                categoryName: item.categoryName,
                otherNum: item.otherNum,
              };
              if (item.id) {
                goods.id = item.id;
              }
              return goods;
            });

            const params = {
              ...this.form,
              goodsData: goodsData,
            };
            if (this.goods_list.length > 0) {
              this.loading = true;
              try {
                let target = {};
                if (this.pusrchase_id) {
                  params.deleteArray = this.del_goods_id;
                  // console.log(params);
                  target = await editPurchase(this.pusrchase_id, params);
                } else {
                  target = await addPurchase(params);
                }
                const data = target;
                this.loading = false;
                this.$message({
                  type: "success",
                  message: "提交成功",
                });
                await this.delPauseSave();
                if (this.systemType === 2) {
                  this.$closeCurrentGoEdit(
                    "/SingleStore/purchase/purchaseList"
                  );
                } else {
                  this.$closeCurrentGoEdit("/Purchase/ManageP/Merchant");
                }
              } finally {
                this.loading = false;
              }
            } else {
              this.$message("请选择商品");
            }
            // 价格暂存添加
            const priceData = goodsData.map((item) => {
              return {
                skuId: item.skuId,
                money: item.buyerUnitPrice,
              };
            });
            await this.addMoneyPauseSave(priceData);
          }
        });
      },
      delData(index, row) {
        if (row.id) {
          this.del_goods_id.push(row.id);
        }
        if (this.goods_list.length === 1) {
          this.$message.warning("必须保留一条");
          return;
        }
        this.goods_list.splice(index, 1);
      },
      selShop(val, row) {
        this.form.shopName = row[0].name;
      },
      // 选择商户
      mearchant() {
        this.mearchant_show = true;
      },
      // 合计
      getSummaries(param) {
        return this.$_common.getSummaries(param, ["小计金额", "采购数量"]);
      },
    },
  };
</script>

<style lang="scss" scoped>
  .other-price-view {
    padding-top: 10px;
    border: 1px solid #ecf0f7;
    border-top: 0;
    padding-left: 10px;
  }
  .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;
    }
  }
  .table-b-div {
    height: 80px;
    width: 100%;
    padding: 16px 24px 32px 25px;
    border: 1px solid #ebeef5;
    text-align: center;
    line-height: 40px;
    border-top: 0 none;
    cursor: pointer;
    .table-b-div-cont {
      border: 1px dashed #2153d4;
    }
  }
  .btn-top-div {
    position: absolute;
    right: 20px;
    top: 15px;
    z-index: 999;
  }
</style>
<style>
  .AddMerchantPurchase {
    background-color: #fff;
  }
  .AddMerchantPurchase .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .AddMerchantPurchase .is-active {
    font-weight: 700;
    color: #000;
  }
  .AddMerchantPurchase .el-tabs__nav {
    margin-left: 24px;
  }
</style>
