<template>
<div class="veteSelecbox"
    :style="styleData.veteSelecbox"
    ref="voteSelectNew"
    @click="styleClick('click', 'voteSelectNew')"
    @mousemove="styleClick('mousemove', 'voteSelectNew')"
    @mouseout="styleClick('mouseout')">
    <div :style="styleData.titleImg"></div>
    <div :style="styleData.voteImgStyle">
      <div  v-if="veteSelectData == 1">
        <div :style="styleData.queryTitle">{{votingTheme}}（{{votingForm}}）</div>
        <div  class="veteSelectdiv" :style="styleData.veteSelectdiv">
           <div
          v-for="(item, index) in voteList"
          :key="index"
          @click="SelectButtonClick(index, item)"
        >
        <div :class="item.isChecked?'checkedText voteBox':'voteBox'"  :style="styleData.voteSelectStyle" v-if="voteStick.length == 0">
          <div class="m-r-17">
            <div :style="styleData.voteSelectButton" :class="item.isChecked?'checked':''" >
            <van-icon class="checkedText-icon" name="success" v-if="item.isChecked"/></div>
           </div>
          <div style="flex: 1; text-align: left">{{ item.text }}</div>
        </div>
          <div  v-if="voteStick.length > 0" class="m-b-43">
            <div class="voteTitle">{{ item.text }} <span v-if="item.isChecked"  class="selected">（已选）</span></div>
            <div :style="styleData.ProgressText">
            <div :style="styleData.ProgressTextStyle">
            <div
              class="ProgressColor"
              :style="nowProgressNum +  allNum[index] + '%;'"
            ></div>
          </div>
          <div :style="styleData.ProgressNowNum">
            <span>{{ item.count }} 票 {{ allNum[index]}}%</span>
          </div>
        </div>
          </div>
        </div>
        </div>
        
      </div>
      <!--图片和商品--->
      <div v-else>
        <div :style="styleData.queryTitle">{{votingTheme}}（{{votingForm}}）</div>
        <div  class="veteSelectdiv" :style="styleData.veteSelectdiv">
          <div
          v-for="(item, index) in voteList"
          :key="index"
          :style="styleData.voteSelectImgStyle"
          @click="SelectButtonClick(index, item)"
          >
           <div :style="styleData.voteSelectImgBox">
              <div :style="styleData.voteSelectImg">
              <img :src="item.skuImg || item.imgUrl || item.imagePath" alt />
              </div>
              <div class="itemdiv" :style="styleData.voteSelectImgText">
                <div>{{item.imgName  || item.skuName || item.name}}</div>           
              </div>
           </div>
           <div>
             <div v-if="voteStick.length == 0" :style="styleData.voteSelectButton" :class="item.isChecked?'voteSelectButton':''" >
             <van-icon class="checked-icon" name="success" v-if="item.isChecked"/></div>
             <span v-if="item.isChecked && voteStick.length > 0"  class="selected">已选</span>
           </div>
           <div :style="styleData.Progress" v-if="voteStick.length >0">
            <div :style="styleData.ProgressStyle">
            <div
              class="ProgressColor"
              :style="nowProgressNum +  allNum[index] + '%;'"
            ></div>
          </div>
          <div :style="styleData.ProgressNowNum">
            <span>{{ item.count }} 票 {{ allNum[index]}}%</span>
          </div>
        </div>
            
          </div>
        </div>
      </div>
    </div>
    <div>
      <button :style="styleData.voteButton" class="bnt" :disabled="touPiaoBtn"  @click="voteClick()"  v-if="!drawBnt"> {{ voteText }}</button>
      <button :style="styleData.voteButton" class="bnt" :class="{'over-btn': overBtnClass}"  v-if="drawBnt"  @click="drawClick()">立即抽奖</button>

    </div>

</div>
</template>
<script>
import {
  PrizeResultPopComService,
  NoPrizeResultPopComService,
} from "../../../util/hdzxtcomCreate.js";
import apis1 from "../../../util/apis1.js";
let { votePolitely, voteSavePkResult,startDraw } = apis1;

