var util = require("../../../../utils/util.js");
var WxParse = require('../../../../utils/wxParse/wxParse.js');
const app = getApp();
let imghost = app.globalData.setting.imghost;
let self = null;
let imgDraw = {
  "width": "554px",
  "height": "899px",
  "background": imghost + "miniapp/images/share_bg.png",
  "views": [
    { //0.头像
      "type": "image",
      // "url": app.globalData.userInfo.head_pic,
      "css": {
        "background": "white",
        "width": "80px",
        "height": "80px",
        "top": "24px",
        "left": "40px",
        "borderRadius": "80px",
      }
    },
    { //1.昵称
      "type": "text",
      // "text": "",
      "css": {
        "color": "#000000",
        "width": "400px",
        "top": "25px",
        "left": "140px",
        "fontSize": "26px",
        "maxLines": "1",
      }
    },
    { //2.强烈推荐
      "type": "text",
      "text": "强烈推荐",
      "css": {
        "color": "#fff",
        "background": "#FF6768",
        "width": "105px",
        "height": "26px",
        "lineHeight": "26px",
        "top": "70px",
        "left": "140px",
        "borderRadius": "10px",
        "fontSize": "18px",
        "textAlign": "center"

      }
    },
    { //3.分享标题
      "type": "text",
      "text": "",
      "css": {
        "width": "554px",
        "padding": "20px",
        "left": "20px",
        "top": "160px",
        "fontSize": "28px",
        "textAlign": "left",
        "maxLines": "1",
      }
    },
    { //4.分享内容
      "type": "text",
      // "text": "",
      "css": {
        "color": "#000000",
        "width": "554px",
        "padding": "20px",
        "left": "20px",
        "top": "190px",
        "fontSize": "26px",
        "textAlign": "center",
        "maxLines": "1",
      }
    },
    { //5.分享图片
      "type": "image",
      "url": "/packageB/images/luckDraw/jiang.png",
      "css": {
        "width": "auto",
        "height": "380px",
        "top": "220px",
        "left": "277px",
        "align": "center",
        "mode": "aspectFill",
      }
    },
    { //6
      "type": "image",
      "url": "/images/share/s_gou.png",
      "css": {
        "width": "30px",
        "height": "30px",
        "top": "630px",
        "left": "18px",
        "rotate": "0",
        "borderRadius": "30px",
      }
    },
    {	//7
      "type": "text",
      "text": "正品保障",
      "css": {
        "color": "red",
        "width": "110px",
        "top": "630px",
        "left": "52px",
        "fontSize": "22px",
      }
    },
    {	//8
      "type": "image",
      "url": "/images/share/s_gou.png",
      "css": {
        "width": "30px",
        "height": "30px",
        "top": "630px",
        "left": "208px",
        "borderRadius": "30px",
      }
    },
    {	//9
      "type": "text",
      "text": "纯实体店",
      "css": {
        "color": "red",
        "width": "129px",
        "top": "630px",
        "left": "243px",
        "fontSize": "22px",
      }
    },
    {	//10
      "type": "image",
      "url": "/images/share/s_gou.png",
      "css": {
        "width": "30px",
        "height": "30px",
        "top": "630px",
        "left": "410px",
        "borderRadius": "30px",
      }
    },
    {	//11
      "type": "text",
      "text": "官方验证",
      "css": {
        "color": "red",
        "width": "121px",
        "top": "630px",
        "left": "450px",
        "fontSize": "22px",
      }
    },
    { //12.横线
      "type": "rect",
      "css": {
        "color": "#eee",
        "width": "548px",
        "height": "1px",
        "top": "676px",
        "left": "277px",
        "align": "center",
      }
    },
    {	//13
      "type": "text",
      "text": "特惠活动时间仅限",
      "css": {
        "color": "#000000",
        "width": "245px",
        "top": "730px",
        "left": "28px",
        "fontSize": "24px",
        "textAlign": "left"
      }
    },
    { //14.时间
      "type": "text",
      // "text": "",
      "css": {
        "width": "377px",
        "top": "770px",
        "left": "28px",
        "fontSize": "24px",
      }
    },
    {	//15
      "type": "text",
      "text": "长按识别小程序码有惊喜哦！",
      "css": {
        "color": "#7c7c7c",
        "width": "348px",
        "top": "820px",
        "left": "27px",
        "fontSize": "24px",
      }
    },

    {	//16.码
      "type": "image",
      // "url": "",
      "css": {
        "width": "150px",
        "height": "150px",
        "top": "715px",
        "left": "380px",
        "mode": "scaleToFill"
      }
    },

  ]
};


