<!--新建商品调价单-->
<template>
  <ContainerTit>
    <span v-if="isDraw" slot="pagetit">商品调价</span>
    <div slot="headr">
      <el-button v-if="!isDraw" :loding="loading" @click="delPauseSave(1)">
        清除暂存
      </el-button>
      <el-button v-if="!isDraw" :loding="loading" @click="AddTem">
        暂存
      </el-button>
      <el-button type="primary" :loading="loading" @click="checkSub">
        保存
      </el-button>
    </div>

    <div class="detail-tab-main" style="background-color: #fff; padding: 20px">
      <div v-if="!isDraw && systemType === 1">
        <SelectShop
          v-model="shop_id"
          size="small"
          :is-default="true"
          :clearable="false"
          @change="selShop"
          @default="shopDefault"
        />
        <el-button
          size="mini"
          type="text"
          @click="$router.push('/SystemSettings/liansuoguanli/AddShop')"
        >
          【新建商铺】
        </el-button>
      </div>

      <div style="padding-top: 10px">
        <el-table :data="tableData">
          <el-table-column
            prop="skuId"
            label="ID"
            min-width="60"
            align="center"
          ></el-table-column>
          <el-table-column
            v-if="!isDraw"
            prop="goodsName"
            label="商品名称"
            min-width="140"
            align="center"
          >
            <template slot-scope="scope">
              <ConditionSelGoods
                v-if="!!shop_id"
                v-model="scope.row.goodsName"
                :shop-id="shop_id"
                :spec-check="spec_check"
                @goodsVisibleChange="goodsVisibleChange($event, scope.$index)"
                @specSelConfirm="specSelConfirm"
                @selectSelGoods="selectSelGoods"
                @selGoods="selGoods"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="unitName"
            label="单位"
            align="center"
            min-width="60"
          ></el-table-column>
          <el-table-column
            prop="specGropName"
            label="属性"
            align="center"
            min-width="120"
          ></el-table-column>
          <el-table-column
            v-if="!isDraw"
            prop="nowPrice"
            label="当前价格"
            align="center"
            min-width="80"
          ></el-table-column>
          <el-table-column
            v-if="systemType !== 3"
            prop="enabledLadder"
            align="center"
            label="启用阶梯价"
            min-width="80"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="!!scope.row.goodsId"
                v-model="scope.row.enabledLadder"
                :inactive-value="0"
                :active-value="1"
                active-color="#36B365"
                inactive-color="#ff4949"
                @change="enabledLadderChange(scope.$index)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="salePriceAreaType"
            label="调整价格"
            align="center"
            min-width="240"
          >
            <template slot-scope="scope">
              <div v-if="!scope.row.goodsId">未发布</div>
              <div v-else>
                <el-input-number
                  v-if="parseInt(scope.row.enabledLadder) === 0"
                  v-model="scope.row.salePrice"
                  size="mini"
                  :min="0.01"
                ></el-input-number>
                <el-button slot="append" style="margin-left: 10px" size="mini">
                  元
                </el-button>
                <ul v-if="parseInt(scope.row.enabledLadder) === 1">
                  <li
                    v-for="(item, index) in scope.row.ladderPrice"
                    :key="index"
                    style="padding-bottom: 5px; text-align: left"
                  >
                    <el-input-number
                      :controls="false"
                      size="mini"
                      disabled
                      :value="item.from"
                      style="width: 60px"
                      :min="0"
                    ></el-input-number>
                    --
                    <el-input-number
                      v-if="!(index === scope.row.ladderPrice.length - 1)"
                      v-model="item.to"
                      :controls="false"
                      size="mini"
                      :min="item.from + 1"
                      style="width: 60px"
                      @blur="ladderPriceBlur(item.to, index, scope.$index)"
                    ></el-input-number>
                    <el-input-number
                      v-else
                      size="mini"
                      disabled
                      value="∞"
                      style="width: 60px"
                      :min="1"
                    ></el-input-number>
                    {{ scope.row.unitName }}
                    ¥
                    <el-input-number
                      v-model="item.price"
                      :controls="false"
                      size="mini"
                      style="width: 80px"
                      :min="0"
                    ></el-input-number>
                    <el-button
                      v-if="!(index === scope.row.ladderPrice.length - 1)"
                      :disabled="scope.row.ladderPrice.length === 2"
                      style="color: #f56c6c"
                      size="mini"
                      icon="el-icon-remove"
                      type="text"
                      @click="delLadderPrice(index, scope.$index)"
                    ></el-button>
                  </li>
                  <el-button
                    :disabled="scope.row.ladderPrice.length === 3"
                    size="mini"
                    icon="el-icon-circle-plus"
                    type="text"
                    @click="addLadderPrice(scope.$index)"
                  >
                    新增
                  </el-button>
                </ul>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!isDraw"
            label="管理"
            align="center"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                :disabled="tableData.length === 1"
                @click="delData(scope.$index)"
              >
                删除
              </el-button>
              <el-button type="text" size="mini" @click="addListGoods">
                新增
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div
          v-if="!!shop_id"
          style="text-align: center; padding-top: 10px"
          class="clearfix"
        >
          <el-button
            type="text"
            icon="el-icon-circle-plus"
            @click="addListGoods"
          >
            新增一条
          </el-button>
        </div>
      </div>
    </div>
    <!--    选择商铺-->
    <!--    <GoodsChooseShop-->
    <!--      v-if="show_shop"-->
    <!--      :dialog-visible="show_shop"-->
    <!--      :is-default="true"-->
    <!--      :is-show-add="true"-->
    <!--      @close="show_shop = false"-->
    <!--      @confirm="selShop"-->
    <!--    ></GoodsChooseShop>-->
  </ContainerTit>
