<template>
  <ContainerTit>
    <div slot="headr">
      <el-button type="primary" :loading="loading" @click="submitData">
        保存
      </el-button>
    </div>
    <div class="detail-tab-main" style="background-color: #fff; padding: 20px">
      <div style="padding-bottom: 10px" class="clearfix">
        <div class="float_left">
          <el-input
            v-model="customer_type_name"
            style="width: 260px"
            size="small"
            placeholder="请选择客户类型"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="customer_type_show = true"
            ></i>
          </el-input>
          <el-button
            size="mini"
            type="text"
            @click="customer_type_add_show = true"
          >
            【新建客户类型】
          </el-button>
        </div>
        <div class="float_right">
          <el-button v-if="!show_set" type="text" @click="show_set = true">
            批量设置
          </el-button>
          <div v-else>
            <el-select
              v-model="adjPricetag"
              style="width: 60px; display: inline-block; margin-right: 5px"
              size="mini"
              placeholder="请选择"
            >
              <el-option
                v-for="(tag, tagi) in adjPricetag_list"
                :key="tagi"
                :label="tag.label"
                :value="tag.value"
              ></el-option>
            </el-select>
            <el-input-number
              v-model="price_num"
              style="width: 90px"
              :controls="false"
              size="mini"
            ></el-input-number>
            <el-button type="primary" @click="betchSet">确定</el-button>
            <el-button type="text" @click="show_set = false">取消</el-button>
          </div>
        </div>
      </div>
      <el-table :data="goods_data" style="width: 100%">
        <el-table-column
          prop="goodsCode"
          label="商品编码"
          min-width="180"
        ></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" min-width="180">
          <template slot-scope="scope">
            <ConditionSelGoods
              v-if="!!customer_type_name"
              v-model="scope.row.goodsName"
              :shop-id="shop_id"
              :spec-check="spec_check"
              @goodsVisibleChange="goodsVisibleChange($event, scope.$index)"
              @specSelConfirm="specSelConfirm"
              @selGoods="selGoods"
            />
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="规格" min-width="140">
          <template slot-scope="scope">
            {{ scope.row.unitName }};{{ scope.row.specGropName }}
          </template>
        </el-table-column>
        <el-table-column prop="nowPrice" label="调整价格" min-width="300">
          <template slot-scope="scope">
            <div v-if="scope.row.goodsId">
              <div v-if="!scope.row.enabledLadder" class="ladder-li">
                <span class="price-span">
                  <span
                    v-if="parseInt(scope.row.salePrice[0].adjPricetag) === 1"
                  >
                    {{
                      $NP.minus(
                        scope.row.nowPrice,
                        scope.row.salePrice[0].price
                      )
                    }}
                  </span>
                  <span
                    v-else-if="
                      parseInt(scope.row.salePrice[0].adjPricetag) === 2
                    "
                  >
                    {{
                      $NP.plus(scope.row.nowPrice, scope.row.salePrice[0].price)
                    }}
                  </span>
                  <span
                    v-else-if="
                      parseInt(scope.row.salePrice[0].adjPricetag) === 3
                    "
                  >
                    {{
                      $NP.times(
                        scope.row.nowPrice,
                        scope.row.salePrice[0].price
                      )
                    }}
                  </span>
                  <span v-else>
                    {{ scope.row.nowPrice }}
                  </span>
                </span>
                <el-select
                  v-model="scope.row.salePrice[0].adjPricetag"
                  style="width: 60px; display: inline-block; margin: 0 5px"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(tag, tagi) in adjPricetag_list"
                    :key="tagi"
                    :label="tag.label"
                    :value="tag.value"
                  ></el-option>
                </el-select>
                <el-input-number
                  v-model="scope.row.salePrice[0].price"
                  style="width: 90px"
                  :controls="false"
                ></el-input-number>
              </div>
              <div v-else>
                <div
                  v-for="(price, index) in scope.row.salePrice[0].ladderPrice"
                  :key="index"
                  class="ladder-li"
                >
                  <span class="price-span">{{ price.from }}</span>
                  <span style="font-size: 12px; margin: 0 4px">至</span>
                  <span
                    v-if="
                      index === scope.row.salePrice[0].ladderPrice.length - 1
                    "
                    class="price-span"
                  >
                    ∞
                  </span>
                  <span v-else class="price-span">{{ price.to }}</span>
                  =
                  <span style="margin-right: 5px" class="price-span">
                    <span v-if="parseInt(price.adjPricetag) === 1">
                      {{ $NP.minus(price.price, price.adjPrice) }}
                    </span>
                    <span v-else-if="parseInt(price.adjPricetag) === 2">
                      {{ $NP.plus(price.price, price.adjPrice) }}
                    </span>
                    <span v-else-if="parseInt(price.adjPricetag) === 3">
                      {{ $NP.times(price.price, price.adjPrice) }}
                    </span>
                    <span v-else>
                      {{ price.price }}
                    </span>
                  </span>
                  <el-select
                    v-model="price.adjPricetag"
                    style="width: 60px; display: inline-block"
                    size="small"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(tag, tagi) in adjPricetag_list"
                      :key="tagi"
                      :label="tag.label"
                      :value="tag.value"
                    ></el-option>
                  </el-select>
                  <!-- 如果做减法，最大值只能为当前的价格-->
                  <el-input-number
                    v-model="price.adjPrice"
                    style="width: 80px"
                    :controls="false"
                    :min="0"
                    :max="
                      parseInt(price.adjPricetag) === 1
                        ? price.price
                        : 99999999999
                    "
                    size="small"
                  ></el-input-number>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createUserName"
          label="调价人"
          min-width="120"
        ></el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template slot-scope="scope">
            <el-button
              :disabled="goods_data.length === 1"
              size="mini"
              type="text"
              @click="delData(scope.$index)"
            >
              删除
            </el-button>
            <el-button size="mini" type="text" @click="addListGoods">
              新增
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <CutomerTypeAdd
      :is-show="customer_type_add_show"
      @cancel="customer_type_add_show = false"
    ></CutomerTypeAdd>
    <CustomerTypeModel
      v-if="customer_type_show"
      :is-show-add="true"
      :is-check="false"
      :is-show="customer_type_show"
      @confirm="customerTypeConfirm"
      @cancel="customer_type_show = false"
    ></CustomerTypeModel>
  </ContainerTit>
