var app = getApp()
import Scratch from "../../../utils/scratch/scratch.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow: true,
    currentTab: 1,
    isStart: true,
    txt: "开始刮奖",
    awards: [],
    // img: "https://jisu.shenmikj.com/painter/Uploads/image_manage/20171127/5a1b762701f39.png",
    prizename: [],
    prizedata: [],
    indexSelect: "",
    indexOn: '',
    yinc: 0,
    carousel: [],
    user_id: '',
    gl: [],


    animationData: {},
    showhide: '0',
    showimgaes: '../../../images/egg_1.png',
    switchs: 0,
    reward: '',
    prizegroup: [
      //{
      //id: 0, //奖品id
      //name: '一等奖', //奖品名称
      //pro: "0.3%", //0~1之间如为小数，那么保持在小数点后面三位，如是百分数，那么保持百分数小数点后一位小数，
      //order: 1, //中奖次序，相同概率时以中奖次序判断，小前大后，正整数
      //}
    ],
    eggacc: '',  //蛋消耗积分
    egginter: '',  //判断积分够不够砸金蛋
    eggId: '',  //奖品id
  },

  swichNav: function (e) {
    var current = e.currentTarget.dataset.current
    this.setData({
      currentTab: current
    })
  },
  //轮播预览
  fangImage: function (e) {
    var current = e.currentTarget.dataset.images;
    var movimg = [];
    for (var i = 0; i < this.data.movies.length; i++) {
      movimg.push(this.data.movies[i].image_url);
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: movimg // 需要预览的图片http链接列表  
    })
  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      currentTab: options.kind == undefined ? 1 : options.kind == 'card' ? 1 : 2,
    })
    var award_img;
    //刮刮乐需要积分
    wx.request({
      url: app.globalData.hostadmin + 'Game/card_config',
      data: {},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      success: function (res) {
        var acc = res.data.data.int
        that.setData({
          awards: acc
        })
      }
    })

    //砸金蛋需要积分
    wx.request({
      url: app.globalData.hostadmin + 'Game/eggs_config',
      data: {},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      success: function (res) {
        that.setData({
          eggacc: res.data.data.int
        })
      }
    })

    //获取user_id
    // wx.request({
    //   url: app.globalData.hostadmin + '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
    //     that.setData({
    //       user_id: user_id
    //     })
        var user_id = wx.getStorageSync('openid');
        //获取刮刮卡奖品
        wx.request({
          url: app.globalData.hostadmin + 'Game/card_index',
          data: {
            user_id: user_id
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
          },
          method: 'POST',
          success: function (res) {
            console.log(res.data, '刮刮卡');
            var prize = [];
            var gl = [];
            for (var i = 0; i < res.data.data.length; i++) {
              prize.push(res.data.data[i].goods_name);
              gl.push(res.data.data[i].probability);
            }
            that.setData({
              prizename: prize,
              carousel: res.data.data,
              gl: gl
            })
            that.setData({
              yinc: false,
            })
            setTimeout(function () {
              that.get_new()
            }, 1000)
          }
        })

        //砸金蛋奖品
        wx.request({
          url: app.globalData.hostadmin + 'Game/eggs_index',
          data: {
            user_id: user_id
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
          },
          method: 'POST',
          success: function (res) {
            console.log(res.data, '砸金蛋');
            that.setData({
              prizegroup: res.data.data,
            })
          }
        })
    //   },
    // })

    //获取个人信息
    // wx.request({
    //   url: app.globalData.hostadmin + '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
    //       that.setData({
    //         info: oData,
    //         address: oText,
    //         address_id: address_id
    //       })
    //     } else {
    //       that.setData({
    //         address: '',
    //         info: res.data.result
    //       })
    //     }
    //   },
    // })
  },

  //刮刮乐
  onStart: function () {
    var user_id = wx.getStorageSync('openid');
    var that = this;
    wx.request({
      url: app.globalData.hostadmin + 'Game/card_start',
      data: {
        user_id: user_id
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      success: function (res) {
        console.log(res);
        if (res.data.status == -1) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            success: function () {
              that.setData({
                isRunning: false
              })
            }
          })
          return false;
        } else {
          var indexSelect = that.data.indexSelect;
          let isStart = that.data.isStart
          if (isStart) {
            that.setData({
              txt: "再刮一次",
              isStart: false,
              indexSelect: indexSelect,
              yinc: 1
            })
            that.scratch.start()
          } else {
            that.scratch.restart()
            that.setData({
              yinc: 1
            })
          }
        }

      }
    })
  },

  get_new: function () {
    var that = this;
    that.setData({
      yinc: false
    })
    var ProArray = that.data.gl;
    console.log(ProArray + "这是数组的概率")
    //随机数
    var ranNumber = Math.random() * 100000;
    var jieguo = ranNumber / 100000;

    var result = [];
    var rep = [];
    var indexSelect = 0;
    for (var i = 0; i < ProArray.length; i++) {
      if (jieguo < ProArray[i]) {
        result.push(ProArray[i]);
        rep.push(i);
      }
    }
    if (result.length == 0) {
      var maxres = ProArray[0];
      for (var i = 0; i < ProArray.length; i++) {
        if (maxres < ProArray[i]) {
          maxres = ProArray[i]
        }
      }
      for (var i = 0; i < ProArray.length; i++) {
        if (maxres == ProArray[i]) {
          indexSelect = i
        }
      }
    } else {
      var maxres = result[0];
      for (var i = 0; i < result.length; i++) {
        if (maxres > result[i]) {
          maxres = result[i]
        }
      }
      for (var i = 0; i < result.length; i++) {
        if (maxres == result[i]) {
          indexSelect = i
        }
      }
      for (var i = 0; i < rep.length; i++) {
        if (indexSelect == i) {
          indexSelect = rep[i]
        }
      }
    }
    that.setData({
      indexOn: indexSelect,
    })

    //刮刮乐
    that.scratch = new Scratch(that, {
      canvasWidth: 220,
      canvasHeight: 100,
      maskColor: "#C5C5C6",
      r: 15,
      awardTxt: that.data.prizename[that.data.indexOn],
      awardTxtColor: "#3985ff",
      awardTxtFontSize: "24px",
      callback: function () {
        var info = that.data.info
        var goods_id = that.data.indexOn + 1
        wx.showModal({
          title: '提示',
          content: "恭喜您获得：" + that.data.prizename[that.data.indexOn],
          showCancel: false,
          success: function (res) {
            that.scratch.reset()
            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/card_add_record',
                    data: {
                      user_id: wx.getStorageSync('openid'),
                      bw_goods_id: goods_id,
                      name: name,
                      mobile: mobile,
                      address: address,
                    },
                    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,
                          image: '../../../images/warning.png'
                        })
                      }
                    },
                  })
                },
                fail: function (chooseRes) { },
                complete: function (chooseRes) { },
              })
              that.setData({
                yinc: false,
              })
              if (that.data.prizename[that.data.indexOn] == '谢谢参与') {
                return false;
              }
            } else if (res.cancel) {
              that.setData({
                yinc: false,
              })
            }
          }
        })
      }
    })
  },


  //砸金蛋
  animationtap: function () {
    var that = this;
    var animation = wx.createAnimation({
      timingFunction: 'ease',
    })
    this.animation = animation;
    animation.rotate(25).step({
      duration: 200
    })
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.rotate(-40).step({
        duration: 150
      })
      this.setData({
        animationData: animation.export()
      })
      setTimeout(function () {
        that.setData({
          showimgaes: "../../../images/egg_2.png",
        })
      }.bind(this), 150)
      setTimeout(function () {
        this.probability();
      }.bind(this), 250)

    }.bind(this), 200)
  },
  zaeggtap: function (e) {
    var that = this
    //判断积分够不够
    wx.request({
      url: app.globalData.hostadmin + 'Game/eggs_start',
      data: {
        user_id: wx.getStorageSync('openid'),
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        if (res.data.status == -1) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
          })
          return false;
        }
        // if (res.data.status == 1) {
        //     wx.showModal({
        //         title: '提示',
        //         content: res.data.msg,
        //     })
        // }
        if (that.data.switchs == "1") {
          return
        }
        var type = e.currentTarget.dataset.type;
        that.setData({
          showimgaes: "../../../images/egg_1.png",
          showhide: type,
          switchs: "1",
        })
        that.animationtap()
      }
    })
  },

  //如果不是谢谢参与 跳订单
  egg_go: function () {
    var that = this;
    if (that.data.reward == "谢谢参与") {
      that.setData({
        reward: '',
        switchs: "0",
      })
    } else {
      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/eggs_add_record',
            data: {
              user_id: wx.getStorageSync('openid'),
              bw_goods_id: that.data.eggId,
              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,
                  image: '../../../images/warning.png'
                })
              } else {
                that.setData({
                  reward: '',
                })
              }
            }
          })
        },
        fail: function (chooseRes) { },
        complete: function (chooseRes) { },
      })
    }
    that.setData({
      showimgaes: "../../../images/egg_1.png",
      showhide: "0"
    })
  },

  //砸金蛋概率
  probability: function () {
    var decimal = Math.random() + "";
    decimal = decimal.substring(0, 5);
    decimal = decimal * 1;
    if (decimal == 0) {
      decimal = 0.001
    }
    var arrayset2 = [];
    var arrayvalue2 = parseInt(Math.random() * 10);
    for (var i = 0; i < 10; i++) {
      var arraynum = parseInt(Math.random() * 10);
      arrayset2.push(arraynum);
    }
    var tsn2 = 0;
    for (var i = 0; i < arrayset2.length; i++) {
      if (arrayvalue2 == arrayset2[i]) {
        tsn2++;
      }
    }
    var arrayset_2 = [];
    for (var i = 0; i < 9; i++) {
      var arraynum = parseInt(Math.random() * 10);
      arrayset_2.push(arraynum);
    }
    var tsn_2 = "";
    var tsnum_2 = 0;
    for (var i = 0; i < arrayset_2.length; i++) {
      var tsn_name = arrayset_2[i];
      var tsnum = 0;
      for (var j = 0; j < arrayset_2.length; j++) {
        if (arrayset_2[i] == arrayset_2[j]) {
          if (tsn_name != tsn_2) {
            tsnum++
          }
        }
      }
      if (tsnum_2 * 1 < tsnum * 1) {
        tsn_2 = tsn_name;
        tsnum_2 = tsnum;
      }
    }
    var lucky = parseInt(Math.random() * 1000) / 500;
    var sumpro = tsnum_2 / 10 * tsn2 / 10 * decimal * lucky + "";
    sumpro = sumpro.substring(0, 5) * 1;
    var resultpro = 1 - sumpro;
    resultpro = resultpro + "";
    resultpro = resultpro.substring(0, 5);
    this.promatch(resultpro)
  },
  promatch: function (e) {
    var resultpro = e;
    var prizegroup = this.data.prizegroup;
    var prizegroups = [];
    for (var i = 0; i < prizegroup.length; i++) {
      var escape = prizegroup[i].probability + "";
      if (escape.indexOf("%") != -1) {
        var num = escape.split("%")[0] * 1;
        num = num / 100 + "";
        num = num.substring(0, 5) * 1;
        prizegroup[i].probability = num
        prizegroups.push(prizegroup[i])
      } else {
        prizegroups.push(prizegroup[i])
      }
    }
    var prizegroupes = [];
    for (var i = 0; i < prizegroups.length; i++) {
      var state = 0;
      for (var j = 0; j < prizegroupes.length; j++) {
        if (prizegroups[i].probability * 1 > prizegroupes[j].probability * 1) {
          prizegroupes.splice(j, 0, prizegroups[i]);
          state = 1;
          break;
        }
      }
      if (state == 0) {
        prizegroupes.push(prizegroups[i]);
      }
    }
    var retultid = "";
    var retultname = "";
    for (var i = 0; i < prizegroupes.length; i++) {
      if (prizegroupes[i].probability * 1 < resultpro) {
        if (i == 0) {
          retultid = prizegroupes[i].id;
          retultname = prizegroupes[i].goods_name;
        } else {
          retultid = prizegroupes[i - 1].id;
          retultname = prizegroupes[i].goods_name;
        }
        break;
      }
    }
    this.setData({
      reward: retultname,
      eggId: retultid,
    })
  },

  //砸金蛋须知
  xuzhi: function () {
    wx.showModal({
      title: '提示',
      content: '1、砸金蛋每次消耗' + this.data.eggacc + '积分。2、积分可通过推客分享获得。',
    })
  },

  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    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;
  }
}
