var survey = (function () {
  'use strict';
  var Survey = function (params) {
    var p = this;
    p.params = {
      appid: '',
      accountsId: '',
      cfApp: null,
      devMode: false,
      dataApi: G.baseUri() + '/mobile/auth/qustion/getquest',
      postApi: G.baseUri() + '/mobile/auth/qustion/insertpaperlog',
        paperread:G.baseUri()+ '/mobile/auth/paper/paperread',
        paperaddren:G.baseUri()+'/mobile/auth/paperredadd/paperaddren',
        acitvityId:'',
      vt: ''
    };

    for (var param in params) {
      p.params[param] = params[param];
    }
    var cfApp = p.params.cfApp;
 p.english = cfApp.getQueryString('english') == 1 ? true : false;
    console.log(p.english);

    if (p.params.devMode) {
      p.params.dataApi = 'json/survey.json';
      p.params.postApi = 'json/code.json';
        p.params.paperread = 'json/survey.json';
        p.params.paperaddren = 'json/survey.json';

    }
    //注册索引+1的helper
    Handlebars.registerHelper("addOne", function (index) {
      //返回+1之后的结果
      return index + 1;
    });

    /**
     * 判断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();
      p.params.accountsId = p.empInfo.accountsId;
      return validAppField();
    };

    /**
     * 初始化组件
     * @returns {boolean}
     */


    p.init = function () {



      if (initBaseFields()) {
        log();
        loadData();
          paperreads();
          paperaddrens();
        chooseInit();
        submit();

  $('.language').click(function () {
    if(!p.english){
location.href = 'public-survey-english.html?appid=' + p.params.appid  + '&english=1'+'&paperId='+cfApp.getQueryString('paperId');
    }else{
location.href = 'public-survey.html?appid=' + p.params.appid +'&paperId='+cfApp.getQueryString('paperId');
    }
          
        });
        return true;
      } else {
        return false;
      }
    };
    var log = function () {

      var formdata = {
        openid: p.empInfo.openId,
        module: "开放问卷",
        modulename: "问卷调查",
        keyword: "问卷调查",
        keywordid: cfApp.getQueryString('paperId'),
        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 () {
      $.showLoading();
      var formdata = {
        activid: cfApp.getQueryString('paperId')
      };
      G.ajax('get', p.params.dataApi, formdata, function (retdata) {
        $.hideLoading();
        if (retdata.errorNo == '0') {
          var question = JSON.parse(retdata.question);
            p.params.acitvityId=retdata.activityId;
          retdata.question = question;
          console.log(question);
          for (var i = 0, j = question.length; i < j; i++) {
            if (question[i].type == "BLANKFILL") {
              question[i].isBlank = true;
            } else if (question[i].type == "MULTISEL") {
              question[i].isMultsel = true;
            }
            if (question[i].type == "SINGLESEL") {
              question[i].isSinglesel = true;
            }
          }
          var content = $('#template').html();
          p.template = Handlebars.compile(content);
            console.log(retdata)
          var htmlStr = p.template(retdata);
          $('.content').append(htmlStr);

          /*  if(p.english){
                $("title").html(retdata.paper_title_en);
            }else{
                $("title").html(retdata.paper_title);
            }*/

        }
      });
    }

    var chooseInit = function () {
      //单选
      $('body').on('click', '.single-select li', function () {
        $(this).parents('.single-select').find('li').removeClass('choose');
        $(this).addClass('choose');
      });
      //多选
      $('body').on('click', '.multi-select li', function () {
        $(this).toggleClass('choose');
      });
    }

    var submit = function () {

      $('#submit').click(function () {
        var allArr = [];




        //单选
        $('.single-select').each(function () {
            var singleObj = {
                type: "SINGLESEL",
                value: '',
                activid: cfApp.getQueryString('paperId'),
                openid: p.empInfo.openId
            }
          var obj = $(this);
          var index=$(this).attr('data-index');
          if (!obj.find('.choose').length > 0) {
            $.modal({
              title: "",
              text: '<span class="color-green">第'+index+'题：最少选择一项！</span><br>Question '+index+': Choose at least 1 option',
              buttons: [{
                text: "确定OK"
              }]
            });
           
            return false;
          }
          var valueObj = new Object;
          valueObj.sid = obj.attr('id');
          valueObj.oid = obj.find('.choose').attr('id');
          singleObj.value = JSON.stringify(valueObj);
          allArr.push(singleObj);
        });
        //多选
        $('.multi-select').each(function () {
            var multiObj = {
                type: "MULTISEL",
                value: ''
            }
          var obj = $(this);
          var index=$(this).attr('data-index');
          var min=$(this).attr('data-min');
          var max=$(this).attr('data-max');

          if (obj.find('.choose').length <min) {
            $.modal({
              title: "",
              text: '<span class="color-green">第'+index+'题：最少选择'+min+'项！</span><br>Question '+index+': Choose at least '+min+' options',
              buttons: [{
                text: "确定OK"
              }]
            });
            return false;
          }

          if(max&&max!=''&&obj.find('.choose').length>max){
            $.modal({
                title: "",
                text: '<span class="color-green">第'+index+'题：最多只能选择'+max+'项！</span><br>Question '+index+':Can not select<br>more than '+max+' options',
                buttons: [{
                    text: "确定OK"
                }]
            });
            return false;

        }


          var valueArr = [];
          obj.find('.choose').each(function () {
            var valueObj = {
              sid: obj.attr('id'),
              oid: "",
              activid: cfApp.getQueryString('paperId'),
              openid: p.empInfo.openId
            };
            valueObj.oid = $(this).attr('id');
            valueArr.push(valueObj);
          });

          multiObj.value = JSON.stringify(valueArr);
          allArr.push(multiObj);
        });

        //简答
          var valueObj = null;
        $('.text').each(function () {

            var textObj = {
                type: "BLANKFILL",
                value: '',
                activid: cfApp.getQueryString('paperId'),
                openid: p.empInfo.openId
            }

          var obj = $(this);
          var content = obj.find('textarea').val();
            var min=obj.find('textarea').attr('data-min');
            var max=obj.find('textarea').attr('data-max');
            var index=obj.find('textarea').attr('data-index');

           /* if(content.length<min){
                $.modal({
                    title: "",
                    text: '<span class="color-green">第'+index+'题：回答字数不能少于'+min+'个字！</span><br>Question '+index+': Answer no less than '+min+' words',
                    buttons: [{
                        text: "确定OK"
                    }]
                });
                return false;
            }*/


            if(max&&max!=''&&content.length>max){
                $.modal({
                    title: "",
                    text: '<span class="color-green">第'+index+'题：回答字数不能多于'+max+'个字！</span><br>Question '+index+': Answer no more than '+max+' words',
                    buttons: [{
                        text: "确定OK"
                    }]
                });
                return false;

            }
          // if (!content || content == '') {
          //   $.modal({
          //     title: "",
          //     text: '<span class="color-green">请完成问卷！</span><br>Please complete the<br>survey',
          //     buttons: [{
          //       text: "确定OK"
          //     }]
          //   });
          //   return false;
          // }
            valueObj = new Object;
          valueObj.sid = obj.attr('id');
          valueObj.option_con = content;
          textObj.value = JSON.stringify(valueObj);
          allArr.push(textObj);
        });
        console.log(allArr);

if(allArr.length==$('.select').length){
    postData(allArr);
}
        
        
      })

    }
      //浏览量
      var paperreads = function(){
          var formdata = {
              id:cfApp.getQueryString('paperId')
          }
          G.ajax(G.devModePost,p.params.paperread,formdata,function(retdata){
              if(retdata.errorNo == 0){
                  return
              }else if(retdata.errorNo == 1){
                  $.modal({
                      title: "",
                      text: '<span class="color-green">获取异常！</span></br>System error',
                      buttons: [{
                          text: "确定OK"
                      }]
                  });
              }else if(retdata.errorNo == 2){
                  $.modal({
                      title: "",
                      text: '<span class="color-green">参数异常！</span></br>Parameter  error',
                      buttons: [{
                          text: "确定OK"
                      }]
                  });
              }
          })
      }

      //添加浏览人的信息
        var paperaddrens = function(){
            var formdata = {
                openid:p.empInfo.openId,
                paper_id:cfApp.getQueryString('paperId'),
                accountsId:p.params.accountsId
            }
            G.ajax(G.devModePost,p.params.paperaddren,formdata,function(retdata){
                if(retdata.errorNo == 0){
                    return
                }else if(retdata.errorNo == 1){
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                }else if(retdata.errorNo == 2){
                    $.modal({
                        title: "",
                        text: '<span class="color-green">参数异常！</span></br>Parameter  error',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                }
            })
        }

    var postData=function(e){
        var formdata={
            questionAnswer:JSON.stringify(e),
            openid:p.empInfo.openId,
            paperId:cfApp.getQueryString("paperId")
        }

        G.ajax(G.devModePost, p.params.postApi, formdata, function (retdata) {
            if (retdata.errorNo == '0') {
                if(p.params.acitvityId!=null && p.params.acitvityId!=''){
                    $.modal({
                        title: "",
                        text: '<span class="color-green">提交成功,去抽奖</span><br>Success,go to draw',
                        buttons: [{
                            text: "确定OK",
                            onClick:function(){
                                if(p.english){
                                    location.href='lottery-english.html?appid='+p.params.appid+'&id='+cfApp.getQueryString('id')+'&english=1'+"&activityId="+p.params.acitvityId;
                                }else{
                                    location.href='lottery.html?appid='+p.params.appid+'&id='+cfApp.getQueryString('id')+"&activityId="+p.params.acitvityId+"&vt="+new Date().getTime();
                                }

                            }
                        }]
                    });
                }else{
                    $.modal({
                        title: "",
                        text: '<span class="color-green">提交成功</span><br>Success',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                }

            }else if(retdata.errorNo==4){
                $.modal({
                    title: "",
                    text: '<span class="color-green">你已参加此问卷</span><br>Success',
                    buttons: [{
                        text: "确定OK"
                    }]
                });
            }
      
      
        });

    }
  };

  return Survey;
})();