</template>

<script>
  import { addPauseSave, getPauseSave, delPauseSave } from "@/api/common";
  import { addCustomerTypePriceAdjustment } from "@/api/Price";

  import CutomerTypeAdd from "@/component/customer/CutomerTypeAdd";
  import CustomerTypeModel from "@/component/customer/CustomerTypeModel";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  const goodsItem = {
    createUserName: "",
    goodsName: "",
    goodsId: "",
    goodsCode: "",
    nowPrice: "",
    shopId: "",
    shopName: "",
    skuId: "",
    salePrice: [
      {
        price: 0,
        skuId: "",
        unitName: "",
        adjPricetag: "2",
      },
    ],
    customerName: "",
    customerType: "",
  };
  export default {
    name: "CostumeTypeAdjustPrice",
    components: {
      CutomerTypeAdd,
      CustomerTypeModel,
      ConditionSelGoods,
    },
    data() {
      return {
        customer_type_add_show: false,
        loading: false,
        material_index: "",
        customer_type_show: false,
        show_goods: false,
        goods_data: [],
        customer_type_name: "",
        customer_type_id: 0,
        shop_id: "",
        pageName: "",
        spec_check: [],
        goods_index: 0,
        adjPricetag: "2",
        price_num: 0,
        show_set: false,
        adjPricetag_list: [
          {
            label: "+",
            value: "2",
          },
          {
            label: "-",
            value: "1",
          },
          {
            label: "*",
            value: "3",
          },
        ],
      };
    },
    created() {
      this.pageName = this.$route.name;
      // this.getPauseSave()
      for (let i = 1; i <= 1; i++) {
        this.goods_data.push(this.$_common.deepClone(goodsItem));
      }
    },
    methods: {
      betchSet() {
        this.goods_data.forEach((item) => {
          if (item.skuId) {
            item.salePrice.forEach((sku) => {
              sku.adjPricetag = this.adjPricetag;
              sku.price = this.price_num;
              sku.ladderPrice = sku.ladderPrice.map((ladder) => {
                return {
                  ...ladder,
                  adjPricetag: this.adjPricetag,
                  adjPrice: this.price_num,
                };
              });
            });
          }
        });
        this.show_set = false;
      },
      addListGoods() {
        this.goods_data.push(this.$_common.deepClone(goodsItem));
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      specSelConfirm(params) {
        let target = this.$_common.deepClone(this.goods_data);
        const goodsD = params.goodsD.map((item) => {
          return {
            createUserName: this.userName,
            goodsName: params.now_goods_data.title,
            goodsId: params.now_goods_data.id,
            goodsCode: params.now_goods_data.code,
            nowPrice: item.spec.salePrice,
            shopId: params.now_goods_data.shopId,
            shopName: params.now_goods_data.shopName,
            skuId: item.skuId,
            specGropName: item.spec.specGropName,
            unitName: item.spec.unitName,
            salePrice: [
              {
                price: 0,
                skuId: item.skuId,
                unitName: item.spec.specGropName || item.spec.unitName,
                adjPricetag: "2",
                ladderPrice: item.ladderPrice.map((ladder) => {
                  return {
                    ...ladder,
                    adjPricetag: "2",
                    adjPrice: 0,
                  };
                }),
              },
            ],
            customerName: this.customer_type_name,
            customerType: this.customer_type_id,
          };
        });
        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);
          }
        });

        this.goods_data = target;
      },
      delData(index) {
        this.goods_data.splice(index, 1);
      },
      // 选择商品确定
      selGoods(row) {
        const goods = row.map((item) => {
          let specGropName = "";
          if (item.specGroup.length) {
            specGropName = item.specGroup
              .map((itemM) => itemM.specValueName)
              .join(";");
          }
          return {
            createUserName: this.userName,
            goodsName: item.title,
            goodsId: item.id,
            goodsCode: item.code,
            nowPrice: item.salePrice,
            ladderPrice: item.ladderPrice,
            enabledLadder: item.enabledLadder,
            shopId: item.shopId,
            shopName: item.shopName,
            skuId: item.skuId,
            specGropName: specGropName,
            unitName: item.unitName,
            salePrice: [
              {
                price: 0,
                skuId: item.skuId,
                unitName: item.unitName,
                adjPricetag: "2",
                ladderPrice: item.ladderPrice.map((ladder) => {
                  return {
                    ...ladder,
                    adjPricetag: "2",
                    adjPrice: 0,
                  };
                }),
              },
            ],
            customerName: this.customer_type_name,
            customerType: this.customer_type_id,
          };
        });
        if (!this.goods_data.length) {
          this.goods_data = goods;
        } else {
          const arr = this.$_common
            .unique(this.goods_data.concat(goods), ["goodsId", "skuId"])
            .filter((item) => item.goodsId);
          arr.push(this.$_common.deepClone(goodsItem));
          this.goods_data = arr;
        }
      },
      customerTypeConfirm(val) {
        const row = val[0];
        this.customer_type_name = row.name;
        this.customer_type_id = row.id;
      },
      // 暂存
      async addPauseSave() {
        const params = this.$_common.deepClone(this.goods_data).map((item) => {
          delete item.skuId;
          return {
            ...item,
          };
        });
        this.loading = true;
        const data = await addPauseSave({
          key: this.pageName,
          data: params,
        });
        this.loading = false;

        this.$message({
          type: "success",
          message: "暂存成功",
        });
        if (this.systemType === 2) {
          this.$closeCurrentGoEdit(
            "/SingleStore/goods/priceAdjustCustomerType"
          );
        } else {
          this.$closeCurrentGoEdit("/goods/sale/CustomerTypeAdjustPrice");
        }
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.goods_data = data;
      },
      // 删除
      async delPauseSave() {
        const { data } = delPauseSave({
          key: this.pageName,
        });
      },
      // 提交保存
      async submitData() {
        if (!this.customer_type_id) {
          this.$message.warning("请选择客户类型");
          return;
        }
        let params = [];
        this.$_common.deepClone(this.goods_data).forEach((item) => {
          if (item.goodsId) {
            const index = params.findIndex(
              (itemP) => itemP.goodsId === item.goodsId
            );

            if (index === -1) {
              params.push({
                createUserName: this.userName,
                goodsName: item.goodsName,
                goodsId: item.goodsId,
                shopId: item.shopId,
                shopName: item.shopName,
                salePrice: item.salePrice,
                customerName: item.customerName,
                customerType: this.customer_type_id,
              });
            } else {
              params[index].salePrice.push(item.salePrice[0]);
            }
          }
        });
        if (!params.length) {
          this.$message.warning("请选择需要调价的商品！");
          return;
        }
        this.loading = true;
        const { data } = await addCustomerTypePriceAdjustment(
          JSON.stringify(params)
        );
        this.loading = false;

        this.$message({
          type: "success",
          message: "添加成功",
        });
        this.delPauseSave();
        if (this.systemType === 2) {
          this.$closeCurrentGoEdit(
            "/SingleStore/goods/priceAdjustCustomerType"
          );
        } else {
          this.$closeCurrentGoEdit("/goods/sale/AdjustPriceGoods");
        }
      },
    },
  };
</script>

<style scoped lang="scss">
  .ladder-li {
    margin-top: 5px;
    .price-span {
      width: 40px;
      text-align: center;
      line-height: 30px;
      display: inline-block;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #ffffff;
    }
  }
</style>
