// pages/bigWheel/bigWheel.js
var app = getApp()
Page({
  data: {
    circleList: [],//圆点数组
    awardList: [],//奖品数组
    colorCircleFirst: '#FFDF2F',//圆点颜色1
    colorCircleSecond: '#FE4D32',//圆点颜色2
    colorAwardDefault: '#F5F0FC',//奖品默认颜色
    colorAwardSelect: '#ffe400',//奖品选中颜色
    indexSelect: -1,//被选中的奖品index
    isRunning: false,//是否正在抽奖
    imageAward: [

    ],//奖品图片数组
    times: '140',//转盘转动的速度
    image: [],
    probabi: [],
    turnName: [],
    chouId: [],
    acc: '',
    user_id: '',
    address: '',
    info: '',
  },

  //中奖纪录
  get_record: function () {
    wx.navigateTo({
      url: '../record/record',
    })
  },

  onLoad: function (options) {
    var _this = this;

    //获取user_id
    // wx.request({
    //   url: app.globalData.hostname + 'Api/Api/getUserInfo',
    //   data: {
    //     openid: wx.getStorageSync('openid')
    //   },
    //   header: {
    //     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
    //   },
    //   method: 'POST',
    //   success: function (res) {
    //     var user_id = res.data.data.id
    //     _this.setData({
    //       user_id: user_id
    //     })
    //   },
    // })

    //获取个人信息
    // wx.request({
    //   url: app.globalData.hostname + 'home/index/default_address',
    //   data: {
    //     openid: wx.getStorageSync('openid')
    //   },
    //   header: {
    //     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
    //   },
    //   method: 'GET',
    //   success: function (res) {
    //     console.log(res.data.result)
    //     if (res.data.status == 1) {
    //       var oData = res.data.result
    //       var oText = oData.province + oData.city + oData.area + oData.detail
    //       var address_id = oData.id
    //       _this.setData({
    //         info: oData,
    //         address: oText,
    //         address_id: address_id
    //       })
    //     } else {
    //       _this.setData({
    //         address: '',
    //         info: res.data.result
    //       })
    //     }
    //   },
    // })

    var that = this;
    var user_Id = app.globalData.userId;
    wx.request({
      url: 'https://jisu.shenmikj.com/mall_case/black_gb/mall_mchs/Game/wheel_index',
      // url: "https://jisu.shenmikj.com/zhuangzhuang/" + 'Api/BigWheel/index',
      // url: app.globalData.hostname + 'Api/BigWheel/index',
      data: {},
      success: function (res) {
        console.log(res.data.data, '123');
        var imgText = [];
        var probabi = [];
        var turnName = [];
        var chouId = [];
        var dingyi;
        for (var i = 0; i < res.data.data.length; i++) {
          //图
          var img = res.data.data[i].img;
          imgText.push(img);
          //概率
          var baibi = res.data.data[i].probability;
          probabi.push(baibi);
          //名字
          var name = res.data.data[i].goods_name;
          turnName.push(name);

          //id
          var id = res.data.data[i].id;
          chouId.push(id);


        }
        that.setData({
          image: imgText,
          probabi: probabi,
          turnName: turnName,
          chouId: chouId
        })
        console.log(res.data);
      },
      complete: function () {
        //圆点设置
        var leftCircle = 7.5;
        var topCircle = 7.5;
        var circleList = [];
        for (var i = 0; i < 24; i++) {
          if (i == 0) {
            topCircle = 15;
            leftCircle = 15;
          } else if (i < 6) {
            topCircle = 7.5;
            leftCircle = leftCircle + 102.5;
          } else if (i == 6) {
            topCircle = 15
            leftCircle = 620;
          } else if (i < 12) {
            topCircle = topCircle + 94;
            leftCircle = 620;
          } else if (i == 12) {
            topCircle = 565;
            leftCircle = 620;
          } else if (i < 18) {
            topCircle = 570;
            leftCircle = leftCircle - 102.5;
          } else if (i == 18) {
            topCircle = 565;
            leftCircle = 15;
          } else if (i < 24) {
            topCircle = topCircle - 94;
            leftCircle = 7.5;
          } else {
            return
          }
          circleList.push({ topCircle: topCircle, leftCircle: leftCircle });
        }
        that.setData({
          circleList: circleList
        })
        //圆点闪烁
        setInterval(function () {
          if (_this.data.colorCircleFirst == '#FFDF2F') {
            _this.setData({
              colorCircleFirst: '#FE4D32',
              colorCircleSecond: '#FFDF2F',
            })
          } else {
            _this.setData({
              colorCircleFirst: '#FFDF2F',
              colorCircleSecond: '#FE4D32',
            })
          }
        }, 500)
        //奖品item设置
        var awardList = [];
        //间距,怎么顺眼怎么设置吧.
        var topAward = 25;
        var leftAward = 25;
        for (var j = 0; j < 8; j++) {
          if (j == 0) {
            topAward = 25;
            leftAward = 25;
          } else if (j < 3) {
            topAward = topAward;
            //166.6666是宽.15是间距.下同
            leftAward = leftAward + 166.6666 + 15;
          } else if (j < 5) {
            leftAward = leftAward;
            //150是高,15是间距,下同
            topAward = topAward + 150 + 15;
          } else if (j < 7) {
            leftAward = leftAward - 166.6666 - 15;
            topAward = topAward;
          } else if (j < 8) {
            leftAward = leftAward;
            topAward = topAward - 150 - 15;
          }

          var imageAward = that.data.image[j];
          awardList.push({ topAward: topAward, leftAward: leftAward, imageAward: imageAward });


        }

        that.setData({
          awardList: awardList
        })
      }
    })

    //需要消耗积分
    wx.request({
      url: 'https://jisu.shenmikj.com/mall_case/black_gb/mall_mchs/Game/wheel_config',
      data: {},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      success: function (res) {
        var acc = res.data.data.int
        _this.setData({
          acc: acc
        })
      }
    })


  },
  //开始游戏
  startGame: function () {
    if (this.data.isRunning) return
    this.setData({
      isRunning: true,
      indexSelect: -1,
    })
    var _this = this;
    var that = this;
    var user_id = wx.getStorageSync('openid');
    wx.request({
      url: app.globalData.hostadmin + 'Game/wheel_start',
      data: {
        user_id: user_id
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      success: function (res) {
        if (res.data.status == -1) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            success: function () {
              _this.setData({
                isRunning: false
              })
            }
          })
          return false;
        } else {
          var ProArray = that.data.probabi;
          var sortArray = JSON.parse(JSON.stringify(ProArray));
          var randomIndex = random(sortArray);
          _this.setData({
            randomIndex: randomIndex
          })
          console.log(randomIndex,'randomIndex');
          var i = 0;
          var canId = that.data.chouId;
          var cishu = that.data.turnName;
          var gailv = that.data.probabi;
          var address = that.data.address;
          var info = that.data.info;
          var gid;
          var indexSelect = that.data.indexSelect;
          // console.log(gailv[indexSelect] + "这是if外面的概率")
          var timer = setInterval(function () {
            indexSelect++;
            //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
            i += 40;
            indexSelect = indexSelect % 8;
            _this.setData({
              indexSelect: indexSelect
            })
            if (i > 1000 && (indexSelect == randomIndex) ) {
              //去除循环
              clearInterval(timer)
              //获奖提示
              wx.showModal({
                title: '恭喜您',
                content: '获得' + (cishu[randomIndex]),
                confirmText: '选择地址',
                success: function (res) {
                  _this.setData({
                    isRunning: false
                  })
                  if (res.confirm) {
                    wx.chooseAddress({
                      success: function(chooseRes) {
                        console.log(chooseRes);
                        var name = chooseRes.userName;
                        var address = chooseRes.provinceName + chooseRes.cityName + chooseRes.countyName + chooseRes.detailInfo;
                        var mobile = chooseRes.telNumber;
                        console.log(name, address, mobile,'name, address,mobile');
                        wx.request({
                        url: app.globalData.hostadmin + 'Game/wheel_add_record',
                        data: {
                          user_id: user_id,
                          bw_goods_id: canId[randomIndex],
                          name: name,
                          address: address,
                          mobile: mobile,
                        },
                        header: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                        },
                        method: 'POST',
                        success: function (res) {
                          if (res.data.status == -1) {
                            wx.showToast({
                              title: res.data.msg,
                            })
                          }
                        }
                       })
                      },
                      fail: function (chooseRes) {},
                      complete: function (chooseRes) {},
                    })
                    // wx.request({
                    //   url: app.globalData.hostadmin + 'Game/wheel_add_record',
                    //   data: {
                    //     user_id: user_id,
                    //     bw_goods_id: canId[randomIndex],
                    //     // name: info.contact,
                    //     // address: address,
                    //     // mobile: info.mobile,
                    //   },
                    //   header: {
                    //     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                    //   },
                    //   method: 'POST',
                    //   success: function (res) {
                    //     if (res.data.status == -1) {
                    //       wx.showToast({
                    //         title: res.data.msg,
                    //       })
                    //     }
                    //   }
                    // })
                  }
                }
              })
            }

          }, (_this.data.times * 1 + i))
        }

      }
    })

  },
  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    return {
      // title: '',
      path: '/pages/index/index?share=' + wx.getStorageSync('openid'),
      success: function (res) {
        //转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})

function random(randomArray) {
  var length = randomArray.length, a = 0, b = parseFloat(randomArray[length - 1]);
  if (length >= 2) {
    for (var i = 0; i < length - 1; i++) { a += parseFloat(randomArray[i]); }
    a = parseFloat(a / (a + b)), b = 1 - a;
    var randomNum = Math.random();
    if ((b < 0.5 && randomNum < b) || (b >= 0.5 && randomNum >= a)) {
      // selectedName = prizeGoods[length - 1];
      var selectedIndex = length - 1;
      return selectedIndex;
    } else {
      randomArray.length = length - 1;
      return random(randomArray);
    }
  } else {
    // selectedName = prizeGoods[length - 1];
    var selectedIndex = length - 1;
    return selectedIndex;
  }
}