var lottery = (function () {
  'use strict';
  var Lottery = function (params) {
    var p = this;
    p.params = {
      appid: '',
      accountsId: '',
      cfApp: null,
      devMode: false,
      dataApi: G.baseUri() + '/mobile/auth/wheel/detail/',
      prizesApi: G.baseUri() + '/mobile/auth/wheel/play/',
      vt: ''
    };

    for (var param in params) {
      p.params[param] = params[param];
    }
    var cfApp = p.params.cfApp;
    if (p.params.devMode) {
      p.params.dataApi = 'json/lottery-detail.json';
      p.params.prizesApi = 'json/prizes.json';

    }
 p.english = cfApp.getQueryString('english') == 1 ? true : false;
    console.log(p.english);

    p.id = cfApp.getQueryString('activityId');
    p.wintips;
    Handlebars.registerHelper({

      'datetimeformat': function (t) {
        var date = new Date(t);
        return dataUtils.dateFormat(date, 'yyyy.MM.dd')
      }
    });
    /**
     * 判断app字段
     * @returns 是否app有值
     */
    var validAppField = function () {
      if (!p.params.appid || p.params.appid == '') {
        return false;
      } else {
        return true;
      }
    };

    /**
     * 确认初始化的app 和tokenId 两个值是否都存在
     * 如果不存在则获取一次,获取不到则初始化失败
     * @returns 初始化基础字段是否成功
     */
    var initBaseFields = function () {
      if (!validAppField()) {
        p.params.appid = cfApp.getQueryString('appid');
        //p.params.accountsId = cfApp.getQueryString('accountsId');
      }



      //如果获取不到app和tokenId,则直接从传入的CfApp中获取值
      if (!validAppField()) {
        if (p.params.cfApp) {
          p.params.appid = cfApp.getAppId();
          //p.params.tokenId = cfApp.getTokenId();
        }
      }
      p.empInfo = cfApp.getMpInfo();

      if (!p.params.devMode) {
        p.params.prizesApi = p.params.prizesApi + p.id + '/' + p.empInfo.openId;
      }

      return validAppField();
    };

    /**
     * 初始化组件
     * @returns {boolean}
     */
    p.init = function () {
      if (initBaseFields()) {

        var sideDiv = new side({
          currentIndex: '4',
          cfApp:cfApp

        });


        sideDiv.init();
        log();
        loadData();
        event();
  $('.language').click(function () {
    if(!p.english){
 location.href = 'lottery-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1&activityId='+cfApp.getQueryString("activityId");
    }else{
 location.href = 'lottery.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id')+'&activityId='+cfApp.getQueryString("activityId");
    }
         
        });
        return true;
      } else {
        return false;
      }
    };
    var log = function () {

      var formdata = {
        openid: p.empInfo.openId,
        module: "研讨会",
        modulename: "抽奖",
        keyword: "抽奖",
        keywordid: '',
        vt: new Date().getTime(),
        appid: cfApp.getQueryString('appid'),
        url: location.href
      };
      G.ajax(G.devModePost, '/schaeffler/mobile/testAsync/doLOg', formdata, function (retdata) {


      });
    }




    var loadData = function () {
      var formdata = {
        id: p.id,
        openId: p.empInfo.openId,
        meetingId:cfApp.getQueryString('id')
      };
      if (!p.params.devMode) {
        p.params.dataApi = p.params.dataApi + p.id + '/' + p.empInfo.openId;

      }
      G.ajax('get', p.params.dataApi, formdata, function (retdata) {
        if (retdata.errorNo == '0') {
          var data = retdata.data;
          p.data = data;
          p.wintips = data.wintips;
          if (data.status == 0) {
            var text = p.english?"The activity is over":"活动未开始！"
            $.modal({
              title: "",
              text: '<span class="color-green">'+text+'</span>',
              buttons: [{
                text: "确定OK",
                onClick: function () {
                  window.history.go(-1);
                }
              }]
            });
            return false;
          } else if (retdata.errorNo == '2') {
            var text = p.english?"The activity is over":"活动已结束！";
            $.modal({
              title: "",
              text: '<span class="color-green"></span><br>',
              buttons: [{
                text: "确定OK",
                onClick: function () {
                  window.history.go(-1);
                }
              }]
            });
            return false;
          }

          if (data.needRegister) {
            if (p.empInfo.memberId == '') {
              var text = p.english?"Please register first":"请先注册！"
              $.modal({
                title: "",
                text: '<span class="color-green">'+text+'</span><br>',
                buttons: [{
                  text: "确定OK",
                  onClick: function () {
                    location.href = 'register.html?appid=' + p.params.appid;
                  }
                }]
              });
              return false;
            }
          }

          var content = $('#template').html();
          var template = Handlebars.compile(content);
          retdata.data.prizes = JSON.parse(retdata.data.prizes);
          console.log(data)
          var htmlStr = template(data);
          $('.content').append(htmlStr);
          p.prizesArr = retdata.data.prizes;
          //p.nameArr = ['谢谢参与'];
            p.nameArr = [];
            var noPrizeCount=0;
          for (var i = 0, k = p.prizesArr.length; i < k; i++) {
            p.nameArr.push(p.prizesArr[i].name)
              if(p.prizesArr[i].name=='谢谢参与'){
                  p.itemIndex=i+1;
                  noPrizeCount++;
              }
          }
            if(noPrizeCount==0){
                p.nameArr.push('谢谢参与')
                p.itemIndex=p.nameArr.length;
            }
          initPan(p.nameArr);
        }
      })
    };




    var loadPrizes = function () {

    }



    var initPan = function (data) {
      var turnplate = {
        restaraunts: [], //大转盘奖品名称
        colors: [], //大转盘奖品区块对应背景颜色
        outsideRadius: 204, //大转盘外圆的半径
        textRadius: 120, //大转盘奖品位置距离圆心的距离
        insideRadius: 0, //大转盘内圆的半径
        startAngle: 0, //开始角度

        bRotate: false //false:停止;ture:旋转
      };


      //动态添加大转盘的奖品与奖品区域背景颜色
      turnplate.restaraunts = data;
      turnplate.colors = ["rgba(0,0,0,0)", "rgba(0,0,0,0)", "rgba(0,0,0,0)", "rgba(0,0,0,0)", "rgba(0,0,0,0)6", "rgba(0,0,0,0)", "rgba(0,0,0,0)", "rgba(0,0,0,0)"];


      var rotateTimeOut = function () {
        $('#wheelcanvas').rotate({
          angle: 0,
          animateTo: 2160,
          duration: 8000,
          callback: function () {
            alert('网络超时，请检查您的网络设置！');
          }
        });
      };

      //旋转转盘 item:奖品位置; txt：提示语;
      var rotateFn = function (item, txt) {
        var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length * 2));
        if (angles < 270) {
          angles = 270 - angles;
        } else {
          angles = 360 - angles + 270;
        }
        $('#wheelcanvas').stopRotate();
        $('#wheelcanvas').rotate({
          angle: 0,
          animateTo: angles + 1800,
          duration: 8000,
          callback: function () {
            console.log(txt);
            turnplate.bRotate = !turnplate.bRotate;


            $.modal({
              title: "",
              text: txt,
              buttons: [{
                text: "确定OK"
              }]
            });



            //


          }
        });
      };

      $('.pan-pointer').click(function () {
        if (turnplate.bRotate) return;
        turnplate.bRotate = !turnplate.bRotate;
        //获取随机数(奖品个数范围内)
        //var item = rnd(1,turnplate.restaraunts.length);
        //获取获奖数据

        var formdata = {
          meetingId:cfApp.getQueryString("id")
        };

        G.ajax('post', p.params.prizesApi, formdata, function (retdata) {
          if (retdata.errorNo == '0') {
            p.prizes = retdata.data.name;
            var item = p.nameArr.indexOf(p.prizes);
            item = item + 1;
            rotateFn(item, p.wintips + '您获得' + p.prizes);
            var count = parseInt($('#count').text())
            $('#count').html(count + 1);
          } else if (retdata.errorNo == '1') {
            var text = p.english?retdata.errorEnMsg:retdata.errorMsg;
            $.modal({
                title: "",
                text:text,
                buttons: [{
                  text: "确定OK"
                }]
              });
            turnplate.bRotate = false;
            return false;
          } else if (retdata.errorNo == '2') {
              rotateFn(p.itemIndex, '未中奖！');
            var count = parseInt($('#count').text())
            $('#count').html(count + 1);
          }else if(retdata.errorNo==6){
            //没有填问卷不能玩
            $.modal({
              title: "",
              text: '没有填问卷不能玩</br>',
              buttons: [{
                text: "确定OK"
              }]
            });
          turnplate.bRotate = false;
          return false;
          }
        })




        //奖品数量等于10,指针落在对应奖品区域的中心角度[252, 216, 180, 144, 108, 72, 36, 360, 324, 288]




      });


      function rnd(n, m) {
        var random = Math.floor(Math.random() * (m - n + 1) + n);
        return random;

      }


      //页面所有元素加载完毕后执行drawRouletteWheel()方法对转盘进行渲染
      window.onload = function () {
        //drawRouletteWheel();
      };

      var drawRouletteWheel = function () {
        var canvas = document.getElementById("wheelcanvas");
        if (canvas.getContext) {
          //根据奖品个数计算圆周角度
          var arc = Math.PI / (turnplate.restaraunts.length / 2);
          var ctx = canvas.getContext("2d");
          //在给定矩形内清空一个矩形
          ctx.clearRect(0, 0, 422, 422);
          //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式  
          ctx.strokeStyle = "rgba(0,0,0,0)";
          //font 属性设置或返回画布上文本内容的当前字体属性
          ctx.font = '20px Microsoft YaHei';
          for (var i = 0; i < turnplate.restaraunts.length; i++) {
            var angle = turnplate.startAngle + i * arc;
            ctx.fillStyle = turnplate.colors[i];
            ctx.beginPath();
            //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）    
            ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false);
            ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true);
            ctx.stroke();
            ctx.fill();
            //锁画布(为了保存之前的画布状态)
            ctx.save();

            //----绘制奖品开始----
            ctx.fillStyle = "#ffffff"; //字体颜色

            var text = turnplate.restaraunts[i];
            var line_height = 17;
            //translate方法重新映射画布上的 (0,0) 位置
            ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius);

            //rotate方法旋转当前的绘图
            ctx.rotate(angle + arc / 2 + Math.PI / 2);

            /** 下面代码根据奖品类型、奖品名称长度渲染不同效果，如字体、颜色、图片效果。(具体根据实际情况改变) **/
            if (text.indexOf("M") > 0) { //流量包
              var texts = text.split("M");
              for (var j = 0; j < texts.length; j++) {
                ctx.font = j == 0 ? 'bold 20px Microsoft YaHei' : '16px Microsoft YaHei';
                if (j == 0) {
                  ctx.fillText(texts[j] + "M", -ctx.measureText(texts[j] + "M").width / 2, j * line_height);
                } else {
                  ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                }
              }
            } else if (text.indexOf("M") == -1 && text.length > 6) { //奖品名称长度超过一定范围 
              text = text.substring(0, 6) + "||" + text.substring(6);
              var texts = text.split("||");
              for (var j = 0; j < texts.length; j++) {
                ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
              }
            } else {
              //在画布上绘制填色的文本。文本的默认颜色是黑色
              //measureText()方法返回包含一个对象，该对象包含以像素计的指定字体宽度
              ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
            }

            //添加对应图标

            //把当前画布返回（调整）到上一个save()状态之前 
            ctx.restore();
            //----绘制奖品结束----
          }
        }
      };

      drawRouletteWheel();
    }
    var event = function () {



    };







  };

  return Lottery;
})();