<template>
  <div
    class="npriceMcount"
    :style="styleData.npriceMcountStyle"
    ref="npriceMcount"
    @click="styleClick('click', 'npriceMcount')"
    @mousemove="styleClick('mousemove', 'npriceMcount')"
    @mouseout="styleClick('mouseout')"
  >
    <div class="tab-box" :style="styleData.prizeBoxWrap">
      <div
        :class="currentIndex == index ? 'tab tab-active' : 'tab'"
        v-for="(item, index) in promotionList"
        :style="styleData.tab"
        :key="index"
        @click="changeTab(index)"
      >
        {{ item.quota }}选{{ item.rate }}
      </div>
    </div>
    <div
      class="card"
      :style="{
        'background-image': 'url(' + promotionList[currentIndex].tabImg + ')'
      }"
    >
      <div class="card-quota">{{ promotionList[currentIndex].quota }}元</div>
      <div class="card-rate">{{ promotionList[currentIndex].rate }}</div>
      <div class="card-time">
        活动时间：{{ startTime | filterDate("M月DD日") }}-{{
          endTime | filterDate("M月DD日")
        }}
      </div>
      <div class="card-desc">
        活动说明：参与任选的规格请以最终成交为准，每款商品下文案的说明供您参考。
      </div>
    </div>
    <div class="prize-box">
      <div
        class="prize-item"
        v-for="(item, index) in promotionList[currentIndex].skuInfoList"
        :style="styleData.prizeBox"
        :key="index"
      >
        <img class="prize-img" :src="item.skuImg" alt="" />
        <div class="prize-name text-hide2">{{ item.name }}</div>
        <div class="prize-label">
          {{ promotionList[currentIndex].quota }}选{{
            promotionList[currentIndex].rate
          }}
        </div>
        <div class="prize-quota">￥{{ item.skuPrice }}</div>
        <img
          :class="['shop-car', 'shop-car' + index]"
          :ref="'shopcar' + index"
          @click="addCar(item, index)"
          src="//img10.360buyimg.com/imgzone/jfs/t1/204099/36/40418/913/660d344aFc4b3060a/978ac815d95702ef.png"
          alt=""
        />
      </div>
    </div>
    <div class="bottom-bar">
      <div class="total-shop-car" @click="openPop" ref="destination">
        <div v-if="carGoodsList.length > 0" class="add-num">
          {{ carGoodsTotalNum }}
        </div>
      </div>
      <div style="flex:1;text-align: left;">
        <div class="sum">合计：￥{{ sumPrice }}</div>
        <div class="discount">已优惠：￥{{ discountPrice }}</div>
      </div>
      <div class="buy" @click="gotoBuy">购买</div>
    </div>
  </div>
</template>