export default {
  props: [
    "styleData",
    "keyData",
    "datas",
    "isTemplate",
    "templateData",
    "isWebClick",
    "modifyContent",
  ],
  data() {
    return {
      styleDataOld: {},
      voteList: [],
      votingTheme:'',
       nowProgressNum: "width:",
      choiceCount:1, // 最多可投机票
      veteSelectData:1,
      votingForm:'单选',
      voteStick: [], //是否投过票
      voteText: "投票",
      allcount:0,
      allNum: [], //所有选项的概率
      shopId: 0, //商品Id
      voteStickBtn: true,
      checkNow:[], // 选中列表数据
      touPiaoBtn:false, // 活动开始按钮状态
      drawBnt:false, // 立即抽奖
      voteState:false,
      buttonClick:false,//单选是否选
      lotterStater:false, // 抽完奖
      showlist: "",
      prizeResultData: {
        styleData: {},
        datas: {},
        keyData: {
          prizeUrl: "showImg",
          prizeName: "prizeName",
          prizeType: "prizeType",
          priceInfo: "priceInfo",
          discountType: "discountType",
          couponType: "couponType",
        },
      },
      overBtnClass:false
    };
  },
  created() {},
  mounted() {
    //深拷贝重置需要
    this.styleDataOld = JSON.parse(JSON.stringify(this.styleData));
    setTimeout(()=>{
      let actStatus = sessionStorage.getItem("actStatus");
      if (actStatus == 2) {
        this.overBtnClass = true;
      }
    },800)
    this.initdata();
  },
  methods: {
    initdata() {
      //初始化数据
      var datasAll = this.templateData;
      if (this.isTemplate || this.isWebClick) {
        this.veteSelectData = 1;
        this.restDrawCount = 0;
        this.publicData.$emit('voteSelectCount',0)
        if (datasAll) {
           this.showlist = datasAll.draw.prizeList;
          this.veteSelectData = datasAll.voting.votingType;
          this.voteList = datasAll.voting.votingOption;
           this.votingTheme = datasAll.voting.votingTheme
           this.voteText = "投票";
           console.log(datasAll,this.voteList,'datasAll')
        } else {
          this.votingTheme ="你喜欢手机什么功能？"
          this.voteList = [
          {
            count: 0,
            text: "短信功能",
          },
          {
            count: 0,
            text: "计算器",
          },
          {
            count: 0,
            text: "记事本",
          },
          {
            count: 0,
            text: "指南针",
          },
        ];
        }
      } else {
        
          votePolitely((data) =>{
            if(this.voteState){
             this.$toast("投票成功，请抽奖");
             }
              if(data.resp_code == 0){
              this.publicData.$emit('voteSelectCount',data.data.voteUserCount)
              this.veteSelectData = data.data.votingType
              this.choiceCount = data.data.choiceCount
              this.canDraw = data.data.canDraw
              if(data.data.skuInfos){
               this.voteList = data.data.skuInfos
              } else {
                this.voteList = data.data.rule
              }
              this.allcount = 0
              if(this.voteList && this.voteList.length >0){
                this.voteList.forEach(item =>{
                   this.allcount = this.allcount + item.count
                  // 添加标识
                  this.$set(item,'id',Math.random())
                  // 添加选中状态
                  this.$set(item,'isChecked',false)
                })
              }
              this.votingTheme = data.data.votingTheme
              if(data.data.votingForm && data.data.votingForm == 1){
                  this.votingForm = '单选'
              } else{
                   this.votingForm = '多选'
              }
              if(data.data.voteSelectList && data.data.voteSelectList.length > 0){
              if(data.data.canDraw){
               this.drawBnt = true
              } else{
                 this.touPiaoBtn = true
                this.voteText = "您已投票";
                this.lotterStater = true
              }
               this.voteStick = data.data.voteSelectList
               this.voteList.forEach((item,index) =>{
                 if(this.allcount != 0){
                  this.allNum[index] = (item.count / this.allcount * 100).toFixed(2)
                 } else {
                  this.allNum[index] = 0
                 }
                 
                 console.log(this.allcount,this.allNum[index],'this.allNum')
                 this.voteStick.forEach(ele =>{
                  if(item.skuId == ele || item.text == ele || item.imgName == ele){
                    item.isChecked = true
                  }
                 })
                  
                })
              }
              

              }
              
             
             
          })
       
    this.publicData.$on("prizeList", (content) => {         
        this.showlist = content;
        console.log(content,'111111111111')
       });
      }
    },
    styleClick(type, refName) {
      if (this.isWebClick) {
        //传值给B端
        let byValue = {
          modifyContent: this.modifyContent,
          refName: refName,
          styleData: this.styleData,
          c_this: this,
          styleDataOld: this.styleDataOld,
        };
        this.$emit("opertaionCom", type, byValue);
      }
    },
    SelectButtonClick(num, item) {
     
      if (this.isTemplate|| this.isWebClick) {
        // this.$toast("活动预览，仅供查看");
        return;
      }
      let actStatus = sessionStorage.getItem("actStatus");
      if (actStatus == 2) {
        this.$toast("活动已结束");
        this.startTime = false;
        return;
      }
      if (actStatus == 1) {
        this.$toast("活动未开始");
        this.startTime = false;
        return;
      }
      console.log(this.canDraw || this.lotterStater,this.lotterStater,'this.lotterStater')
      if(this.canDraw || this.lotterStater){
        this.$toast("已投完票");
        return;
      }
      
      // 判断单选还是多选
      if(this.votingForm == '单选'){
       
        if(this.checkNow && this.checkNow.length > 0 ){
         
          if(this.checkNow[0] != item){
            
          this.checkNow = []
          this.checkNow[0] = item
           this.voteList.forEach(ele =>{
           if(ele.id === item.id){
            ele.isChecked = true
           } else {
            ele.isChecked = false
           }
           })
          } else {
           this.minusList(item)
          }
        } else {
         this.addList(item)
        }
         console.log(this.checkNow,this.voteList,'this.checkNow')
      } else{
        if(this.checkNow.includes(item)){
         this.minusList(item)
        } else {
            this.addList(item)
        }        
        console.log(this.checkNow,'this.checkNow--0-0-0-0-0-0-0-0-0');
      }
    },
    // 添加选中
    addList(list){
      this.checkNow = this.checkNow.concat(list)
      this.voteList.forEach(item =>{
        if(item.id === list.id){
          item.isChecked = true
        }
        if(this.votingForm == '单选'){
           if(item.id === list.id){
          item.isChecked = true
        }else{
          item.isChecked = false
        }
        }
      })
      console.log(this.voteList,'this.voteList')
    },
    // 减去选中
    minusList(list){
      this.checkNow = this.checkNow.filter(item => item != list)
      this.voteList.forEach(item =>{
        if(item.id === list.id){
          item.isChecked = false
        }
      })
      console.log(this.checkNow,this.num,'this.num222333333333')
    },
    // 投票
    voteClick(){
       if (this.isTemplate  || this.isWebClick) {
        // this.$toast("活动预览，仅供查看");
        return;
      }
      let actStatus = sessionStorage.getItem("actStatus");
      if (actStatus == 2) {
        this.$toast("活动已结束");
        this.startTime = false;
        return;
      }
      if (actStatus == 1) {
        this.$toast("活动未开始");
        this.startTime = false;
        return;
      }
      if(!this.checkNow || this.checkNow.length == 0 ){
         this.$toast("请投票");
         return
      }
      if(this.choiceCount < this.checkNow.length){
        this.$toast("最多可以投" + this.choiceCount + "票" );
       return 
      }
      if(this.votingForm != '单选'){
        if(2 > this.checkNow.length){
        this.$toast("多选最少投2票" );
       return 
      }

      }
      this.touPiaoBtn = true
      let parameter = []
      this.checkNow.forEach((item,index) => {
        if(this.veteSelectData == 3){
         parameter[index] = item.skuId

      } else if(this.veteSelectData == 2){
         parameter[index] = item.imgName
       
      }else {
        parameter[index] = item.text
      }
         
        })
      
      voteSavePkResult(parameter, (data) => {
        parameter =  this.checkNow
        if(data.resp_code == 0){
          this.drawBnt = true
          this.touPiaoBtn = false
          this.voteState = true
          this.initdata()
           
        }
      })
    },
    // 抽奖
    drawClick(){
       
      this.voteState = false
      let that = this;
      startDraw((initDatas) => {
        this.publicData.$emit('reloadPrize',true)
          if (initDatas.resp_code == 50009) {
            that.$toast("活动已结束");
            that.showAlert = false;
            return;
          } else if (initDatas.resp_code != 0) {
            that.showAlert = false;
            
          } else {
            this.lotterStater = true
            if (initDatas.data == "") {
              
              that.fulfillHandle("未中奖", initDatas.data);
            } else {
              that.fulfillHandle("已中奖", initDatas.data);
            }
          }
          console.log("initDatas.data", initDatas.data);
        });
    },
    fulfillHandle(prizeData, initDatas) {
      console.log(prizeData, initDatas);
      this.showAlert = false;
      if (prizeData == "未中奖") {
        NoPrizeResultPopComService.create(
         this.styleData,
          (submit) => {
            NoPrizeResultPopComService.close();
             this.initdata()
              this.drawBnt = false
             this.touPiaoBtn = true
             this.voteText = "您已投票";
          }
        );
      } else {
        //中奖
        let prizeData;
        for (let i = 0; i < this.showlist.length; i++) {
          if (initDatas.prizeInfoId == this.showlist[i].id) {
            prizeData = this.showlist[i];
          }
        }
        
        this.publicData.$emit("isNotyFiceWinnerReorrd", true, this.isTemplate);
        this.prizeResultData.datas = prizeData;
        PrizeResultPopComService.create(
          this.prizeResultData,
          initDatas,
          this.styleData,
          (submit) => {
            PrizeResultPopComService.close();
            this.initdata()
            
            this.drawBnt = false
             this.touPiaoBtn = true
             this.voteText = "您已投票";
          }
        );
      }
    },

  },
};
</script>
<style lang="scss" scoped>
.veteSelectimg {
  width: 160px;
  height: 160px;
}
.veteSelectimg1 {
  width: 60px;
  height: 60px;
}
.selected {
  color: #F2270C;
  font-size: 0.24rem;
  font-weight: bold;
}

