<template>
  <div class="purchaseDivAll" ref="pointExchangePrize" @click="styleClick('click', 'pointExchangePrize')"
    @mousemove="styleClick('mousemove', 'pointExchangePrize')" @mouseout="styleClick('mouseout')">
    <div :style="styleData.topTitle">我的积分<span :style="styleData.topTitleSpan">{{myPoints}}</span></div>
    <div v-if="pointExchangePrizeVoList.length > 1" :style="styleData.previewBox">
      <div class="previewUl">
        <div v-for="(item,index) in pointExchangePrizeVoList" :style="styleData.previewItem" :data-index="index" :class="currentIndex == index ? 'selectedBox':'ordinaryBox'" @click="jumpIndex(index)">
          <div :style="styleData.previewImgBox">
            <img :src="item.showImg" alt="" :style="styleData.previewImg">
          </div>
          <div :style="styleData.previewName">{{item.prizeName}}</div>
        </div>
      </div>
    </div>
    <van-swipe ref="swiper" class="my-swipe" :autoplay="5000" indicator-color="white" :style="styleData.swiperAll" @change="onChange">
      <van-swipe-item v-for="(item,index) in pointExchangePrizeVoList" :key="index">
        <div class="fd-item-content">
          <div class="fd-row">
            <!-- 商品图片 -->
            <div :style="styleData.skuPicture">
              <img :src="item.showImg" alt=".." style="width:1.5rem;height:1.5rem">
            </div>
            <div :style="styleData.rightContent">
              <!-- 商品名称 -->
              <div :style="styleData.prizeName">
                {{item.prizeName}}
              </div>

              <!-- 剩余份数 -->
              <div :style="styleData.stock">
                奖品剩余：{{item.stock}}份
              </div>
              <div :style="styleData.fullMsg">
                <span :style="styleData.fullSpan">{{item.num}}</span>积分
              </div>
            </div>
          </div>
          <!-- 按钮 -->
          <div v-if="item.status == 1 && (canExchangeNum ==0 || canExchangeNum >= pointExchangePrizeVoList.length)" :style="styleData.btn1" @click="prizeStstusClick(item)"></div>
          <div v-if="item.status == 1 && canExchangeNum >=0 && canExchangeNum < pointExchangePrizeVoList.length" 
          :style="styleData.btn1" @click="receiveClick(item)"></div>
          <div v-if="item.status == 2" :style="styleData.btn2"></div>
          <div v-if="item.status == 3" :style="styleData.btn3"></div>
        </div>
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script>
import Vue from 'vue';
import { CountDown, Progress,Dialog } from 'vant';
Vue.use(CountDown);
Vue.use(Progress);
Vue.use(Dialog);
import apis1 from '../../../util/apis1.js';
let { pointExchange, pointExchangeExchange } = apis1;
import store from '../../../store/store.js';
import { PrizeResultPopComService, NoPrizeResultPopComService } from '../../../util/hdzxtcomCreate.js';
export default {
  props: ['datas', 'styleData', 'keyData', 'isTemplate', 'templateData', 'modifyContent', 'isWebClick'],
  data() {
    return {
      pointExchangePrizeVoList: [],
      basicData: {},
      myPoints: '',
      flag: false,
      canExchangeNum:0,
      currentIndex: 0
    };
  },
  created() {
    this.initData();
  },
  methods: {
    //点击可修改位置的方法
    styleClick(type, refName) {
      if (this.isWebClick) {
        //传值给B端
        let byValue = {
          modifyContent: this.modifyContent,
          refName: refName,
          styleData: this.styleDataNew,
          isCustomSwitching: this.receive,
          c_this: this,
          styleDataOld: this.styleDataOld
        };
        this.$emit('opertaionCom', type, byValue);
      }
    },
    initData() {
      if (this.isTemplate) {
        console.log(this.templateData, 'this.templateData');
        if (this.templateData) {
          let activityCommonRule = [{
            prizeName: this.templateData.pointsExchange.draw.prizeList[0].prizeName,
            showImg: this.templateData.pointsExchange.draw.prizeList[0].showImg,
            num: this.templateData.pointsExchange.draw.prizeList[0].num,
            stock: this.templateData.pointsExchange.draw.prizeList[0].totalPrizeNum,
            orderPrice: 0,
            receivingPrice: 0,
            orderNum: 0,
            receivingNum: 0,
            orderSkuNum: 0,
            receivingSkuNum: 0,
            status: '1' // 1可兑换，2兑换过，3没库存
          }]
          this.myPoints = '***'
          this.pointExchangePrizeVoList = activityCommonRule
        } else {
          this.myPoints = '***'
          let activityCommonRule = [{
            prizeName: '积分',
            showImg: '//img10.360buyimg.com/imgzone/jfs/t1/172629/8/10529/9649/60a4cb50Edc2ee40a/b53b1246de5f2089.png',
            num: 20,
            stock: 5,
            orderPrice: 0,
            receivingPrice: 0,
            orderNum: 0,
            receivingNum: 0,
            orderSkuNum: 0,
            receivingSkuNum: 0,
            status: '1' // 1可兑换，2兑换过，3没库存
          },
          {
            prizeName: '积分',
            showImg: '//img10.360buyimg.com/imgzone/jfs/t1/172629/8/10529/9649/60a4cb50Edc2ee40a/b53b1246de5f2089.png',
            num: 20,
            stock: 5,
            orderPrice: 0,
            receivingPrice: 0,
            orderNum: 0,
            receivingNum: 0,
            orderSkuNum: 0,
            receivingSkuNum: 0,
            status: '1' //1可兑换，2兑换过，3没库存
          }]
          this.pointExchangePrizeVoList = activityCommonRule
        }
      } else {
        pointExchange(res => {
          this.myPoints = res.data.myPoints
          this.pointExchangePrizeVoList = res.data.pointsExchangePrizeVos
          this.basicData = res.data
          this.canExchangeNum = res.data.canExchangeNum
        });
      }
    },
    receiveClick(item){
      let haveNum = 0 
      this.pointExchangePrizeVoList.map(item=>{
        if(item.status !=1){
          haveNum ++
        }
      })
      Dialog.confirm({
        message: `
        <div>当前活动可兑换<span style="color: red;">${this.pointExchangePrizeVoList.length}</span>个奖品，当前已兑换<span style="color: red;">${haveNum}</span>个奖品，还可兑换<span style="color: red;">${this.canExchangeNum - haveNum}</span>个奖品。是否确认兑换？</div>
      `,
      })
        .then(() => {
          this.prizeStstusClick(item)
        })
        .catch(() => {
          
        });
    },
    //奖品状态点击
    prizeStstusClick(item) {
      console.log(item);
      if (this.isTemplate) {
        // this.$toast('活动预览，仅供参考');
        return;
      }
      let actStatus4 = sessionStorage.getItem('actStatus');
      if (actStatus4 == 1) {
        this.$toast('活动尚未开始');
        return;
      }
      if(this.flag == true){
        console.log(11111,"lussss");
        
        return
      }
      this.flag = true;
      if (item.status == 1) {
          //正常领奖
          let params = {
            prizeInfoId: item.prizeInfoId,
            status: item.status
          }
          pointExchangeExchange({ ...params }, receiveData => {
            if (receiveData.resp_code == 0) {
              if (receiveData.data.result == true) {
                this.initData();
                this.publicData.$emit('isNotyFiceWinnerReorrd', true, this.isTemplate);
                var obj = {
                  datas: {},
                  keyData: {
                    prizeUrl: 'showImg',
                    prizeName: 'prizeName',
                    prizeType: 'prizeType',
                    priceInfo: 'priceInfo',
                    discountType: 'discountType',
                    couponType: 'couponType'
                  }
                };
                obj.datas = receiveData.data;
                if (receiveData.data.status == '1') {
                  PrizeResultPopComService.create(obj, receiveData.data, this.styleData, submit => {
                    PrizeResultPopComService.close();
                  });
                }
              } else {
                if (receiveData.data.status == '2') {
                  NoPrizeResultPopComService.create(this.styleData, submit => {
                    NoPrizeResultPopComService.close();
                  });
                  this.initData()
                } else if (receiveData.data.status == '5') {
                  pointExchange(res => {
                    this.myPoints = res.data.myPoints
                    this.pointExchangePrizeVoList = res.data.pointsExchangePrizeVos
                    this.basicData = res.data
                    this.$toast('积分扣减失败~');
                  });
                } else if (receiveData.data.status == '6') {
                  pointExchange(res => {
                    this.myPoints = res.data.myPoints
                    this.pointExchangePrizeVoList = res.data.pointsExchangePrizeVos
                    this.basicData = res.data
                    this.$toast('抱歉您的积分不足，不符合兑奖资格~');
                  });
                }else if (receiveData.data.status == '7') {
                  pointExchange(res => {
                    this.myPoints = res.data.myPoints
                    this.pointExchangePrizeVoList = res.data.pointsExchangePrizeVos
                    this.basicData = res.data
                    this.$toast('发奖失败，积分已退还~');
                  });
                }
              }
              this.flag = false;
            } else if (receiveData.resp_code == 50079) {
              this.$toast(`${receiveData.resp_msg}`);
              this.flag = false;
            } else {
              this.$toast(`${receiveData.resp_msg}`);
              this.flag = false;
            }
          });

      }
    },
    onChange(index) {
      this.currentIndex = index;
      this.$nextTick(() => {
        const previewUl = this.$el.querySelector('.previewUl');
        if (!previewUl) return;
        const items = previewUl.querySelectorAll('[data-index]');
        const currentItem = items[index];

        if (currentItem && previewUl) {
          const containerWidth = previewUl.offsetWidth;
          const itemWidth = currentItem.offsetWidth;
          const itemLeft = currentItem.offsetLeft;

          const scrollLeft = itemLeft - (containerWidth / 2) + (itemWidth / 2);
          previewUl.scrollTo({
            left: scrollLeft,
            behavior: 'smooth'
          });
        }
      });
    },
    jumpIndex(index) {
      this.currentIndex = index;
      this.$refs.swiper.swipeTo(index);

      this.$nextTick(() => {
        const previewUl = this.$el.querySelector('.previewUl');
        if (!previewUl) return;
        const items = previewUl.querySelectorAll('[data-index]');
        const currentItem = items[index];

        if (currentItem && previewUl) {
          const containerWidth = previewUl.offsetWidth;
          const itemWidth = currentItem.offsetWidth;
          const itemLeft = currentItem.offsetLeft;

          const scrollLeft = itemLeft - (containerWidth / 2) + (itemWidth / 2);
          previewUl.scrollTo({
            left: scrollLeft,
            behavior: 'smooth'
          });
        }
      });
    }
  }
};
</script>