</template>

<script>
  import GoodsChooseShop from "@/component/goods/GoodsChooseShop.vue";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import { getGoodsInfo } from "@/api/goods";
  import { addPauseSave, getPauseSave, delPauseSave } from "@/api/common";
  import { addAndEffective, PriceAdjustmentAdd } from "@/api/Price";
  import { mapGetters } from "vuex";
  import { getSupplierOfferPrice } from "@/api/Supplier";
  import { getRelMap } from "@/api/goods";
  const ladderPriceData = [
    {
      from: 1,
      price: 0.01,
      to: 2,
    },
    {
      from: 3,
      price: 0.01,
      to: 4,
    },
    {
      from: 5,
      price: 0.01,
      to: 999999999,
    },
  ];
  const goodsItem = {
    createUserName: "",
    goodsName: "",
    goodsId: "",
    saleType: "1",
    salePriceType: "1",
    salePriceAreaType: 1,
    salePrice: "",
    nowPrice: "",
    unitName: "",
    skuId: "",
    shopId: "",
    shopName: "",
    ladderPrice: ladderPriceData,
    enabledLadder: 0,
  };
  export default {
    name: "AddGoodsAdjustPrice",
    components: {
      ConditionSelGoods,
      SelectShop,
    },
    props: {
      goodId: {
        type: [Number, String],
        default: 0,
      },
    },
    data() {
      return {
        show_goods: false,
        loading: false,
        shop_name: "",
        isDraw: false,
        show_shop: false,
        m_index: "",
        tableData: [],
        materialName: "",
        materialData: {},
        shop_id: "",
        user_power: {},
        pageName: "",
        goods_index: 0,
        goods_options: [],
        select_loading: false,
        spec_check: [],
        goodsItem: {},
        modify_list: [],
        price_id: 0,
      };
    },
    computed: {
      ...mapGetters({
        storeData: "MUser/storeData",
      }),
    },
    created() {
      this.pageName = this.$route.name;
      // 商品列表进行商品调价
      this.isDraw = this.goodId > 0;
      if (this.isDraw) {
        this.getGoodsDetail();
      } else {
        // 报价单
        if (this.$route.query.price_id) {
          this.price_id = this.$route.query.price_id;
          // this.getSupplierOfferPrice();
          return;
        }
        for (let i = 1; i <= 1; i++) {
          this.tableData.push(this.$_common.deepClone(goodsItem));
        }
        this.getPauseSave();
      }
    },
    mounted() {
      if ([2, 3].includes(this.systemType)) {
        this.shop_id = this.storeData.id;
        this.shop_name = this.storeData.name;
      }
    },
    methods: {
      priceChange(index) {
        let target = this.$_common.deepClone(this.tableData);
        let salePrice = target[index].salePrice;
        if (salePrice < 0) {
          target[index].salePrice = 0;
        }
        this.tableData = target;
      },
      shopDefault(val, obj) {
        this.shop_id = val;
        this.shop_name = obj.name;
        if (this.$route.query.price_id) {
          this.getSupplierOfferPrice();
        }
      },
      async getRelMap(materielId) {
        const { data } = await getRelMap({
          shopId: this.shop_id,
          materielIds: materielId,
        });
        this.tableData = this.tableData.map((item) => {
          return {
            ...item,
            goodsId: data[item.id] || 0,
          };
        });
      },
      async getSupplierOfferPrice() {
        const data = await getSupplierOfferPrice(this.price_id);
        let details_list = [];
        data.data.details.forEach((item) => {
          for (let i in item.offerPrice) {
            details_list.push({
              goodsName: item.materielName,
              code: item.materielCode,
              id: item.materielId,
              skuId: i,
              ...item.offerPrice[i],
            });
          }
        });
        let goods_list = details_list.map((itemP) => {
          const specGropName = itemP.specGroup.map((itemP) => {
            return itemP.specGropName;
          });
          return {
            id: itemP.id,
            goodsName: itemP.goodsName,
            unitName: itemP.unitName,
            specGropName: specGropName,
            skuId: itemP.skuId,
            nowPrice: itemP.costPrice,
            enabledLadder: 0,
            createUserName: this.userName,
            goodsId: 0,
            saleType: "1",
            salePriceType: "1",
            salePriceAreaType: 1,
            salePrice: itemP.costPrice,
            shopId: this.shop_id,
            shopName: this.shop_name,
            ladderPrice: [],
          };
        });

        this.tableData = goods_list;
        const materielId = details_list.map((itemG) => {
          return itemG.id;
        });
        await this.getRelMap(this.$_common.unique(materielId));
      },
      async getGoodsDetail() {
        const { data } = await getGoodsInfo(this.goodId);
        this.shop_name = data.title;
        this.goodsItem = data;
        // 多商户只展示主单位
        let specMultiple = [];
        if (this.systemType === 3) {
          specMultiple = data.specMultiple.filter(
            (item) => item.isMaster === 5
          );
        } else {
          specMultiple = data.specMultiple;
        }
        console.log(specMultiple);
        if (data.specType === 2) {
          this.tableData = specMultiple.map((item) => {
            const specValueName = item.specGroup
              .map((itemS) => {
                return itemS.specValueName;
              })
              .join("_");
            return {
              ...item,
              goodsId: data.id,
              skuId: item.id,
              specGropName: specValueName,
            };
          });
        } else if (data.specType === 1) {
          this.tableData = specMultiple.map((item) => {
            return {
              ...item,
              goodsId: data.id,
              skuId: item.id,
              specGropName: "无",
            };
          });
        }
      },
      addListGoods() {
        this.tableData.push(this.$_common.deepClone(goodsItem));
      },
      selectSelGoods(id) {
        this.spec_check = this.tableData
          .filter((item) => item.goodsId === id)
          .map((item) => {
            return item.skuId;
          });
      },
      specSelConfirm(params) {
        let target = this.$_common.deepClone(this.tableData);
        const goodsD = params.goodsD.map((item) => {
          return {
            // spec_check_list: params.spec_check_list,
            createUserName: this.userName,
            goodsName: params.now_goods_data.title,
            goodsId: params.now_goods_data.id,
            saleType: "1",
            salePriceType: "1",
            salePriceAreaType: 1,
            salePrice: item.spec.salePrice,
            nowPrice: item.spec.salePrice,
            unitName: item.spec.unitName,
            specGropName: item.spec.specGropName,
            skuId: item.skuId,
            shopId: params.now_goods_data.shopId,
            shopName: params.now_goods_data.shopName,
            ladderPrice: item.spec.ladderPrice,
            enabledLadder: item.spec.enabledLadder,
          };
        });
        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.tableData = target;
      },
      selGoods(list) {
        const goodsD = list.map((item) => {
          let specGropName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            createUserName: this.userName,
            goodsName: item.title,
            goodsId: item.id,
            saleType: "1",
            salePriceType: "1",
            salePriceAreaType: 1,
            salePrice: item.salePrice,
            nowPrice: item.salePrice,
            unitName: item.unitName,
            specGropName: specGropName,
            skuId: item.skuId,
            shopId: item.shopId,
            shopName: item.shopName,
            ladderPrice: item.ladderPrice,
            enabledLadder: item.enabledLadder,
          };
        });

        if (!this.tableData.length) {
          this.tableData = goodsD;
        } else {
          const arr = this.$_common
            .unique(this.tableData.concat(goodsD), ["goodsId", "skuId"])
            .filter((item) => item.goodsId);
          arr.push(this.$_common.deepClone(goodsItem));
          this.tableData = arr;
        }

        // this.tableData = target;
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      enabledLadderChange(index) {
        const target = this.$_common.deepClone(this.tableData);
        if (
          target[index].enabledLadder &&
          target[index].ladderPrice.length === 0
        ) {
          target[index].ladderPrice = this.$_common.deepClone(ladderPriceData);
        }
        this.tableData = target;
      },
      // 双击选择店铺
      selShop(row) {
        this.shop_name = row[0].name;
        this.shop_id = row[0].id;
      },
      ladderPriceBlur(val, index, rindex) {
        const target = this.$_common.deepClone(this.tableData);
        target[rindex].ladderPrice[index + 1].from = val + 1;
        if (index === 0) {
          target[rindex].ladderPrice[index + 1].to = val + 2;
          if (target[rindex].ladderPrice[index + 2]) {
            target[rindex].ladderPrice[index + 2].from = val + 3;
          }
        }
        this.tableData = target;
      },
      // 删除阶梯价
      delLadderPrice(index, rIndex) {
        const target = this.$_common.deepClone(this.tableData);
        target[rIndex].ladderPrice.splice(index, 1);
        target[rIndex].ladderPrice[0].from = 1;
        target[rIndex].ladderPrice[target[rIndex].ladderPrice.length - 1].from =
          target[rIndex].ladderPrice[0].to + 1;
        this.tableData = target;
      },
      // 新增一条阶梯价
      addLadderPrice(rIndex) {
        const target = this.$_common.deepClone(this.tableData);
        if (!target[rIndex].ladderPrice.length) {
          target[rIndex].ladderPrice.push({
            from: 1,
            price: "",
            to: 2,
          });
        } else {
          const upL = target[rIndex].ladderPrice[0];
          target[rIndex].ladderPrice.splice(1, "", {
            from: upL.to + 1,
            price: "",
            to: upL.to + 2,
          });
          if (target[rIndex].ladderPrice.length === 3) {
            target[rIndex].ladderPrice[
              target[rIndex].ladderPrice.length - 1
            ].from = upL.to + 3;
          }
        }
        this.tableData = target;
      },
      // 删除
      delData(index) {
        this.tableData.splice(index, 1);
      },
      // 选择大区确定
      regionConfirm(price) {},
      // 调整全国销售价
      standardConfirm(price) {
        const target = this.$_common.deepClone(this.tableData);
        target[this.m_index].salePrice[target[this.m_index].skuId] = {
          ...price,
          unitName: target[this.m_index].unitName,
        };
        this.tableData = target;
      },
      // 新增暂存
      async AddTem() {
        this.loading = true;
        const { data } = await addPauseSave({
          key: this.pageName,
          data: {
            shopId: this.shop_id,
            shopName: this.shop_name,
            params: this.tableData,
          },
        });
        this.loading = false;

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

        if (JSON.stringify(data) === "{}") return;
        this.tableData = data.params || [];
        this.shop_name = data.shopName || "";
        this.shop_id = data.shopId || "";
      },
      // 检查提交
      checkSub() {
        if (!this.isDraw && !this.shop_id) {
          this.$message.warning("请选择商铺");
          return;
        }
        if (!this.tableData[0].goodsId) {
          this.$message.warning("第一项商品不能为空");
          return;
        }
        const price = this.tableData
          .filter((item) => item.goodsId)
          .map((item) => {
            return {
              ...item,
              ladderPrice: item.enabledLadder === 0 ? [] : item.ladderPrice,
              salePrice: item.enabledLadder === 1 ? 0 : item.salePrice,
              shopName: this.shop_name,
            };
          });
        let ladderPriceLength = true;
        let isLadderPrice = true;
        for (let i in price) {
          const item = price[i];
          if (item.enabledLadder === 1) {
            if (item.ladderPrice.length < 2) {
              ladderPriceLength = false;
              break;
            } else if (!item.ladderPrice.every((itemP) => itemP.price > 0)) {
              isLadderPrice = false;
              break;
            }
          } else {
            if (!item.salePrice) {
              isLadderPrice = false;
              break;
            }
          }
        }
        if (!ladderPriceLength) {
          this.$message.warning("请至少设置两条阶梯价");
          return;
        }
        if (!isLadderPrice) {
          this.$message.warning("请输入价格");
          return;
        }
        this.submitData();
      },

      // 保存
      async submitData() {
        let params = [];
        // 商品列表调价
        if (this.isDraw) {
          // 价格管理调价
          let salePrice = {};
          let min = 0;
          if (this.goodsItem.enabledLadder === 1) {
            const arr = this.goodsItem.ladderPrice.map((itemM) => {
              return itemM.price;
            });
            min = Math.min.apply(null, arr);
          }
          for (let i in this.tableData) {
            const itemS = this.tableData[i];
            if (itemS.ladderPrice.length) {
              itemS.ladderPrice[itemS.ladderPrice.length - 1].to = 9999999999;
            }
            salePrice[itemS.id] = {
              marketPrice: itemS.salePrice,
              salePrice: itemS.enabledLadder === 0 ? itemS.salePrice : min,
              unitName: itemS.unitName,
              ladderPrice: itemS.enabledLadder === 0 ? [] : itemS.ladderPrice,
              enabledLadder: itemS.enabledLadder,
            };
          }
          params = [
            {
              createUserName: this.userName,
              goodsName: this.goodsItem.title,
              goodsId: this.goodsItem.id,
              saleType: 1, // 1，实物销售，2，虚物销售
              salePriceType: 1, // 1 销售价 2，秒杀价
              salePriceAreaType: 1, // 销售价格为区域价还是全国价
              salePrice: salePrice,
              shopId: this.goodsItem.shopId,
              shopName: this.shop_name,
            },
          ];
        } else {
          // 新增调价单
          const tableData = this.tableData.filter((item) => item.goodsId);
          params = tableData.map((item) => {
            if (item.ladderPrice.length) {
              item.ladderPrice[item.ladderPrice.length - 1].to = 9999999999;
            }
            // 获取最小的价格
            let min = 0;
            if (item.enabledLadder === 1) {
              const arr = item.ladderPrice.map((itemM) => {
                return itemM.price;
              });
              min = Math.min.apply(null, arr);
            }
            return {
              createUserName: item.createUserName || this.userName,
              goodsName: item.goodsName,
              goodsId: item.goodsId,
              saleType: item.saleType, // 1，实物销售，2，虚物销售
              salePriceType: item.salePriceType, // 1 销售价 2，秒杀价
              salePriceAreaType: item.salePriceAreaType,
              salePrice: {
                [item.skuId]: {
                  salePrice: item.enabledLadder === 0 ? item.salePrice : min,
                  unitName: item.specGropName,
                  ladderPrice: item.enabledLadder === 0 ? [] : item.ladderPrice,
                  marketPrice: item.nowPrice,
                  enabledLadder: item.enabledLadder,
                },
              },
              shopId: item.shopId,
              shopName: this.shop_name,
            };
          });
        }

        let target = {};
        this.loading = true;
        if (this.isDraw) {
          // 自动创建调价单且自动生效接口
          target = await addAndEffective(JSON.stringify(params));
        } else {
          target = await PriceAdjustmentAdd(JSON.stringify(params));
        }
        const data = target;
        this.loading = false;

        this.$message({
          type: "success",
          message: "操作成功",
        });
        await this.delPauseSave();
        if (!this.isDraw) {
          if (this.systemType === 2) {
            this.$closeCurrentGoEdit("/SingleStore/goods/priceAdjust");
          } else {
            this.$closeCurrentGoEdit("/goods/sale/AdjustPrice");
          }
        } else {
          this.$emit("handelSuccess");
        }
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/goods/sale/AddGoodsAdjustPrice");
        }
      },
    },
  };
</script>

<style scoped lang="scss">
  .creat-shop {
    color: #1890ff;
    font-size: 12px;
    margin: 5px 0 0 5px;
  }
</style>
