// pages/luckydraw/luckydraw.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    circleList: [],//圆点数组
    awardList: [],//奖品数组

    colorAwardDefault: '#F5F0FC',//奖品默认颜色
    colorAwardSelect: '#ffe400',//奖品选中颜色
    indexSelect: 0,//被选中的奖品index
    isRunning: false,//是否正在抽奖
    times: '70',//转盘转动的速度

    lottery_integral: '',//抽奖所需积分
    image: [],//奖品图片
    turnName: [],//奖品名称
    chouId: [],
    user_integral: '',//用户积分
    name:'',//姓名
    phone:'',//手机号
    region: ['广东省','广州市','海珠区'],
    xxdz:'',
    showbiaodan:'',//表单
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that =this;
    wx.showLoading({
      title: '加载中',
    })
    var u_openid = options.u_openid;
    app.getUserInfo(function (cb, userInfo) {
      that.setData({
        userInfo: userInfo,
      })
    }, u_openid)
    //  大转盘奖品列表
    wx.request({
      url: app.globalData.hostname + '/BigWheel/index',
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      data: {
        business_id: app.globalData.business_id,
      },
      success: function (res) {
        console.log(res);
        var imgText = []; //奖品图片数组
        var turnName = []; //奖品名称数组
        var chouId = []; //奖品id数组

        for (var i = 0; i < res.data.data.length; i++) {
          //奖品图
          var img = res.data.data[i].img;
          imgText.push(img);
          //奖品名称
          var name = res.data.data[i].goods_name;
          turnName.push(name);
          //奖品id
          var id = res.data.data[i].id;
          chouId.push(id);

        }
        that.setData({
          lottery_integral: res.data.lottery_integral,//抽奖所需积分
          image: imgText,//奖品图片数组
          turnName: turnName,//奖品名称数组
          chouId: chouId//奖品id数组
        })

      },
      fail: function (res) { },
      complete: function (res) {
        wx.hideLoading()
        //圆点设置
        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 (that.data.colorCircleFirst == '#FFDF2F') {
            that.setData({
              colorCircleFirst: '#FE4D32',
              colorCircleSecond: '#FFDF2F',
            })
          } else {
            that.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
        })

      }
    })

  },

  //中奖纪录
  get_record: function () {
    var zhuanpanurl ="BigWheel/winning_log"
    wx.navigateTo({
      url: '../record/record?zhuanpanurl=' + zhuanpanurl,
    })
  },

  //开始游戏
  startGame: function () {
    if (this.data.isRunning) return
    this.setData({
      isRunning: true
    })
    var _this = this;
    console.log("测试")
    //开始游戏先扣除积分
    wx.request({
      url: app.globalData.hostname + 'BigWheel/config',
      dataType: "json",
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: "POST",
      data: {
        business_id: app.globalData.business_id,
      },
      success: function (res) {
        console.log(res,"积分")
        
        // 获取我的积分
        let jifen;
        // wx.getStorage({
        //   key: 'jifen',
        //   success: function(res) {
        //     jifen = res.data
        //   },
        // })
        wx.request({
          url: app.globalData.hostname + 'Int/get_my_int',
          method: 'POST',
          header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
          data: {
            openid: wx.getStorageSync('openId'), business_id: app.globalData.business_id
          },
          success: function (res) {
            jifen = res.data.data
          }
        })
        _this.setData({
          user_integral: jifen,
          lottery_integral:res.data.data.int
        })
        console.log(res.data.data.int,"积分")
        if (jifen < res.data.data.int) {
          wx.showModal({
            title: '提示',
            content: '积分不足!',
            success: function () {
              _this.setData({
                isRunning: false
              })
            }
          })
          return false;
        } else {

          var indexSelect = 0
          var i = 0;
          var timer = setInterval(function () {
            indexSelect++;
            //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
            i += 30;
            if (i > 850) {
              //去除循环
              _this.setData({
                indexSelect: -1
              })
              clearInterval(timer)
            //  抽奖开始接口
              wx.request({
                url: app.globalData.hostname + 'BigWheel/start',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                method: "POST",
                data: {
                  business_id: app.globalData.business_id,
                  user_id: wx.getStorageSync('users_id')
                },
                success: function (res) {
                  console.log(res);
                  _this.setData({
                    indexSelect: -1
                  })
                  console.log("奖品",res)
                  var status = res.data.prize_res.status
                  var prize_id = res.data.prize_res.id
                  var prize_name = res.data.prize_res.prize
                  //获奖提示
                  if (status == 1) {
                    wx.showModal({
                      title: '恭喜您',
                      content: '获得' + '[' + (prize_name) + ']',
                      showCancel: false,//去掉取消按钮
                      success: function (res) {
                        _this .setData({
                          showbiaodan:1,
                          prize_id: prize_id,
                            isRunning: false
                        })
                        // 设置获取位置
                        wx.chooseAddress({
                          success:function(res){
                            _this.setData({
                              name: res.userName,
                              phone:res.telNumber,
                              region: [res.provinceName, res.cityName, res.countyName,],
                              xxdz: res.detailInfo
                            })
                          }
                        })
                      }
                    })
                  } else if(status== -1){
                    wx.showModal({
                      title: '提示',
                      content: '你本次没抽中,谢谢参与!',
                      showCancel: false,//去掉取消按钮
                      success:function(){
                        _this.setData({
                          isRunning:false,
                        })
                      }
                    })
                  }else{
                    wx.showModal({
                      title: '提示',
                      content: '抽奖失败',
                      showCancel: false,//去掉取消按钮
                    })
                  } 
                },
              })
            }
            indexSelect = indexSelect % 8;
            _this.setData({
              indexSelect: indexSelect
            })
          }, (_this.data.times * 1 + i))
        }
      },
    })
  },

  // 姓名监听
  name:function(e){
    var that =this;
    that.setData({
      name:e.detail.value,
    })
  },
  // 手机号
  phone:function(e){
    var that =this;
    that.setData({
      phone:e.detail.value
    })
  },
  // 地址
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  // 详细地址
  xxdz:function(e){
    var that = this;
    that.setData({
      xxdz: e.detail.value
    })
  },
  // 收货人表单提交
  ok:function(){
    var that =this;
    if(that.data.name.length==0){
      wx.showModal({
        title: '提示',
        content: '请填写姓名',
        showCancel:false,
      })
    } else if (that.data.phone.length == 0){
      wx.showModal({
        title: '提示',
        content: '请填写手机号',
        showCancel: false,
      })
    } else if (!((/^1[3|4|5|8][0-9]\d{4,8}$/.test(that.data.phone)) || (/^0\d{2,3}-?\d{7,8}$/).test(that.data.phone))){
      wx.showModal({
        title: '提示',
        content: '手机号格式错误',
        showCancel: false,
      })
    } else if (that.data.region.length==0) {
      wx.showModal({
        title: '提示',
        content: '请选择地址',
        showCancel: false,
      })
    } else if (that.data.xxdz.length == 0) {
      wx.showModal({
        title: '提示',
        content: '请填写详细地址',
        showCancel: false,
      })
    }else{
      // 提交接口
      wx.request({
        url: app.globalData.hostname + '/BigWheel/add_record',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          business_id: app.globalData.business_id,
          user_id: wx.getStorageSync('users_id'),
          name:that.data.name,
          bw_goods_id: that.data.prize_id,
          mobile:that.data.phone,
          address: that.data.region + that.data.xxdz
        },
        success: function (res) {
          if (res.data.status == 1) {
            wx.showToast({
              title: '提交成功!',
            })
            that.setData({
              showbiaodan: ''
            })
  
          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (res) {
    var userid = wx.getStorageSync('openId')
    // var userid = 1

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: app.globalData.share_title,
      path: '/pages/index/index?u_openid=' + userid,
      success: function (res) {
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length - 1]    //获取当前页面的对象
        //点击分享传进userid 截取userid 从onload拿到
        var url = currentPage.route + '?u_openid=' + userid;  //当前页面url
        console.log(url, '/pages/index/index?u_openid=' + userid);
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
})