<style lang="scss">
.purchaseDivAll {
  .getDrawConditionDiv {
    // text-decoration: underline;
  }
  .orderEndTimeDiv {
    font-size: 0.3rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    height: 100%;
    background: #8f3f37;
    width: 2.7rem;
    height: 0.4rem;
    border-radius: 0.2rem;
    margin-left: 3.5rem;
  }
  .prizeDivAll {
    padding: 0.45rem 0.44rem 0 0.44rem;
  }

  .prizeImageDiv {
    width: 1.8rem;
    height: 1.8rem;
    border-radius: 50%;
  }

  .prizeStatusImgStyle {
    width: 1.91rem;
    height: 0.55rem;
  }
  .horizontal-scroll {
    &::-webkit-scrollbar {
      height: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #ccc;
      border-radius: 3px;
    }
  }
}
.fd-item-content {
  width: 100%;
  height: 100%;
  .fd-row {
    display: flex;
    flex-direction: row;
  }
}
.van-swipe__track {
  width: 100% !important;
  height: 100%;
}
.previewUl {
  display: flex;
  overflow-x: auto;
  width: 6.9rem;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
  padding: 0.5rem 0; /* 给放大元素留出空间 */
}
.previewUl::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.selectedBox {
  transform: scale(1.3);
  transform-origin: center;
  z-index: 10;
  position: relative;
  margin: 0 10px;
}
.ordinaryBox {
  margin: 0 10px;
}
</style>

