var register = (function () {
  'use strict';
  var Register = function (params) {
    var p = this;
    p.params = {
      appid: '',
      accountsId: '',
      cfApp: null,
      devMode: false,
      dataApi: G.baseUri() + '/mobile/auth/screen/addscreen',
      returnqustion: G.baseUri()+ '/mobile/auth/screen/selectcustomiz',
      selecttopic:G.baseUri()+'/mobile/auth/screen/selecttopic',
      customizbyid:G.baseUri()+'/mobile/auth/screen/customizbyid',
      vt: ''
    };
    for (var param in params) {
      p.params[param] = params[param];
    }
    var cfApp = p.params.cfApp;
    p.english = cfApp.getQueryString('english') == 1 ? true : false;
    if (p.params.devMode) {
      p.params.dataApi = 'json/code.json';
      p.params.returnqustion = 'json/code.json';
      p.params.selecttopic = 'json/code.json';
      p.params.customizbyid = 'json/code.json';
    }


    var serverId;
    var customId;
    var topicIds;
    //会场数组
    p.groupDatas = [];
    //主题数组
    p.topicDatas = [];
    //已选择的会场id
    p.groupId = null;

    /**
     * 判断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()) {
        var sideDiv = new side({
          currentIndex: '10',
          cfApp: cfApp
        });
        initSearch();
        sideDiv.init();
        initInfinite();
        log();
        submit();
        loadData();


        $('.language').click(function () {
          if(p.english){
            location.href="meeting-screen.html?appid="+cfApp.getQueryString("appid")+"&id="+cfApp.getQueryString("id");
          }else{
            location.href="meeting-screen-english.html?appid="+cfApp.getQueryString("appid")+"&id="+cfApp.getQueryString("id")+"&english=1";
          }
        })
        return true;
      } else {
        return false;
      }
    };
    var log = function () {
      var formdata = {
        openid: p.empInfo.openId,
        module: "研讨会",
        modulename: "现场投屏",
        keyword: "现场投屏",
        keywordid: cfApp.getQueryString('id'),
        vt: new Date().getTime(),
        appid: cfApp.getQueryString('appid'),
        url: location.href
      };
      G.ajax(G.devModePost, '/schaeffler/mobile/testAsync/doLOg', formdata, function (retdata) {


      });
    }
    var initInfinite = function () {
      $('body').infinite().on("infinite", function () {
        if (p.loading) return;
        p.loading = true;

        setTimeout(function () {

          loadCommentList();

        }, 800);
      });

      $('.submitheader>img').click(function () {
        $(".diymask").hide();
        $(".submitdesc").hide();
      });
    };
    //会场弹窗
    var initSearch = function () {
      $(".diymask").show();
      $(".submitdesc").show();
      //单选
      $('body').on('click', '.single-select li', function () {
        $(this).parents('.single-select').find('li').removeClass('choose');
        $(this).addClass('choose');
      });
    }

    var agendaId = null;
    var customiz_Id = null;
    //提交会场
    $('body').on('click','.submitbody button',function(){
      var customizids = null;
      for(var i=1;i<$('.single-select li').length;i++){
        var node = $('.single-select li')[i];
        //if($(node).attr('class').length>31){ //选中
        if($(node).attr('class').indexOf('choose')>0){  //选中
          //alert($(node).find('p').html())
          customizids = $(node).find('span').attr('data-value');
          break;
        }
      }
        if(customizids == null){
            return;
        }else{
            var formdata = {
                customizId:customizids
            }
            G.ajax(G.devModePost,p.params.customizbyid, formdata, function (retdata) {
                if(retdata.errorNo == 0){
                  $(".diymask").hide();
                  $(".submitdesc").hide();
                  var item = retdata.data;
                  if(p.english){
                    $('#customiz').val(item.customiz_name_en);
                    $('#topic').val(item.agenda_title_en);
                  }else{
                    $('#customiz').val(item.customiz_name);
                    $('#topic').val(item.agenda_title);
                  }
                  agendaId = item.id;
                  customiz_Id = item.customiz_id;
                }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"
                        }]
                    });
                }else if(retdata.errorNo ==3){
                  $(".diymask").hide();
                  $(".submitdesc").hide();
                    $.modal({
                        title: "",
                        text: '<span class="color-green">该会场当前未开放</span></br>This session is currently not open',
                        buttons: [{
                            text: "确定OK",
                          onClick:function(){
                            location.reload();/*11111*/
                          }
                        }]
                    });
                }

            });
        }


    })


    //初始化会场组件
   /* function meetingGroup() {
      var formdata = {
        workshop_id:cfApp.getQueryString('id'),
        accountsid:p.params.accountsId
      }
      G.ajax(G.devModePost, p.params.returnqustion, formdata, function (retdata) {
        if(retdata.errorNo == 0){
          var customiz = [];
          var customizId = [];
          p.groupDatas = retdata.data;
          for (var i =0,j=retdata.data.length;i<j;i++){
              var item = retdata.data[i];
            customizId.push(item.id);
            customiz.push(item.customiz_name);
          }
          $("#customiz").picker({
            title: "",
            cols: [{
              textAlign: 'center',
              values: customiz
            }],
            onClose: function () {
              var index = customiz.indexOf($("#customiz").val());
              customId=customizId[index];
              if (customId != p.groupId) {
                //topicGrop();
                handleTopicPicker(customId);
                console.log(customId);
              }

            }
          });

          $('#pic1').on('click', function(e) {
            e.stopPropagation();
            e.preventDefault();
            $("#customiz").picker('open')

          });

        }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"
            }]
          });
        }
      })

    }*/
    /*$('#pic2').on('click', function(e) {
      e.stopPropagation();
      e.preventDefault();
      $("#topic").picker('open')

    });
    $('#topic').on('click', function(e) {
      e.stopPropagation();
      e.preventDefault();
      $("#topic").picker('open');
    })*/

    //处理联查问题
   /* var handleTopicPicker = function(customId) {
      var topicDom = $("#topic");
      // 处理选择的数据关联
      var topic = [];
      var topicId = [];
      //var customNames = [];
      for (var i = 0,j = p.topicDatas.length; i< j; i++) {
        var item = p.topicDatas[i];
        if (item.customiz_id == customId) {
          topic.push(item.agenda_title);
            topicId.push(item.id);
          //customNames.push(item.customiz_name);
        }

      }
      if (topicDom.data('picker')) {
        topicDom.removeData('picker');
        topicDom.val("");
      }
      //重新初始化picker
      $("#topic").picker({
        title: "",
        cols: [{
          textAlign: 'center',
          values: topic
        }],
        onClose: function () {
          //var index = topic.indexOf($("#topic").val());
          //var customName =customNames[index];
         // $("#customiz").picker("setValue",[customName]);
            var index = topic.indexOf($("#topic").val());
            topicIds=topicId[index];
        }
      });
    };*/


   /* var topics = "";
    //初始化主题
    function topicGrop(){
      $("#topic").val("");
      var formdata = {
        customiz_id:customId,
        meetingId:cfApp.getQueryString('id')
      }
      G.ajax(G.devModePost,p.params.selecttopic,formdata,function(retdata){
        if(retdata.errorNo == 0){
          var topic = [];
          var topicId = [];
          var customIds = [];
          p.topicDatas=retdata.data;
          for (var i =0, j=retdata.data.length;i<j;i++){
            var item = retdata.data[i];
            topicId.push(item.id);
            topic.push(item.agenda_title);
            customIds.push(item.customiz_id);
          }
          if(customId &&customId!=null){
            $("#topic").picker("setValue", topic);
          }else{
            $("#topic").picker({
              title: "",
              cols: [{
                textAlign: 'center',
                values: topic
              }],
              onClose: function () {
                var index = topic.indexOf($("#topic").val());
                  topicIds=topicId[index];
                  console.log(topicIds);
                var customId =customIds[index];
                p.groupId = customId;
                // $("#customiz").picker('open');
                // $("#customiz").picker('close');
                // $("#customiz").picker("setValue",[customName]);
                // $("#topic").picker('open');
                // $("#topic").picker('close');
                // $("#topic").picker('setValue',[topic[index]]);
                //$("#customiz").val(customName);
                //$("#customiz").data().picker.value = [customName];

              }
            });
          }


        }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 loadData = function () {
      var formdata = {
        workshop_id:cfApp.getQueryString('id'),
        accountsid:p.params.accountsId
      }
      G.ajax(G.devModePost, p.params.returnqustion, formdata, function (retdata) {
        if(retdata.errorNo == 0){

          var content = $('#template').html();
          p.template = Handlebars.compile(content);
          var htmlStr = p.template(retdata);
          $('#list').append(htmlStr);
        }
      });
    }

    //提交现场提问
    var submit = function () {
      $('#submit').click(function () {

        var customiz = $('#customiz').val();
        if (StringValidateUtils.isEmpty(customiz)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请选择会场！</span><br>Please choose the<br>customiz',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }

        var topic = $('#topic').val();
        if (StringValidateUtils.isEmpty(topic)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请选择主题！</span><br>Please choose the<br>topic',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var problem = $('#problem').val();
        if(StringValidateUtils.isEmpty(problem)){
          $.modal({
            title:"",
            text:'<span class="color-green">请输入您想咨询的问题！</span><br>Please input the<br>question',
            buttons:[{
              text:"确定OK"
            }]
          })
          return false;
        }

        var formdata = {
          accountsId: p.params.accountsId,
          open_id: p.empInfo.openId,
          customiz_id:customiz_Id,
          topic_id:agendaId,
          meetingId: cfApp.getQueryString('id'),
          question:problem,
        }

        G.ajax(G.devModePost, p.params.dataApi, formdata, function (retdata) {
          //0:获取成功 1:获取异常 2:参数错误 3:验证码不正确 4:手机号被占用 5:此openId已注册
          if (retdata.errorNo == '0') {
            //注册成功
            $.modal({
              title: "",
              text: '<span class="color-green">提交成功！</span></br>Success',
              buttons: [{
                text: "确定OK",
                onClick:function(){
                  //location.href="exhibition.html?appid="+cfApp.getQueryString("appid")+"&id="+cfApp.getQueryString("id");
                  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"
                }]
              });
          }
          else if (retdata.errorNo == '3') {
            $.modal({
                title: "",
                text: '<span class="color-green">验证码不正确！</span></br>The phone number is occupied',
                buttons: [{
                  text: "确定OK"
                }]
              });
          }
          else if (retdata.errorNo == '4') {
            $.modal({
                title: "",
                text: '<span class="color-green">手机号被占用！</span></br>System error',
                buttons: [{
                  text: "确定OK"
                }]
              });
          }
          else if (retdata.errorNo == '5') {
            $.modal({
                title: "",
                text: '<span class="color-green">此openId已注册！</span></br>The openId is registered',
                buttons: [{
                  text: "确定OK"
                }]
              });
          }

        })



      })
    }


  };

  return Register;
})();