.itemdiv {
  height: 1rem;
  position: relative;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
}

.ProgressColor {
  height: 100%;
  background-color: #F2270C;
border-radius: 4px;
}
.buttonCheck {
  background: #6379FF;
  text-align: center;
  font-size: 0.3rem;
  font-weight: bolder;
  line-height: 0.3rem;
  color: white;
}

.veteSelecbox {
  position: relative;
}
.checked-icon{
    width: 100%;
    display: inline-block;
     text-align: center;
    font-size: 0.24rem;
    font-weight: bolder;
    line-height: 0.2rem;
    color: white;

}
.voteSelectButton{
   background: #6379FF;
}
.bnt[disabled]{
  
background: #BFBFBF !important;
}
.m-r-17{
  margin-right: 0.17rem;
}
.checkedText{
background: #6379FF;
color: #fff !important;
}
.checked{
  
background: #FFFFFF;
border-color: #FFFFFF !important;
}
.checkedText-icon{
  color: #6379FF;
}
.voteBox{
  display: flex;
  align-items: center;
  justify-content:flex-start;
}
.m-b-43{
  margin-bottom: 0.43rem;
}
.voteTitle{
  font-size: 0.24rem;
  font-weight: 500;
color: #262626;
line-height:1 ;
text-align: left;
vertical-align: center;
}
.over-btn{
  background: linear-gradient(90deg, #b9b9ba 0%, #c9c9c9 100%) !important;

}
</style>