var app = getApp()
Page({
  data: {
    awardsList: {},
    animationData: {},
    btnDisabled: '',
    record: [],
    prize: '',
    mobile: '',
    awardsConfig: [
      { 'index': 1, 'name': '你要发', awards: '一等奖' },
      { 'index': 2, 'name': '路路顺', awards: '二等奖'},
      { 'index': 3, 'name': '一定发', awards: '三等奖'},
      { 'index': 4, 'name': '财运来', awards: '四等奖'},
      { 'index': 5, 'name': '好运来', awards: '五等奖'},
      { 'index': 6, 'name': '谢谢参与', awards: '谢谢参与'}
    ]
  },
  onLoad:function () {
    let _this = this;
    _this.getList();
  },
  onShow: function () {
    let _this = this;
    let mobile = wx.getStorageSync('persion').persion.mobile;
    if(!mobile) {
      wx.showModal({
        title: '提示',
        content: '您没有绑定手机号！',
        confirmText: '绑定抽奖',
        cancelText: '残忍拒绝',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/mine/wxml/Connect/Connect'
            })
          } else if (res.cancel) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    } else {
      var reg = /^(\d{3})\d{4}(\d{4})$/;
      _this.setData({
        mobile: mobile.replace(reg, "$1****$2")
      })
    }
  },

  startLottery: function (e) {
    let _this = this;
    _this.setData({
      btnDisabled: 'disabled'
    })
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/wx_lottery_raffle',
      data: '',
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        if(data.data.tip.type === "success"){
          _this.getLottery(data.data.ranking-1)
        } else {
          wx.showModal({
            title: '提示',
            content: data.data.tip.msg,
            showCancel: false
          });
          _this.setData({
            btnDisabled: ''
          })
        }
      },
      fail: function(res) {},
      complete: function (res) {},
    })
  },
  getLottery: function (awards) {
    var that = this
    // var num = Math.random();
    // var awardIndex = num * 6 >>> 0;
    var awardIndex = awards;
    // 获取奖品配置
    var awardsConfig = app.awardsConfig
    // if (awardIndex < 2) awardsConfig.chance = false
    // 初始化 rotate
    var animationInit = wx.createAnimation({
      duration: 1
    })
    this.animationInit = animationInit;
    animationInit.rotate(0).step()
    this.setData({
      animationData: animationInit.export(),
      btnDisabled: 'disabled'
    })

    // 旋转抽奖
    setTimeout(function () {
      var animationRun = wx.createAnimation({
        duration: 4000,
        timingFunction: 'ease'
      })
      that.animationRun = animationRun
      animationRun.rotate(360 * 8 - awardIndex * (360 / 6)).step()
      that.setData({
        animationData: animationRun.export()
      })
    }, 100)

    // 中奖提示
    setTimeout(function () {
      wx.showModal({
        title: '恭喜',
        content: '您抽中了' + (awardsConfig.awards[awardIndex].awards + awardsConfig.awards[awardIndex].name),
        showCancel: false
      });
      if (awardsConfig.chance) {
        that.setData({
          btnDisabled: ''
        })
      };
      that.getList();
    }, 4100);


    /*wx.request({
      url: '../../data/getLottery.json',
      data: {},
      header: {
          'Content-Type': 'application/json'
      },
      success: function(data) {
      },
      fail: function(error) {
        wx.showModal({
          title: '抱歉',
          content: '网络异常，请重试',
          showCancel: false
        })
      }
    })*/
  },
  onReady: function (e) {

    var that = this;

    // getAwardsConfig
    app.awardsConfig = {
      chance: true,
      awards: [
        { 'index': 1, 'name': '你要发', awards: '一等奖' },
        { 'index': 2, 'name': '路路顺', awards: '二等奖' },
        { 'index': 3, 'name': '一定发', awards: '三等奖' },
        { 'index': 4, 'name': '财运来', awards: '四等奖' },
        { 'index': 5, 'name': '好运来', awards: '五等奖' },
        { 'index': 6, 'name': '谢谢参与', awards: '' }
      ]
    }

    // wx.setStorageSync('awardsConfig', JSON.stringify(awardsConfig))


    // 绘制转盘
    var awardsConfig = app.awardsConfig.awards,
      len = awardsConfig.length,
      rotateDeg = 360 / len / 2 + 90,
      html = [],
      turnNum = 1 / len  // 文字旋转 turn 值
    that.setData({
      btnDisabled: app.awardsConfig.chance ? '' : 'disabled'
    })
    var ctx = wx.createContext()
    for (var i = 0; i < len; i++) {
      // 保存当前状态
      ctx.save();
      // 开始一条新路径
      ctx.beginPath();
      // 位移到圆心，下面需要围绕圆心旋转
      ctx.translate(150, 150);
      // 从(0, 0)坐标开始定义一条新的子路径
      ctx.moveTo(0, 0);
      // 旋转弧度,需将角度转换为弧度,使用 degrees * Math.PI/180 公式进行计算。
      ctx.rotate((360 / len * i - rotateDeg) * Math.PI / 180);
      // 绘制圆弧
      ctx.arc(0, 0, 150, 0, 2 * Math.PI / len, false);

      // 颜色间隔
      if (i % 2 == 0) {
        ctx.setFillStyle('#ffb820');
      } else {
        ctx.setFillStyle('#ffcb3f');
      }

      // 填充扇形
      ctx.fill();
      // 绘制边框
      ctx.setLineWidth(0.5);
      ctx.setStrokeStyle('#e4370e');
      ctx.stroke();

      // 恢复前一个状态
      ctx.restore();

      // 奖项列表
      html.push({ turn: i * turnNum + 'turn', award: awardsConfig[i].name });
    }
    that.setData({
      awardsList: html
    });

    wx.drawCanvas({
      canvasId: 'lotteryCanvas',
      actions: ctx.getActions()
    })

  },
  getList: function () {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/list_lottery',
      data: '',
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (data) {
        if (data.data.data.length > 0) {
          _this.setData({
            record: data.data.data,
            prize: _this.data.awardsConfig[data.data.data[0].ranking - 1].name
          });
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  }

})