Page({
  data: {
    imgDraw: imgDraw,

    start: false,
    list: null,
    isLoading: false, // 检测是否已经发送请求,防止重复发送请求
    noMore: false, // 检测是否有更多数据,true为没有更多数据,false为还有数据
    pageNum: 1, // 当前页数
    imghost: imghost,
    num: 3,
    canStart: false,
    // store:1,
    prizes: [],
    defaultConfig: {
      offsetDegree: 22.5,
    },
    // defaultStyle: {
    //   fontColor: '#d64737',
    //   fontSize: '14px'
    // },
    blocks: [{
      padding: '76rpx',
      imgs: [{
        src: imghost + 'miniapp/images/luckDraw/weel.png?v=3',
        width: '700rpx',
        height: '700rpx',
        rotate: true,
      }],
    }],
    buttons: [{
      radius: '60rpx',
      imgs: [{
        src: imghost + 'miniapp/images/luckDraw/pointer.png?v=3',
        width: '188rpx',
        height: '230rpx',
        top: '-130rpx',
      }],
    }],
  },

  onLoad(options) {
    self = this;
    let first_leader = null;
    this.data.options = options;

    wx.setNavigationBarTitle({
      title: options.title,
    });
    this.setData({l_title:options.title})

    app.isLogin().then(function (data) {//进入页面前已经授权登录成功
      self.setData({
        userInfo: data,
      });
    });



    //从分享的跳转过来
    if (options.id == undefined || options.id == null || options.id == '') {
      var scene = decodeURIComponent(options.scene);
      scene = scene.split('_');
      first_leader = scene[0];
      this.data.options.id = scene[1];
    };

    if (first_leader) {
      // console.log("log---", first_leader);				
      app.globalData.first_leader = first_leader;
      //调用接口判断是不是会员
      app.request.promiseGet("/api/weshop/shoppingGuide/get/" + app.globalData.setting.stoid + "/" + first_leader, {}).then(res => {
        if (res.data.code == 0) {
          app.globalData.guide_id = res.data.data.id;
        }
      })
    };

  },

  onShow() {
    // console.log('show~~`');

    if (app.globalData.userInfo) {
      if (!this.data.isLogin) {

        // 下载头像
        let path = app.globalData.userInfo.head_pic;
        path = path.replace("http://thirdwx.qlogo.cn", "https://wx.qlogo.cn");
        path = path.replace("https://thirdwx.qlogo.cn", "https://wx.qlogo.cn");
        wx.downloadFile({
          url: path, //仅为示例，并非真实的资源
          success(res) {
            // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
            if (res.statusCode === 200) {
              self.setData({
                'imgDraw.views[0].url': res.tempFilePath,//头像
              });

            }
          }
        });


        this.setData({
          userInfo: app.globalData.userInfo,
          isLogin: true,
          'imgDraw.views[1].text': app.globalData.userInfo.nickname,//昵称
        });


        // console.log('imgDraw.views[1].text+++++++++', imgDraw.views[1], app.globalData.userInfo.nickname);
        let user_id = app.globalData.userInfo.user_id;
        let store_id = app.globalData.setting.stoid;
        let id = this.data.options.id;
        let url = `/api/weshop/marketing/marketingLuckForm/getLuckInfo/${store_id}/${id}/${user_id}`;

        //获取小程序码
        this.getMiniCode({
          url: app.globalData.setting.url,
          store_id: app.globalData.setting.stoid,
          user_id: app.globalData.userInfo.user_id,
          id: this.data.options.id,
        });


        app.request.get(url, {
          success: function (res) {
            if (res.data.code == 0) {
              self.setData({
                luckInfo: res.data.data,
              });
              WxParse.wxParse('content', 'html', self.data.luckInfo.remark, self);

              // 如果is_share为1,隐藏发送给朋友和分享到朋友圈功能
              if (!self.data.luckInfo.is_share) {
                wx.hideShareMenu();
              };

            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
              });
              self.data.msg = res.data.msg;
              // self.setData({
              // 	bannerUrl: imghost + 'miniapp/images/luckDraw/bg.png?v=2',
              // 	'blocks[0].imgs[0].src': imghost + 'miniapp/images/luckDraw/weel.png?v=3', //转盘
              // 	'buttons[0].imgs[0].src': imghost + 'miniapp/images/luckDraw/pointer.png?v=3', //指针
              // });

            };

            // console.log('luckInfo', res.data.data);
            let luckInfo = res.data.data;



            self.setData({
              'imgDraw.views[3].text': self.data.luckInfo.act_name,//分享标题
              // 'imgDraw.views[4].text': '快来一起抽奖吧，精美奖品等着你！',//分享内容
              'imgDraw.views[14].text': util.formar_no_full(luckInfo.begindate) + ' 至 ' + util.formar_no_full(luckInfo.enddate),//活动时间
            });



            let luckStyle = null;


            if (luckInfo && luckInfo.template_type != null && luckInfo.template_type == 1) { //获取模板
              let url = `/api/weshop/marketing/marketingLuckTemplate/get/0/${luckInfo.template_id}`;
              app.request.get(url, {
                success: function (res) {
                  let template = null;
                  if (res.data.code == 0) {
                    template = res.data.data;
                    self.setData({
                      template,
                      bannerUrl: imghost + template.bannerUrl, //背景图
                      'blocks[0].imgs[0].src': imghost + ((template && template.wheelBaseUrl) ? template.wheelBaseUrl : 'miniapp/images/luckDraw/weel.png?v=3'),
                      'buttons[0].imgs[0].src': imghost + ((template && template.wheelPointerUrl) ? template.wheelPointerUrl : 'miniapp/images/luckDraw/pointer.png?v=3'), //指针
                      'imgDraw.views[3].text': template.share_title ? template.share_title : self.data.luckInfo.act_name, //分享标题
                      'imgDraw.views[5].url': imghost + (template && template.share_image ? template.share_image : self.data.luckInfo.imageurl), //分享图片

                    });

                    let color = template && template.colorCode ? template.colorCode : '#da104b';
                    luckStyle = `background: ${color} url(${self.data.bannerUrl}) no-repeat;`;
                    self.setData({
                      luckStyle,

                    });
                    // self.setData({
                    // 	template: res.data.data,
                    // 	bannerUrl: imghost + res.data.data.bannerUrl, //背景图
                    // 	//bannerUrl: imghost + ((res.data.data&&res.data.data.bannerUrl) ? res.data.data.bannerUrl:'miniapp/images/luckDraw/bg.png?v=2'), //背景图
                    // 	'blocks[0].imgs[0].src': imghost + res.data.data&&res.data.data.wheelBaseUrl) ? res.data.data.wheelBaseUrl:'miniapp/images/luckDraw/weel.png?v=2'), //转盘
                    // 	'buttons[0].imgs[0].src': imghost + ((res.data.data&&res.data.data.wheelPointerUrl) ? res.data.data.wheelPointerUrl:'miniapp/images/luckDraw/pointer.png?v=2'), //指针
                    // 	'imgDraw.views[3].text': (res.data.data&&res.data.data.title) ? res.data.data.title : self.data.luckInfo.act_name,//分享标题
                    // 	// 'imgDraw.views[4].text': (res.data.data&&res.data.data.share_content) ? res.data.data.share_content : '快来一起抽奖吧，精美奖品等着你！',//分享内容
                    // 	'imgDraw.views[5].url': (res.data.data&&res.data.data.share_image) ? (imghost + res.data.data.share_image):(self.data.luckInfo.imageurl ? (imghost + self.data.luckInfo.imageurl):'/packpageB/images/luckDraw/jiang.png'),//分享图片
                    // 	'imgDraw.views[14].text': util.formar_no_full(self.data.luckInfo.begindate) + ' 至 ' + util.formar_no_full(self.data.luckInfo.enddate),//活动时间
                    // });
                  } else {
                    luckStyle = `background: #da104b url(${imghost + 'miniapp/images/luckDraw/bg.png?v=2'}) no-repeat;`;
                    self.setData({
                      luckStyle,
                      'imgDraw.views[5].url': self.data.luckInfo.imageurl ? (imghost + self.data.luckInfo.imageurl) : '/packageB/images/luckDraw/jiang.png', //分享图片
                      'blocks[0].imgs[0].src': imghost + 'miniapp/images/luckDraw/weel.png?v=3', //转盘
                      'buttons[0].imgs[0].src': imghost + 'miniapp/images/luckDraw/pointer.png?v=3', //指针
                    });
                    // let color = template&&template.colorCode ? template.colorCode:'#da104b';

                    // self.setData({
                    // 	luckStyle,
                    // });
                  };

                },
              });
            } else {

              if (luckInfo && luckInfo.imageurl) {
                self.setData({
                  'imgDraw.views[5].url': imghost + self.data.luckInfo.imageurl, //分享图片
                });
              };

              if (luckInfo && luckInfo.store_bannerUrl) {
                self.setData({
                  bannerUrl: imghost + luckInfo.store_bannerUrl,
                  custom: true,
                });
              } else {
                self.setData({
                  bannerUrl: imghost + 'miniapp/images/luckDraw/bg.png?v=2',
                  custom: false,
                });
              };

              let color = self.data.custom ? '#f0f0f0' : '#da104b';
              luckStyle = `background: ${color} url(${self.data.bannerUrl}) no-repeat;`;
              self.setData({
                luckStyle,
                'blocks[0].imgs[0].src': imghost + 'miniapp/images/luckDraw/weel.png?v=3', //转盘
                'buttons[0].imgs[0].src': imghost + 'miniapp/images/luckDraw/pointer.png?v=3', //指针
              });

            };


            if (self.data.luckInfo.msgInfo) {
              wx.showToast({
                title: self.data.luckInfo.msgInfo,
                icon: 'none',
              });
            };

          },
        });

        // 获取奖品展示的奖品
        app.request.get('/api/weshop/marketing/marketingLuckList/page', {
          data: {
            store_id,
            luck_formid: id,
          },
          success: function (res) {

            let award = res.data.data.pageData;
            self.setData({
              award,
            });
            // console.log('award', award);
            self.prizeLayout(award);

          },
        });


        //获取兑奖记录
        app.request.get('/api/weshop/marketing/marketingLuckRecord/page', {
          isShowLoading: false,
          data: {
            store_id: app.globalData.setting.stoid,
            user_id: app.globalData.userInfo.user_id,
            luck_formid: this.data.options.id,
            luck_state: 1
          },
          success: function (res) {
            if (res.data.code == 0) {
              self.setData({
                record: res.data.data.pageData,
              });
            }
          },
        });


        //获取中奖人员名单
        app.request.get('/api/weshop/marketing/marketingLuckRecord/page', {
          isShowLoading: false,
          data: {
            store_id: app.globalData.setting.stoid,
            luck_formid: this.data.options.id,
            luck_state: 1,
            pageSize: 20,
          },
          success: function (res) {
            if (res.data.code == 0) {
              self.setData({
                nameList: res.data.data.pageData,
              });
            };
          },
        });




      };
    };
  },

  //获取小程序码
  getMiniCode(objData) {
    wx.getImageInfo({
      src: `${objData.url}/api/wx/open/app/user/getWeAppEwm/${objData.store_id}?sceneValue=${objData.user_id}_${objData.id}&pageValue=packageB/pages/luckactivity/luckinfo/luckinfo`,
      success(res) {
        if (res.code != -1) {
          self.setData({
            'imgDraw.views[16].url': res.path,
            getMiniCode: true,
          });
        };
      }
    });
  },

  // 设置转盘奖品布局
  prizeLayout(award) {
    let prizes = [];
    // let length = award.length;
    if (award) {
      var length = award.length;
    } else {
      wx.showToast({
        title: '请设置奖品',
        icon: 'none',
      });
      return;
    };

    let thx = { fonts: [{ text: '谢谢\n参与', top: '18%', wordWrap: false, fontColor: 'rgba(255,255,255,.6)' }] };

    if (length == 1) {
      [0, 2, 4, 6].map(function (item, index) {
        prizes[item] = {
          id: award[0].id,
          lbtype: award[0].lbtype,
          fonts: [{ text: award[0].luck_goods_name + ' x' + award[0].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[0].lbtype) ? self.prizeSrc(award[0].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [1, 3, 5, 7].map(function (item, index) {
        prizes[item] = thx;
      });

      this.data.thxIndexArr = [1, 3, 5, 7];
    };

    if (length == 2) {
      [0, 4].map(function (item, index) {
        prizes[item] = {
          id: award[0].id,
          lbtype: award[0].lbtype,
          fonts: [{ text: award[0].luck_goods_name + ' x' + award[0].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[0].lbtype) ? self.prizeSrc(award[0].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [2, 6].map(function (item, index) {
        prizes[item] = {
          id: award[1].id,
          lbtype: award[1].lbtype,
          fonts: [{ text: award[1].luck_goods_name + ' x' + award[1].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[1].lbtype) ? self.prizeSrc(award[1].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [1, 3, 5, 7].map(function (item, index) {
        prizes[item] = thx;
      });
      this.data.thxIndexArr = [1, 3, 5, 7];
    };


    if (length == 3) {
      [0, 4].map(function (item, index) {
        prizes[item] = {
          id: award[0].id,
          lbtype: award[0].lbtype,
          fonts: [{ text: award[0].luck_goods_name + ' x' + award[0].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[0].lbtype) ? self.prizeSrc(award[0].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [1, 5].map(function (item, index) {
        prizes[item] = {
          id: award[1].id,
          lbtype: award[1].lbtype,
          fonts: [{ text: award[1].luck_goods_name + ' x' + award[1].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[1].lbtype) ? self.prizeSrc(award[1].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [2, 6].map(function (item, index) {
        prizes[item] = {
          id: award[2].id,
          lbtype: award[2].lbtype,
          fonts: [{ text: award[2].luck_goods_name + ' x' + award[2].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[2].lbtype) ? self.prizeSrc(award[2].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [3, 7].map(function (item, index) {
        prizes[item] = thx;
      });

      this.data.thxIndexArr = [3, 7];
    };


    if (length == 4) {
      [0, 2, 4, 6].map(function (item, index) {
        prizes[item] = {
          id: award[index].id,
          lbtype: award[index].lbtype,
          fonts: [{ text: award[index].luck_goods_name + ' x' + award[index].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[index].lbtype) ? self.prizeSrc(award[index].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [1, 3, 5, 7].map(function (item, index) {
        prizes[item] = thx;
      });

      this.data.thxIndexArr = [1, 3, 5, 7];
    };

    if (length == 5) {
      [0, 2, 3, 5, 6].map(function (item, index) {
        prizes[item] = {
          id: award[index].id,
          lbtype: award[index].lbtype,
          fonts: [{ text: award[index].luck_goods_name + ' x' + award[index].num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(award[index].lbtype) ? self.prizeSrc(award[index].lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      [1, 4, 7].map(function (item, index) {
        prizes[item] = thx;
      });

      this.data.thxIndexArr = [1, 4, 7];
    };

    if (length == 6) {
      prizes = award.map(function (item, index) {
        return {
          id: item.id,
          lbtype: item.lbtype,
          fonts: [{ text: item.luck_goods_name + ' x' + item.num, top: '18%', wordWrap: false, fontColor: 'transparent' }],
          imgs: [
            {
              src: self.prizeSrc(item.lbtype) ? self.prizeSrc(item.lbtype) : (imghost + 'miniapp/images/luckDraw/lb.png'),
              width: '135rpx',
              height: '107rpx',
              top: '12%',
            }
          ],
        };
      });

      prizes.push(thx);
      prizes.splice(3, 0, thx);

      this.data.thxIndexArr = [3, 7];
    };

    // console.log('prizes', prizes);

    this.setData({
      prizes,
    });
  },

  // 根据lbtype指定奖品类别图标
  prizeSrc(lbtype) {
    let src = '';
    switch (lbtype) {
      case 1: { //积分
        src = imghost + 'miniapp/images/luckDraw/jf.png';
        break;
      };
      case 2: { //成长值
        src = imghost + 'miniapp/images/luckDraw/czz.png';
        break;
      };
      case 3: { //优惠券
        src = imghost + 'miniapp/images/luckDraw/yhq.png';
        break;
      };
      case 4: { //服务项目
        src = imghost + 'miniapp/images/luckDraw/fw.png';
        break;
      };
      case 5: { //赠品
        src = imghost + 'miniapp/images/luckDraw/zp.png';
        break;
      };
      case 6: { //礼包
        src = imghost + 'miniapp/images/luckDraw/lb.png';
        break;
      };
    };
    return src;
  },

  // 获取抽奖结果匹配对应奖品在奖品列表里的所有索引号
  luckyIndex(arr, target) {
    var results = [],
      len = arr.length,
      pos = 0;
    while (pos < len) {
      // pos = arr[pos].indexOf(target, pos);
      if (arr[pos].id == target) {
        results.push(pos);//找到就存储索引

      };
      pos += 1;//并从下个位置开始搜索
      // if(pos === -1){//未找到就退出循环完成搜索
      //   break;
      // };

    }
    // console.log('当前奖品列表', this.data.prizes);
    // console.log('中奖结果在当前奖品列表中的索引', results);

    return results;
  },

  start() {
    
    // self.data.start = true;
    if (this.data.start) return;
    this.data.start = true;

    if (!this.data.luckInfo) {
      wx.showToast({
        title: this.data.msg,
        icon: 'none',
      });
      return;
    };

    if (this.data.luckInfo.msgInfo) {
      wx.showToast({
        title: self.data.luckInfo.msgInfo,
        icon: 'none',
        success: function () {
          self.setData({
            start: false
          });
        }
      });
      return;
    };
    wx.showLoading({
      title: '准备开始抽奖',
      mask: true,
    });
    // 获取积分
    app.request.promisePost('/api/weshop/marketing/marketingLuckForm/startLuckIntegral', {
      isShowLoading: false,
      data: {
        storeId: app.globalData.setting.stoid,
        userId: app.globalData.userInfo.user_id,
        LuckId: this.data.options.id,
      },
    })
      .then(function (res) {
        if (res.data.code == -1) {
          //积分不足，弹出提示
          wx.hideLoading();
          self.data.luckInfo.msgInfo = res.data.msg
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            success: function () {
              self.data.start = false;
            }
          });
          return;
        };

        if (res.data.code == 0) {

          if (self.data.luckInfo.user_LuckNumDay > 0 || self.data.luckInfo.vip_act_num == 0) {
            // console.log('start choujiang');
            // let start = false;
            if (self.data.start) {
              // self.data.start = true;
              // 获取抽奖组件实例
              const $lucky = self.selectComponent('#myLucky');
              // 调用play方法开始旋转
              $lucky.play();
              wx.hideLoading();
              // 获取抽奖结果
              app.request.post('/api/weshop/marketing/marketingLuckForm/startLuck', {
                isShowLoading: false,
                data: {
                  storeId: app.globalData.setting.stoid,
                  userId: app.globalData.userInfo.user_id,
                  LuckId: self.data.options.id,
                },
                success: function (res) {

                  if (res.data.code == 0) {
                    // console.log('开始摇奖', res.data.data);
                    if (self.data.luckInfo.vip_act_num != 0) {
                      self.setData({
                        'luckInfo.user_LuckNumDay': self.data.luckInfo.user_LuckNumDay - 1,
                        // isActive: true,
                      });
                    };

                    self.setData({
                      // 'luckInfo.user_LuckNumDay': self.data.luckInfo.user_LuckNumDay - 1,
                      isActive: true,
                      wow: res.data.data,
                    });
                    // console.log('wow', self.data.wow);
                    // console.log('请求成功', res.data.data);
                    let luckyId = res.data.data.id;
                    let indexArr = self.luckyIndex(self.data.prizes, luckyId);
                    // console.log('抽奖奖品id', luckyId);
                    // console.log('奖品列表', self.data.prizes);
                    // console.log('奖品对应的索引数组', indexArr);
                    let random = Math.random() * indexArr.length >> 0;
                    // console.log('random', random);
                    let index = indexArr[random];

                    $lucky.stop(index);

                    // setTimeout(() => {
                    // 	Promise.resolve($lucky.stop(index)).then(()=>{
                    // 			self.data.start = false;
                    // 	});

                    // }, 2000);


                    //获取兑奖记录
                    // app.request.get('/api/weshop/marketing/marketingLuckRecord/page', {
                    // 	isShowLoading: false,
                    // 	data: {
                    // 		store_id: app.globalData.setting.stoid,
                    // 		user_id: app.globalData.userInfo.user_id,
                    // 		luck_formid: self.data.options.id,
                    // 		luck_state: 1
                    // 	},
                    // 	success: function(res) {
                    // 		if(res.data.code == 0) {
                    // 			// console.log('res===>', res.data.data.pageData);
                    // 			self.setData({
                    // 				record: res.data.data.pageData,
                    // 			});
                    // 		};
                    // 	},	
                    // });


                  } else {
                    let thxIndexArr = self.data.thxIndexArr;
                    const random = Math.random() * thxIndexArr.length >> 0;
                    const index = thxIndexArr[random];
                    // console.log('谢谢参与数组', thxIndexArr);
                    // console.log('请求出错产生谢谢参与的随机数', index);
                    $lucky.stop(index);
                    // setTimeout(() => {
                    // 	Promise.resolve($lucky.stop(index)).then(()=>{
                    // 			self.data.start = false;
                    // 	});
                    // }, 2000);




                    if (res.data.code == -1) {
                      wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        success: function () {
                          self.setData({
                            start: false
                          });
                        }
                      });
                      self.data.luckInfo.msgInfo = res.data.msg;
                      return;
                      // self.data.start = true;
                    };


                    if (res.data.code == -2 && self.data.luckInfo.vip_act_num != 0) {
                      self.setData({
                        'luckInfo.user_LuckNumDay': self.data.luckInfo.user_LuckNumDay - 1,
                      });
                    };


                  };


                },

                fail: function (res) {
                  // console.log('出错');
                  wx.showToast({
                    title: '数据请求失败',
                    icon: 'error',
                  });
                  let thxIndexArr = self.data.thxIndexArr;
                  const random = Math.random() * thxIndexArr.length >> 0;
                  const index = thxIndexArr[random];
                  $lucky.stop(index);
                  // setTimeout(() => {
                  // 	Promise.resolve($lucky.stop(index)).then(()=>{
                  // 			self.data.start = false;
                  // 	});
                  // }, 2000);
                },



              });

            }


          } else {
            wx.showToast({
              title: '你今天的抽奖次数已用完啦！~',
              icon: 'none',
              success: function () {
                self.setData({
                  start: false
                });
              }
            });
          };

        };
      });






  },
  end(event) {
    // 中奖奖品详情
    // console.log('抽奖结果：',event.detail);
    let no_luck_urltype = this.data.luckInfo.no_luck_urltype;
    let lbtype = null;
    // let good_id = null;
    let resultTitle = event.detail.fonts[0].text.replace('\n', '');
    // if(event.detail.id) {
    // 	console.log('~~~~~~----++++++',event.detail.id);
    // 	good_id = event.detail.id;
    // };
    if (event.detail.lbtype == 5) {
      lbtype = 5;
    } else {
      lbtype = -1;
    };
    this.setData({
      num: 3,
      hiddenCanvas: true,
      showResult: true,
      showMask: true,
      resultTitle,
      showPopup: false,
      currentLbtype: lbtype,
      // good_id,
    });




    if (no_luck_urltype == 1 && resultTitle == '谢谢参与') {
      if (this.data.luckInfo.no_luck_weappurl) {
        let num = this.data.num;
        let url = this.data.luckInfo.no_luck_weappurl;
        self.timer = setInterval(function () {
          if (num == 0) {
            clearInterval(self.timer);
            app.goto(url);
          } else {
            self.setData({
              num: --num,
            });
          }
        }, 500);

      };

    };


    if (self.data.luckInfo.give_user) {
      if (resultTitle == '谢谢参与') {
        if (self.data.luckInfo.give_type == 1) {
          if (self.data.luckInfo.give_integral > 0) {
            wx.showToast({
              title: `获得游戏奖励积分${self.data.luckInfo.give_integral}`,
              icon: 'none',
            });
          };
        } else if ((self.data.luckInfo.give_type == 2)) {
          if (self.data.luckInfo.give_growth > 0) {
            wx.showToast({
              title: `获得游戏奖励成长值${self.data.luckInfo.give_growth}`,
              icon: 'none',
            });
          };
        };
      };
    } else {
      if (self.data.luckInfo.give_type == 1) {
        if (self.data.luckInfo.give_integral > 0) {
          wx.showToast({
            title: `获得游戏奖励积分${self.data.luckInfo.give_integral}`,
            icon: 'none',
          });
        };
      } else if ((self.data.luckInfo.give_type == 2)) {
        if (self.data.luckInfo.give_growth > 0) {
          wx.showToast({
            title: `获得游戏奖励成长值${self.data.luckInfo.give_growth}`,
            icon: 'none',
          });
        };
      };
    };


  },
  //门店回调
  async callback(e) {
    let item = e.detail;
    console.log('门店信息');
    console.log(item);

    if (item && item.pickup_id) {
      if (this.data.wow) {
        let text = 'wow.goods_pickup_id'
        this.setData({
          [text]: item.pickup_id
        })
        this.showQr()
      } else {
        let action_item = this.data.action_item
        if (!action_item.currentTarget.dataset.verify_pickup_id) {
          action_item.verify_pickup_id = item.pickup_id
        }
        this.showQr(action_item)
      }


    } else {
      wx.showToast({
        title: '门店选择失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  //门店选择1
  select_product() {
    if (this.data.luckInfo.is_store==1) {
      this.setData({
        store: 1,
        showResult: false,
      })
    }else{
      this.clickReceive()
    }
  },
  //门店选择2
  select_product2(e) {
    if (e.currentTarget.dataset.verify_pickup_id) {
      this.showQr(e)
    } else {
      if (this.data.luckInfo.is_store==1) {
        this.setData({
          store: 1,
          showResult: false,
          showPopup: false,
          action_item: e,
          wow: ''
        })
      }else{
        this.showQr(e)
      }
    }

  },
  showPopup() {
    this.setData({
      list: null,
      pageNum: 1,
      noMore: false,
    });
    this.getData(true, '/api/weshop/marketing/marketingLuckRecord/page', {
      store_id: app.globalData.setting.stoid,
      user_id: app.globalData.userInfo.user_id,
      luck_formid: this.data.options.id,
      luck_state: 1,
    }).then(function (res) {
      self.setData({
        showPopup: true,
        showMask: true,
        hiddenCanvas: true,
      });
    });

    // this.setData({
    // 	showPopup: true,
    // 	showMask: true,
    // 	hiddenCanvas: true,
    // 	'list.pageData': this.data.record,
    // 	// record: self.data.list.pageData,
    // });

  },

  closePopup() {
    this.setData({
      showPopup: false,
      showMask: false,
      hiddenCanvas: false,
    });
  },

  /**
   * 关闭中奖结果
   */
  closeResult() {
    clearInterval(this.timer);
    this.setData({
      num: 3,
      showResult: false,
      showMask: false,
      hiddenCanvas: false,
      start: false,
    });
  },

  loadmore() {
    this.scrollToLower('/api/weshop/marketing/marketingLuckRecord/page', {
      store_id: app.globalData.setting.stoid,
      user_id: app.globalData.userInfo.user_id,
      luck_formid: this.data.options.id,
      luck_state: 1,
    });
  },


  /**
   * 请求数据
   */
  getData: function (isInit, url, data) {
    let p = app.request.promiseGet(url, {
      data: data,
      isShowLoading: true,
    })
      .then(function (res) {
        if (res.data.code == 0) {

          self.setData({
            isLoading: false
          });

          if (isInit) {// 第一次加载
            self.setData({
              list: res.data.data
            });
          } else {
            self.setData({
              'list.pageData': self.data.list.pageData.concat(res.data.data.pageData)
            });
          };

          if ((res.data.data.pageData.length == 0) || (res.data.data.pageSize * res.data.data.page >= res.data.data.total)) {
            self.setData({
              noMore: true
            });
          };

        } else {
          self.setData({
            'list.pageData': []
          });
        };

      });

    return p;
  },


  /**
   * 上拉加载
   */
  scrollToLower(url, requestData) {
    // 数据总量
    let total = this.data.list.total;
    // 单页最大数据量
    let pageSize = this.data.list.pageSize;
    // 如果数据总量不为0且小于或等于单页最大数据量，说明数据已全部加载，显示‘没有更多了’
    if ((total != 0) && (total <= pageSize)) {
      this.setData({
        noMore: true
      });
    };

    if (!this.data.isLoading && !this.data.noMore) {
      this.setData({
        isLoading: true,
        pageNum: this.data.pageNum + 1
      });
      requestData.page = this.data.pageNum;
      this.getData(false, url, requestData);
    };
  },


  goto(e) {
    let url = '';
    let type = e.currentTarget.dataset.type;
    let ordersn = null;
    let buyreceive_id = null;
    if (e.currentTarget.dataset.ordersn) {
      ordersn = e.currentTarget.dataset.ordersn;
    };
    if (e.currentTarget.dataset.buyreceiveid) {
      buyreceive_id = e.currentTarget.dataset.buyreceiveid;
    };
    switch (type) {
      case 1: {
        url = '/packageD/pages/user/integral/integral';
        break;
      };
      case 2: {
        url = '/packageE/pages/user/grow_value/grow_value';
        break;
      };
      case 3: {
        url = '/packageD/pages/user/coupons/coupons';
        break;
      };
      case 4: {
        url = '/pages/user/my_service/i_service';
        break;
      };
      case 6: {
        url = `/packageF/pages/giftpack/giftpacklist/giftpacklist?isBuy=0&orderSn=${ordersn}&lbId=${buyreceive_id}`;
        break;
      };
      //-- 每月礼包的优化,去列表领取  --
      case 7: {
        url = `/packageE/pages/user/monthgiftbag/monthgiftbag`;
        break;
      };

    };
    app.goto(url);
  },

  showQr(e) {
    let id = null;
    let store_id = app.globalData.setting.stoid;
    let goods_pickup_id = ''
    let off = false //是否需要携带登记的门店id

    if (e && e.currentTarget.dataset.id) {
      id = e.currentTarget.dataset.id;
      if (e.verify_pickup_id) {
        goods_pickup_id = e.verify_pickup_id;
        off = true
      }
    } else {
      id = this.data.wow.record_id;
      goods_pickup_id = this.data.wow.goods_pickup_id;
      off = true
    };
    let url = `/api/weshop/marketing/marketingLuckList/updateGoodsVerifyCode/${store_id}/${id}`;

    //判断是否需要登记门店，才可以核销商品
    if (this.data.luckInfo.is_store == 1 && goods_pickup_id && off) {
      url += `/${goods_pickup_id}`
    }

    // console.log('good_id', id, url);
    app.request.put(url, {
      success: function (res) {
        if (res.data.code == 0) {
          let data = res.data.data;
          let barcode = self.selectComponent("#qrcode");
          barcode.open({ val: data });
          self.setData({
            hiddenCanvas: true,
            showPopup: false,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          });
        };
      },

    });
  },

  closeQr() {
    this.setData({
      hiddenCanvas: false,
      showMask: false,
    });
  },

  clickReceive() {
    this.setData({
      showResult: false,
    });
    this.showQr();
  },



  showPoster() {

    console.log('已经生成图片!!!!!!', self.data.imgPath);
    // console.log(Promise.resolve(this.onImgOK));
    wx.showLoading({
      title: '生成海报中',
    });
    var timer;
    if (this.data.isImgOk && this.data.getMiniCode) {
      wx.hideLoading();
      self.setData({
        myimg: self.data.imgPath,
        hiddenCanvas: true,
        showMask: true,
        showPoster: true,
      });
    } else {
      timer = setInterval(function () {
        if (self.data.isImgOk && self.data.getMiniCode) {
          clearInterval(timer);
          wx.hideLoading();
          self.setData({
            myimg: self.data.imgPath,
            hiddenCanvas: true,
            showMask: true,
            showPoster: true,
          });
        };
      }, 500);
    };
  },

  closePoster() {
    this.setData({
      showMask: false,
      showPoster: false,
      hiddenCanvas: false,
    });
  },
  //门店退出回调
  closeback(){
    console.log('门店关闭回调');
    this.setData({
      store: 0,
      showPopup: false,
      showMask: false,
      hiddenCanvas: false,
    })
  },


  onImgOK(e) {
    console.log('图片绘制成功', e.detail.path);
    // this.setData({
    // 	imgPath: e.detail.path,
    // });
    if (e && e.detail.path) {
      this.setData({
        isImgOk: true,
        imgPath: e.detail.path,
      });
    };

  },



})