<script>
import store from "../../../store/store";
import apis1 from "../../../util/apis1.js";
import dateUtil from "../../../util/dateUtil";
import { NpriceMcountPopComService } from "../../../util/comCreate.js";
let { totalPricePromo, totalPricePromoAddCart } = apis1;
export default {
  props: [
    "datas",
    "keyData",
    "styleData",
    "isTemplate",
    "templateData",
    "modifyContent",
    "isWebClick"
  ],
  data() {
    return {
      styleDataOld: {},
      preventClick: false,
      promotionList: [],
      status: 0,
      isDisable: false,
      timer: Date.now(),
      actStatus: "",
      currentIndex: 0,
      startTime: "",
      endTime: "",
      carGoodsList: [], //加购的商品
      sumPrice: 0,
      discountPrice: 0,
      showGoodsList: false,
      carGoodsTotalNum: 0,
      showImg: false
    };
  },
  activated() {},
  created() {
    //深拷贝重置需要
    this.styleDataOld = JSON.parse(JSON.stringify(this.styleData));
    this.initData();
    this.publicData.$on("activityLoaded", (initDataAll, datas) => {
      this.startTime = initDataAll.startTime;
      this.endTime = initDataAll.endTime;
    });
  },
  computed: {},
  methods: {
    //点击可修改位置的方法
    styleClick(type, refName) {
      if (this.isWebClick) {
        //传值给B端
        let byValue = {
          modifyContent: this.modifyContent,
          refName: refName,
          styleData: this.styleData,
          styleDataOld: this.styleDataOld,
          c_this: this
        };
        this.$emit("opertaionCom", type, byValue);
      }
    },
    initData() {
      console.log(this.isTemplate, "0000", this.datas);
      setTimeout(() => {
        this.actStatus = sessionStorage.getItem("actStatus");
        console.log("this.actStatus---", this.actStatus);
      }, 500);
      this.userImg = store.state.userImg
        ? store.state.userImg
        : "//img10.360buyimg.com/imgzone/jfs/t1/5442/3/21406/1209/64450fbfF64c7f59f/e504fd84140a67e5.png";
      if (this.isTemplate) {
        var datasAll = this.templateData;
        console.log(datasAll, "datasAll", this.isWebClick);
        if (datasAll) {
          console.log("datasAll1");
        } else {
          console.log("datasAll2", this.isWebClick);
          // if (this.isWebClick) {
          console.log("this.prizeList2----");
          this.promotionList = [
            {
              quota: 100,
              rate: 1,
              skuInfoList: [
                {
                  skuId: 10097218673690,
                  name:
                    "广博(GuangBo) 电动转笔刀 自动削笔器 卷笔刀削笔刀铅笔刀削笔器 太空人削笔器-粉-XB35881",
                  skuImg:
                    "http://img10.360buyimg.com/n0/jfs/t1/208391/9/40050/101045/65e15026Fd66a93d8/8814f36f8c3da3cc.jpg",
                  skuPrice: "49.00",
                  id: 165349612,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "49.00",
                  position: 0,
                  taskType: 0
                },
                {
                  skuId: 10076684797721,
                  name:
                    "广博（GuangBo） 测试商品勿拍不发货语音型计算器 计算机 快速计算 大型语音款 #21",
                  skuImg:
                    "http://img11.360buyimg.com/n0/jfs/t1/167364/5/7520/164168/60347e8dEafe6693f/96088ea421980c60.jpg",
                  skuPrice: "69.00",
                  id: 100431708,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "69.00",
                  position: 1,
                  taskType: 0
                },
                {
                  skuId: 10076684797724,
                  name:
                    "广博（GuangBo） 测试商品勿拍不发货语音型计算器 计算机 快速计算 小型语音款 #29",
                  skuImg:
                    "http://img14.360buyimg.com/n0/jfs/t1/167364/5/7520/164168/60347e8dEafe6693f/96088ea421980c60.jpg",
                  skuPrice: "69.00",
                  id: 100431707,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "69.00",
                  position: 2,
                  taskType: 0
                },
                {
                  skuId: 10076684797722,
                  name:
                    "广博（GuangBo） 测试商品勿拍不发货语音型计算器 计算机 快速计算 大型语音款 #29",
                  skuImg:
                    "http://img12.360buyimg.com/n1/jfs/t1/167364/5/7520/164168/60347e8dEafe6693f/96088ea421980c60.jpg",
                  skuPrice: "69.00",
                  id: 100431653,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "69.00",
                  position: 3,
                  taskType: 0
                },
                {
                  skuId: 10076684797723,
                  name:
                    "广博（GuangBo） 测试商品勿拍不发货语音型计算器 计算机 快速计算 小型语音款 #21",
                  skuImg:
                    "http://img13.360buyimg.com/n0/jfs/t1/167364/5/7520/164168/60347e8dEafe6693f/96088ea421980c60.jpg",
                  skuPrice: "69.00",
                  id: 100431541,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "69.00",
                  position: 4,
                  taskType: 0
                }
              ],
              tabImg:
                "//img10.360buyimg.com/imgzone/jfs/t1/218815/33/37098/9520/660621aaF970dafb5/1ad73fb39d58a4ac.png"
            },
            {
              quota: 100,
              rate: 2,
              skuInfoList: [
                {
                  skuId: 10097234362611,
                  name:
                    "广博旋转阅读架铝合金读书多功能可调节升降电脑支架书架小学生桌面书夹固定器放书本课本书立架 【全铝合金】星光银-A40002- -S",
                  skuImg:
                    "http://img11.360buyimg.com/n0/jfs/t1/164726/11/42468/62996/65e18030F1d1b486b/c1f27feb2b1e6d9e.png",
                  skuPrice: "109.00",
                  id: 165349632,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "109.00",
                  position: 0,
                  taskType: 1
                },
                {
                  skuId: 10097246839573,
                  name:
                    "广博联名酷企鹅A6手帐本礼盒套装手账本送礼笔记本子礼盒文具生日礼物 A6手帐套装-酷企鹅",
                  skuImg:
                    "http://img13.360buyimg.com/n0/jfs/t1/234504/18/13946/52081/65e199cdF58b837c0/45b10688b0976b07.png",
                  skuPrice: "239.00",
                  id: 165349637,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "239.00",
                  position: 1,
                  taskType: 1
                },
                {
                  skuId: 10097230940641,
                  name:
                    "广博木质阅读架书立架收纳读书看书支架桌面固定书本课桌学生绘本神器书挡放书折叠可伸缩支架 木质款【胡桃色】-A40001-K",
                  skuImg:
                    "http://img11.360buyimg.com/n0/jfs/t1/246623/8/5164/59250/65e1787aFde012024/58f140eb1be60779.png",
                  skuPrice: "129.00",
                  id: 165349611,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "129.00",
                  position: 2,
                  taskType: 1
                },
                {
                  skuId: 10097230940642,
                  name:
                    "广博木质阅读架书立架收纳读书看书支架桌面固定书本课桌学生绘本神器书挡放书折叠可伸缩支架 木质款【橡木色】-A40001-Z",
                  skuImg:
                    "http://img12.360buyimg.com/n1/jfs/t1/246623/8/5164/59250/65e1787aFde012024/58f140eb1be60779.png",
                  skuPrice: "129.00",
                  id: 165349610,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "129.00",
                  position: 3,
                  taskType: 1
                },
                {
                  skuId: 10097227980646,
                  name:
                    "广博60色软头丙烯马克笔防水手绘DIY儿童细不透色丙烯颜料笔美术学生水彩笔炳漆彩笔涂鸦炳稀画笔 【专业绘画】60色升级大容量软头-H02295-1",
                  skuImg:
                    "http://img11.360buyimg.com/n0/jfs/t1/245409/11/4938/104593/65e16dc1F41b3374e/59140b8544506797.png",
                  skuPrice: "159.00",
                  id: 165349614,
                  addCartUser: 0,
                  disCountInfo: "0",
                  fullReduction: "0",
                  skuMaxNum: "0",
                  promotionalPrice: "159.00",
                  position: 4,
                  taskType: 1
                }
              ],
              tabImg:
                "//img10.360buyimg.com/imgzone/jfs/t1/218815/33/37098/9520/660621aaF970dafb5/1ad73fb39d58a4ac.png"
            }
          ];
          // }
        }
      } else {
        this.getList();
      }
    },
    getList() {
      totalPricePromo(initdatas => {
        console.log("===", initdatas);
        if (initdatas.data) {
          this.promotionList = initdatas.data;
          this.timer = Date.now();
        }
      });
    },

    gotoBuy() {
      if (this.isTemplate == true) {
        this.$toast("活动预览，仅供查看");
        return;
      }
      if (this.carGoodsList.length == 0) {
        this.$toast("还未添加商品");
        return;
      }
      let params = this.carGoodsList.map(item => {
        return {
          tab: item.taskType,
          quota: item.quota,
          rate: item.rate,
          skuId: item.skuId,
          num: item.num,
          jdPrice: item.skuPrice,
          skuName: item.skuName,
          skuImg: item.skuImg
        };
      });
      console.log(222, params);
      totalPricePromoAddCart(params, res => {
        var param = {
          category: "jump",
          des: "cart"
        };
        param = JSON.stringify(param);
        var linkUrl = "openapp.jdmobile://virtual?params=" + param;
        window.location.href = linkUrl;
      });
    },
    changeTab(index) {
      this.currentIndex = index;
    },
    openPop() {
      if (this.carGoodsList.length > 0) {
        NpriceMcountPopComService.create(this.carGoodsList, submit => {
          console.log("关闭弹窗，更新购物车", this.carGoodsList);
          if (submit == 2) {
            this.carGoodsList = [];
          }
          this.calcPrice();
          if (submit != 1) {
            NpriceMcountPopComService.close();
          }
        });
      }
    },
    addCar(item, index) {
      let quota = Number(this.promotionList[this.currentIndex].quota);
      let rate = Number(this.promotionList[this.currentIndex].rate);
      if (this.carGoodsList.filter(e => e.skuId == item.skuId).length > 0) {
        //如果已经存在商品，就增加数量
        this.carGoodsList.forEach((e, i) => {
          if (e.skuId == item.skuId) {
            this.carGoodsList[i].num += 1;
          }
        });
      } else {
        this.carGoodsList.push({
          ...item,
          quota,
          rate,
          num: 1,
          skuPrice: Number(item.skuPrice)
        });
      }
      // this.carGoodsList.forEach(i => {
      //   this.sumPrice += Number(i.skuPrice);
      // });
      console.log(111, this.carGoodsList);
      this.calcPrice();
      // this.$toast("添加成功");
      // 获取目标位置的坐标
      const destinationRect = this.$refs.destination.getBoundingClientRect();
      const destinationX = destinationRect.left;
      const destinationY = destinationRect.top;
      // 获取图片元素
      let shopcarRef = `shopcar${index}`;
      const shopcarRect = this.$refs[shopcarRef][0].getBoundingClientRect();
      const shopcarX = shopcarRect.left;
      const shopcarY = shopcarRect.top;
      // const image = document.querySelector(`.move-car${index}`);
      let imgElement = document.createElement("img");
      imgElement.src =
        "//img10.360buyimg.com/imgzone/jfs/t1/204099/36/40418/913/660d344aFc4b3060a/978ac815d95702ef.png";
      imgElement.style.zIndex = 999;
      imgElement.style.width = "0.31rem";
      imgElement.style.height = "0.31rem";
      imgElement.style.position = "absolute";
      imgElement.style.transition = "all 2s ease";
      imgElement.style.top = shopcarY + "px";
      imgElement.style.left = shopcarX + "px";
      document.getElementById("index").appendChild(imgElement);

      // 在动画结束后隐藏图片
      setTimeout(() => {
        // 设置动画
        imgElement.style.transform = `translate(${destinationX -
          shopcarX +
          20}px, ${destinationY - shopcarY}px)`;
        imgElement.style.opacity = 0;
      }, 100);
      setTimeout(() => {
        // 销毁
        document.getElementById("index").removeChild(imgElement);
      }, 2100);
    },
    calcPrice() {
      this.sumPrice = 0;
      this.carGoodsTotalNum = 0;
      this.carGoodsList.forEach(e => {
        this.carGoodsTotalNum += e.num;
      });
      const groupedData = this.carGoodsList.reduce((acc, currentValue) => {
        const { taskType, skuPrice, quota, rate, num } = currentValue;
        // 如果已经存在该 taskType 的数组，则将当前对象添加到对应的数组中
        if (acc[taskType]) {
          acc[taskType].push(currentValue);
          acc[taskType].totalPrice += skuPrice * num;
        } else {
          // 否则，创建一个新的数组，并将当前对象添加到新数组中
          acc[taskType] = [currentValue];
          acc[taskType].totalPrice = skuPrice * num;
          acc[taskType].quota = quota;
          acc[taskType].rate = rate;
        }
        return acc;
      }, {});
      console.log(333, groupedData);
      // 循环结束后判断每一组的总价是否大于 quota
      this.discountPrice = 0;
      for (const taskType in groupedData) {
        if (groupedData.hasOwnProperty(taskType)) {
          const group = groupedData[taskType];
          // 判断总价是否大于 quota
          if (group.totalPrice > group.quota) {
            console.log(233);
            group.sort((a, b) => b.skuPrice - a.skuPrice);
            let totalPirceLimitByRate = 0;
            let remainRate = group.rate;
            group.forEach((e, index) => {
              if (remainRate > 0) {
                if (e.num <= remainRate) {
                  totalPirceLimitByRate += e.num * e.skuPrice;
                  remainRate -= e.num;
                } else {
                  totalPirceLimitByRate += remainRate * e.skuPrice;
                  remainRate = 0;
                }
              }
            });
            let discountAmount = 0;
            if (remainRate == 0) {
              discountAmount = totalPirceLimitByRate - group.quota;
            }
            if (discountAmount < 0) {
              discountAmount = 0;
            }
            this.discountPrice += discountAmount;
            this.sumPrice += group.totalPrice - discountAmount;
          } else {
            this.sumPrice += group.totalPrice;
          }
        }
      }
      this.sumPrice = this.sumPrice.toFixed(2);
      this.discountPrice = this.discountPrice.toFixed(2);
    }
  }
};
</script>

