const util = require('../../utils/util.js');
const app = getApp();
Page({
  data: {
    prizeId:'',   //填写地址，奖品id
    wheelId:'',//大转盘id
    winThePrize:{},//中奖奖品信息
    PrizeList:[],
    winPrizeList:[],
    tablePageInfo:{},
    tableSize:'',
    awardsList:[],
    pageIndex:1,
    runDegs:0,
    animationData:{},
    showAwardPopup:false,  //奖品详情弹窗
    showRulesPopup:false,  // 活动规则
    showPrizePopup:false,  //中奖弹窗
    showtableStatus:false, //转盘状态
    showAddress:false,      //地址弹窗 
    prizeInfo:{},   //奖品详情页
    shareTitle:'',
    theam:'redContent',  //redContent --0 blueContent  --1 greenContent  --2
    scrollTop:0,
    scrollIndex:'view0',
    timer:''//定时器
  },
  onLoad: function (options) {
    console.log('options',options)
    if (!util.isEmpty(options.id)) {
      this.setData({wheelId:options.id})
    }
    // 通过二维码进入
    if (!util.isEmpty(options.scene)) {
      console.log('scene',options.scene)
      this.setData({wheelId:options.scene})
    }

    this.setData({
      tableSize: wx.getSystemInfoSync().windowWidth - 40
    })
  },
  onReady: function () {
  },
  onShow: function () {
    this.getTableView()
  },
  // 再来一次
  tryAgain(){
    this.setData({
      showPrizePopup:false
    })
    setTimeout(() => {
      this.getPrize()
    }, 500);
  },
  // 填写地址
  inputAddress(e){
    this.setData({
      showPrizePopup:false,
      showAddress:true,
      prizeId:e.detail.id
    })
  },
  // 获取更多机会
  getMoreChange(){
    this.setData({showtableStatus:false})
    wx.navigateTo({
      url: '/pages/turntable/getPrizeTimes/index?wheelId='+this.data.wheelId+'&theam='+this.data.theam,
    })
  },
  // 获取分享标题
  getShareTitle(){
    let that=this;
    util.ajax({
      func: "v2/market/wheel/info",
      data: {wheelId:this.data.wheelId}
    }, function (res) {
      if (res.code==0) {
        that.setData({
          shareTitle:res.data.shareTitle
        })
      } else {
        util.showTips(res.reason)
      }
    })
  },
  // 滚动条滚动
  scrollTopBar(){
    let timer = setInterval(() => {
    let viewNum=this.data.scrollIndex.slice(4);
    this.setData({scrollIndex:parseInt(viewNum)>=this.data.winPrizeList.length-1?('view0'):('view'+(parseInt(viewNum)+2))})
    }, 2000);
    this.setData({timer})
  },
  // 获取大转盘页面显示信息
  getTableView(){
    let id = this.data.wheelId,that=this;
    util.ajax({
      func: "v2/market/wheel/index",
      data: {wheelId:id}
    }, function (res) {
      if (res.code==0) {
        that.setData({
          tablePageInfo:res.data,
          theam:that.selectTheme(res.data.theme)
        })
        that.initialization();
        that.getPrizeList();
        that.getWinprizeList();
        that.getShareTitle()
      } else {
        util.showTips(res.reason);
      }
    })
  },
  // 判定标题
  selectTheme(theme){
    let str=''
    switch (theme) {
      case 0:
        str='redContent'
        break;
      case 1:
        str='blueContent'
        break;
      case 2:
        str='greenContent'
        break;
    }
    return str;
  },
  // 初始化大转盘
  initialization(){
    let awardsConfig = this.data.tablePageInfo,
    len = awardsConfig.itemList.length,
    rotateDeg = 360 / len / 2 + 90,
    turnNum = 1 / len,
    html = [];
    // var ctx = wx.createContext()
    for (var i = 0; i < len; i++) {
      // 奖项列表
      html.push({turn: i * turnNum + 'turn', lineTurn: i * turnNum + turnNum / 2 + 'turn', award: awardsConfig.itemList[i].title,url:awardsConfig.itemList[i].logo,showWheelLogo: awardsConfig.itemList[i].showWheelLogo});
    }
    this.setData({
      awardsList: html,
      btnDisabled: ''
    });
  },
  // 点击抽奖
  getPrize(){
    this.setData({btnDisabled: 'disabled'})
    let that=this,wheelId=this.data.wheelId,peopleId=this.data.tablePageInfo.peopleId;
    util.ajax({
      func: `v2/market/wheel/${wheelId}/draw`,
      data: {
        peopleId:peopleId,
        wheelId:wheelId
      }
    }, function (res) {
      if (res.code==0) {
        if (res.data.status==1) {
          that.setData({winThePrize:res.data.item})
          let index=0,prize={};
          that.data.tablePageInfo.itemList.forEach((el,i) => {
            if (el.itemId==res.data.item.id) {
              index=i;
              prize=res.data;
            }
          });
          that.getLottery(index,prize)
        } else {
          if (res.data.status!=5) {
            that.setData({
              showtableStatus:true,
              status:res.data.status
            })
          }else{
            that.setData({btnDisabled: ''})
            util.showTips(res.data.message);
          }
        }
      }else{
        util.showTips(res.reason);
      }
    })
  },
  getLottery(index,info) {
    var that = this
    var awardIndex =index;
    var awardsConfig = this.data.tablePageInfo, // 获取奖品配置
        runNum = 6 //旋转圈数
    // 旋转抽奖
    this.data.tablePageInfo.actnum=this.data.tablePageInfo.actnum <=0 ? 0:this.data.tablePageInfo.actnum-1;
    let len =360/awardsConfig.itemList.length/2;
    let random = this.random(-len+1,len-1)
    this.data.runDegs = this.data.runDegs || 0
    this.data.runDegs = this.data.runDegs + (360 - this.data.runDegs % 360) + (360 * runNum - awardIndex * (360 / awardsConfig.itemList.length))+random
    var animationRun = wx.createAnimation({
      duration: 6000,
      timingFunction: 'cubic-bezier(.42,.05,.2,.97)'
    })
    that.animationRun = animationRun
    animationRun.rotate(that.data.runDegs).step()
    that.setData({
      animationData: animationRun.export(),
      'tablePageInfo.actnum':this.data.tablePageInfo.actnum
    })
    // 中奖提示
    setTimeout(function() {
      that.setData({
        showPrizePopup:true,
        winPrizeInfo:info
      })
      if (awardsConfig.chance) {
        that.setData({
          btnDisabled: ''
        })  
      }
    }, 6500);
  },
  // 随机转动度数
  random(m,n) {
    return Math.floor(Math.random() * (n - m)) + m
  },
  // 跳转至中奖记录页面
  jumpRecord(){
    wx.navigateTo({
      url: '/pages/turntable/winRecord/index?wheelId='+this.data.wheelId+'&theam='+this.data.theam,
    })
  },
  // 奖品详情页弹窗
  openPrizeDetail(e){
    let data=e.currentTarget.dataset
    switch (data.name) {
      case 'rules':
        this.setData({
          showRulesPopup:true
        })
        break;
      case 'award':
        this.setData({
          showAwardPopup:true,
          prizeInfo:data.item
        })
        break;
    }
  },
  // 关闭上拉弹窗
  closeTip(e){
    let data = e.detail;
    switch (data.type) {
      case 'award':
        this.setData({
          showAwardPopup:data.status
        })
        break;
      case 'rules':
        this.setData({
          showRulesPopup:data.status
        })
        break;
      case 'notice':
        this.setData({
          showPrizePopup:data.status,
          btnDisabled: '',
        })
        break;
      case 'table':
        this.setData({
          showtableStatus:data.status,
          btnDisabled: '',
        })
        break;
      case 'address':
        this.setData({
          showAddress:data.status,
          btnDisabled: '',
        })
        break;
    }
  },
  // 获取奖品列表
  getPrizeList(){
    let that =this;
    util.ajax({
      func: `v2/market/wheel/item/list`,
      data: { wheelId:that.data.wheelId}
    }, function (res) {
      if (res.code==0) {
        that.setData({PrizeList:res.data})
      }else{
        util.showTips(res.reason);
      }
    })
  },
  // 获取中奖名单列表
  getWinprizeList(bol){
    let that =this;
    util.ajax({
      func: `v2/market/wheel/winning/list`,
      data: { 
        wheelId:that.data.wheelId,
      }
    }, function (res) {
      if (res.code==0) {
        if (res.data.length>0) {
          that.setData({
            winPrizeList:res.data
          })
            that.scrollTopBar()
        }
      }else{util.showTips(res.reason);}
    })
  },
// 用户点击右上角分享
  onShareAppMessage: function () {
    return {
      title:this.data.shareTitle,
      path:'/pages/turntable/index?id='+this.data.wheelId,
    }
  },
  onHide: function () {
    let e = this;
    clearInterval(e.data.timer);
  },
  // 页面卸载关闭定时器
  onUnload: function () {
    let e = this;
    clearInterval(e.data.timer);
  },
})