<style lang="scss" scoped="scoped">
.tab-box {
  width: 100%;
  overflow-x: scroll;
  overflow-y: hidden;
  display: flex;
  margin-bottom: 0.3rem;
}
.tab {
  min-width: 1.53rem;
  height: 0.47rem;
  border-radius: 0.24rem;
  border: solid 1px #d2d2d2;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 0.16rem;
  margin-right: 0.27rem;
  font-size: 0.26rem;
  color: #2d2d2d;
  word-break: keep-all;
}
.tab-active {
  background: #fe792e;
  color: #fff;
  border: none;
}
.card {
  width: 6.89rem;
  height: 2.08rem;
  background-repeat: no-repeat;
  background-size: 100%;
  position: relative;
  margin-bottom: 0.2rem;
  .card-quota {
    position: absolute;
    top: 0.27rem;
    left: 0.18rem;
    width: 1.35rem;
    height: 0.34rem;
    color: #fff;
    font-size: 0.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .card-rate {
    position: absolute;
    bottom: 0.18rem;
    left: 1.3rem;
    width: 1.47rem;
    color: #ffe700;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .card-time {
    position: absolute;
    top: 0.4rem;
    left: 3.52rem;
    color: #000;
    font-size: 0.24rem;
    text-align: left;
  }
  .card-desc {
    position: absolute;
    top: 0.83rem;
    right: 0.16rem;
    width: 3.2rem;
    color: #000;
    font-size: 0.2rem;
    text-align: left;
  }
}
.prize-box {
  display: flex;
  flex-wrap: wrap;
  .prize-item {
    width: 2.19rem;
    border-radius: 0.1rem;
    border: solid 1px #d2d2d2;
    position: relative;
    margin-right: 0.19rem;
    padding: 0.07rem 0.07rem 0.17rem;
    text-align: left;
    margin-bottom: 0.2rem;
    .prize-img {
      width: 2.04rem;
      height: 2.04rem;
      background-color: #ffffff;
      border-radius: 0.05rem;
      display: block;
    }
    .prize-name {
      font-size: 0.2rem;
      color: #2d2d2d;
    }
    .prize-label {
      margin-top: 0.1rem;
      width: fit-content;
      padding: 0.04rem 0.14rem;
      border-radius: 0.18rem;
      border: solid 1px #ff772d;
      font-size: 0.17rem;
      color: #ff772d;
      margin-bottom: 0.1rem;
    }
    .prize-quota {
      font-size: 0.24rem;
      color: #ff772d;
    }
    .shop-car {
      width: 0.31rem;
      height: 0.31rem;
      position: absolute;
      right: 0.07rem;
      bottom: 0.13rem;
      transition: all 5s ease;
    }
  }
}
.bottom-bar {
  width: 100%;
  height: 1.48rem;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 99;
  padding: 0 0.3rem;
  .total-shop-car {
    width: 0.6rem;
    height: 0.61rem;
    background: url(//img10.360buyimg.com/imgzone/jfs/t1/232229/14/15298/1267/66068a3aFa67065b2/02c38f4b7397ace0.png);
    background-repeat: no-repeat;
    background-size: 100%;
    position: relative;
    .add-num {
      width: 0.27rem;
      height: 0.27rem;
      line-height: 0.27rem;
      background-color: #f22b2b;
      border-radius: 50%;
      color: #fff;
      font-size: 0.2rem;
      position: absolute;
      top: -0.06rem;
      right: -0.14rem;
    }
    margin-right: 0.56rem;
  }
  .sum {
    font-size: 0.26rem;
    color: #ff772d;
  }
  .discount {
    margin-top: 0.1rem;
    font-size: 0.2rem;
    color: #767676;
  }
  .buy {
    width: 1.84rem;
    height: 0.67rem;
    background-color: #fe792e;
    border-radius: 0.34rem;
    font-size: 0.3rem;
    color: #fff;
    line-height: 0.67rem;
  }
}
</style>
