var exhibition = (function () {
  'use strict';
  var Exhibition = function (params) {
    var p = this;
    p.params = {
      appid: '',
      accountsId: '',
      cfApp: null,
      devMode: false,
      dataApi: G.baseUri() + '/mobile/auth/exhibi/exhibiid',
      addCommentApi: G.baseUri() + '/mobile/auth/review/addComment',
      commentListApi: G.baseUri() + '/mobile/auth/review/moduleReviewListByFans',
      likeApi: G.baseUri() + '/mobile/auth/like/like',
      clearLikeApi: G.baseUri() + '/mobile/auth/like/like',
      isvocation:G.baseUri() + '/mobile/auth/exhibivacation/isvocation',
      submitvocation:G.baseUri() + '/mobile/auth/exhibivacation/submitvocation',
      isrelease:G.baseUri()+'/mobile/auth/exhibi/isrelease',
      exhibiread:G.baseUri()+'/mobile/auth/exhibi_read/exhibiread',
      exhibisample:G.baseUri()+'/mobile/auth/exhibivacation/submitsample',
      issample:G.baseUri()+'/mobile/auth/exhibivacation/issample',
      selectMaterial:G.baseUri()+'/mobile/auth/material/selectMaterial',
      addemailrecord:G.baseUri()+'/mobile/auth/emailrecord/addEmailRecord',
      materialDetail:G.baseUri()+'/mobile/auth/material/MaterialDetail',
      vt: ''
    };

    for (var param in params) {
      p.params[param] = params[param];
    }
    var cfApp = p.params.cfApp;

    if (p.params.devMode) {
      p.params.dataApi = 'json/exhibition.json';
      p.params.addCommentApi = 'json/exhibition.json';
      p.params.commentListApi = 'json/commentlist.json';
      p.params.likeApi = 'json/commentlist.json';
      p.params.clearLikeApi = 'json/commentlist.json';
      p.params.isvocation = 'json/commentlist.json';
      p.params.submitvocation = 'json/commentlist.json';
      p.params.isrelease = 'json/commentlist.json';
      p.params.exhibiread = 'json/commentlist.json';
      p.params.exhibisample = 'json/commentlist.json';
      p.params.issample = 'json/commentlist.json';
      p.params.selectMaterial = 'json/commentlist.json';
      p.params.addemailrecord = 'json/commentlist.json';

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

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

    /**
     * 初始化组件
     * @returns {boolean}
     */
    Handlebars.registerHelper({
      'datetimeformat': function (t) {
        var date = new Date(t);
        return dataUtils.dateFormat(date, 'yyyy-MM-dd')
      },
      'praiseImg': function (likes) {
        if (likes == 0) {
          return 'image/praise.png'
        } else {
          return 'image/praised.png'
        }


      },
      'islike': function (likes) {
        if (likes != 0) {
          return 'liked'
        }

      }
    });
    p.page = 0;
    p.loading = false;

    p.init = function () {


      if (initBaseFields()) {
        //initSearch();

        log();
        loadData();
        //loadCommentList();
        exhibireads();
        isreleases();
        initInfinite();
        addComment();
        likeEvent();
        showsmple();
        showquestion();
        isvocations();
         showsample();
 $('.language').click(function () {
   if(!p.english){
location.href = 'exhibition-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
   }else{
location.href = 'exhibition.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
   }
          
        });

        return true;
      } else {
        return false;
      }
    };

    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');
      });
    }
    //提交我的身份信息
      $('body').on('click','.submitbody button',function(){
        //alert("a")
        var vocation = null;
        for(var i=1;i<$('.single-select li').length;i++){
          var node = $('.single-select li')[i];
          if($(node).attr('class') == 'align-center choose'){ //选中
             //alert($(node).find('p').html())
            vocation = $(node).find('p').html();
          }
        }
        if(vocation!=null){
          var formdata = {
            vocation:vocation,
            exhibi_id:cfApp.getQueryString('id'),
            open_id:p.empInfo.openId,
            accountsId: p.empInfo.accountsId
          }
          G.ajax(G.devModePost,p.params.submitvocation,formdata,function(retdata){
            if(retdata.errorNo == 0){
              $(".diymask").hide();
              $(".submitdesc").hide();
            }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{
              $(".diymask").show();
              $(".submitdesc").show();
              //单选
              $('body').on('click', '.single-select li', function () {
                $(this).parents('.single-select').find('li').removeClass('choose');
                $(this).addClass('choose');
              });
            }
          })
        }


      })

      var Toemail = null;
      var ToName = null;
      //提交资料信息
      $('body').on('click','.submitbodysample button',function(){
        var phone = $('input[id="phone"]').val();
        var company = $('input[id="company"]').val();
        var email = $('input[id="email"]').val();
          Toemail = email;
          ToName = phone;
        if(phone!=null&&company!=null&&email){
            var formdata = {
                exhibi_id:cfApp.getQueryString('id'),
                open_id:p.empInfo.openId,
                accountsId: p.empInfo.accountsId,
                phone:phone,
                company:company,
                email:email
            }
            G.ajax(G.devModePost,p.params.exhibisample,formdata,function(retdata){
                if(retdata.errorNo == 0){
                    $(".submitdescsample").hide();
                    $(".diymasksample").hide();
                    var formdata = {
                        exhibi_id:cfapp.getQueryString('id')
                    }
                    G.ajax(G.devModePost,p.params.selectMaterial,formdata,function(retdata){
                        var content = $("#list-template").html();
                        p.template = Handlebars.compile(content);
                        var data = retdata;
                        var htmlStr = p.template(data);
                        $('#listSample').html(htmlStr);
                        $("#samplelist").popup();
                        $("#submitemail,#arrow").show();
                    })
                }else if(retdata.errorNo == 1){
                    $.modal({
                        title: "",
                        text: '<span class="color-green">获取异常！</span></br>System error',
                        buttons: [{
                            text: "确定OK"
                        }]
                    });
                }
            })

        }

      })
     //发送邮箱
      $('body').on('click','#submitemail',function(){
          //alert(Toemail)
          $.closePopup()
          var sample_id = "";
          var send_count = 0;
          for(var i=0;i<$('.sample-select li').length;i++){
              var node = $('.sample-select li')[i];
              if($(node).attr('class')=='align-center choose'){
                //alert("a")
                  send_count ++;
                  sample_id = sample_id+$(node).find('span').attr('id')+",";
              }
          }
          var fordata={
              exhibi_id:cfApp.getQueryString('id'),
              email:Toemail,
              open_id:p.empInfo.openId,
              sample_id:sample_id,
              send_count:send_count,
              accounts_id:p.empInfo.accountsId,
              name:ToName
          }
          G.ajax(G.devModePost,p.params.addemailrecord,fordata,function(retdata){
                if(retdata.errorNo == 0){
                    $.closePopup()
                    $.modal({
                        title: "",
                        text: '<span class="color-green">发送成功！</span></br>Success',
                        buttons: [{
                            text: "确定OK",
                            onClick:function(){
                                window.location.reload()
                                /*if(!p.english){
                                    location.href = 'exhibition.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
                                }else{
                                    location.href = 'exhibition-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
                                }*/
                            }
                        }]
                    });
                }else{
                    $.closePopup()
                    alert(retdata.error)
                    $.modal({
                        title: "",
                        text: '<span class="color-green">发送失败!</span></br>System error',
                        buttons: [{
                            text: "确定OK"
                        }],
                        onClick:function(){
                            if(!p.english){
                                location.href = 'exhibition.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
                            }else{
                                location.href = 'exhibition-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
                            }
                        }
                    });
                }
          })
      })


    //判断是否填写过身份
    var isvocations = function(){
      var formdata = {
        openId:p.empInfo.openId,
        exhibi_id:cfApp.getQueryString('id')
      }
      G.ajax(G.devModePost, p.params.isvocation, formdata, function (retdata) {
        if(retdata.errorNo == 0){
          $(".diymask").hide();
          $(".submitdesc").hide();
        }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{
          $(".diymask").show();
          $(".submitdesc").show();
          //单选
          $('body').on('click', '.single-select li', function () {
            $(this).parents('.single-select').find('li').removeClass('choose');
            $(this).addClass('choose');
          });
        }

      });
    }

    //展会浏览
    var exhibireads = function(){
      var formdata = {
        openid:p.empInfo.openId,
        exhibi_id:cfApp.getQueryString("id"),
        accountsId:p.empInfo.accountsId
      }
      G.ajax(G.devModePost,p.params.exhibiread,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 isreleases = function(){
      var formdata = {
        id:cfApp.getQueryString("id")
      }
      G.ajax(G.devModePost,p.params.isrelease,formdata,function(retdata){
        if(retdata.errorNo == 0){
          $.modal({
            title: "",
            text: '<span class="color-green">展会已关闭！</span></br>Exhibition closed',
            buttons: [{
              text: "确定OK",
              onClick:function(){
                WeixinJSBridge.call('closeWindow');
              }
            }]
          });
        }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 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) {


      });
    }

      //开始把三个按钮都隐藏
      // $('#btn-exhibi').hide();
      // $('#btn-sample').hide();
      // $('#btn-question').hide();
      // $('#theleft').hide();
      // $('#theright').hide();
    var loadData = function () {
      var formdata = {
        accountsId: p.empInfo.accountsId,
        openid: p.empInfo.openId,
        id: cfApp.getQueryString('id')
      };
      G.ajax(G.devModePost, p.params.dataApi, formdata, function (retdata) {
        if (retdata.errorNo == '0') {
          var content = $('#template').html();
          p.template = Handlebars.compile(content);
          var data = retdata;
          var htmlStr = p.template(data);
          $(htmlStr).insertBefore('#comment-title');




          //都不显示
          if(retdata.show_exhibits == '1'&&retdata.show_sample == '1'&&retdata.show_inquiries == '1'){
                $('#btn-exhibi').css("display","none");
                $('#btn-sample').css("display","none");
                $('#btn-question').css("display","none");
                $('.span').css("display","none");
            }
            //只显示展品信息
            if(retdata.show_exhibits == '0'&&retdata.show_sample == '1'&&retdata.show_inquiries == '1'){
                $('#btn-exhibi').show();
                $('#btn-exhibi').css("width",'100%');
            }
            //只显示获取样本
            if(retdata.show_exhibits == '1'&&retdata.show_sample == '0'&&retdata.show_inquiries == '1'){
                $('#btn-sample').show();
                $('#btn-sample').css("width",'100%');
            }
            //只显示相关问询
            if(retdata.show_exhibits == '1'&&retdata.show_sample == '1'&&retdata.show_inquiries == '0'){
                $('#btn-question').show();
                $('#btn-question').css("width",'100%');
            }
            //显示展品信息和获取样本
            if(retdata.show_exhibits == '0'&&retdata.show_sample == '0'&&retdata.show_inquiries == '1'){
                $('#btn-exhibi').show();
                $('#btn-sample').show();
                $('#theleft').show();
                $('#btn-exhibi').css("width","49%");
                //$('#btn-exhibi').css("padding-right"," 1.22rem");
                $('#btn-sample').css("width","49%");
            }
            //显示展品信息和相关问询
            if(retdata.show_exhibits == '0'&&retdata.show_sample == '1'&&retdata.show_inquiries == '0'){
                $('#btn-exhibi').show();
                $('#btn-question').show();
                $('#theleft').show();
                $('#btn-exhibi').css("width","49%");
                //$('#btn-exhibi').css("padding-right", "1.22rem");
                $('#btn-question').css("width","49%");
            }
            //显示获取样本和相关问询
            if(retdata.show_exhibits == '1'&&retdata.show_sample == '0'&&retdata.show_inquiries == '0'){
                $("#btn-sample").show();
                $('#btn-question').show();
                $('#theright').show();
                $('#btn-sample').css("width","49%");
                //$('#btn-sample').css("padding-right","1.22rem");
                $('#btn-question').css("width","49%");
            }
            //三个显示
            if(retdata.show_exhibits == '0'&&retdata.show_sample == '0'&&retdata.show_inquiries == '0'){
                $('#btn-exhibi').show();
                $('#btn-sample').show();
                $('#btn-question').show();
                $('#theleft').show();
                $('#theright').show();
            }


          if (retdata.iscollections == 0) {
            $('#btn-collect').find('img').attr('src', 'image/collect.png');

          }
          if (retdata.isfabulous == 0) {
            $('#btn-praise').find('img').attr('src', 'image/praise-white.png');
            $('#btn-praise').addClass('praised');
            $('#detail-praise').find('img').attr('src', 'image/praised.png');

          }
        }

      })
    }

    var loadCommentList = function () {
      $.showLoading();
      var formdata = {
        accountsId: p.empInfo.accountsId,
        moduleType: 0,
        entityId: cfApp.getQueryString('id'),
        openId: p.empInfo.openId,
        page: p.page,
        pageSize: 10
      };
      G.ajax('get', p.params.commentListApi, formdata, function (retdata) {
        $.hideLoading();
        if (retdata.errorNo == '0') {

         /* var content = $('#list-template').html();
          p.template = Handlebars.compile(content);
          var htmlStr = p.template(retdata);
          $('#list').append(htmlStr);
          if (retdata.data.length < 10) {
            $('.weui-loadmore').remove();
            p.loading = true;
          } else {
            p.pageNo++;
            p.loading = false;
          }*/

        }


      });

    }

    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();
      });
     /*关闭样本资料弹出框*/
        $('.submitheadersample>img').click(function(){
            $(".diymasksample").hide();
            $(".submitdescsample").hide();
        })
    };

    var showsmple = function(){
      //展评信息
      $('#btn-exhibi').click(function(){
        if(!p.english){
          location.href = 'exhibi-material.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
        }else{
          location.href = 'exhibi-material-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id')+"&english=1";
        }

      })
    }

    var showquestion = function(){
      //跳到相关问询
      $('#btn-question').click(function(){
        if(!p.english){
          location.href = 'exhibi-inquiries.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
        }else{
            location.href = 'exhibi-inquiries-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id')+'&english=1';
        }

      })
    }


    var showsample = function(){
      //获取样本资料弹出框
        $('#btn-sample').click(function(){
                var formdata = {
                    openid:p.empInfo.openId,
                    exhibi_id:cfapp.getQueryString('id')
                }
            G.ajax(G.devModePost, p.params.issample, formdata, function (retdata) {
              if(retdata.errorNo == 0){
                  //填了资料信息
                  Toemail =  retdata.email;
                  $(".diymasksample").show();
                  $(".submitdescsample").show();
                  $("#phone").val(retdata.phone);
                  $('#company').val(retdata.company);
                  $('#email').val(retdata.email);

              }else if(retdata.errorNo == 1){
                  $.modal({
                      title: "",
                      text: '<span class="color-green">参数异常！</span></br>Parameter  error',
                      buttons: [{
                          text: "确定OK"
                      }]
                  });
              }else{
                  //未填资料信息
                $(".diymasksample").show();
                  $(".submitdescsample").show();
              }
            })

        })
    }

    //关闭样本资料
      $('body').on('click','#arrow p img',function(){
          $.closePopup()
      })

      //多选样本资料
      $('body').on('click', '.sample-select li', function () {
         // $(this).parents('.single-select').find('li').removeClass('choose');
          var str =$(this).attr('class');
          if(str == 'align-center'){
              $(this).addClass('choose');
          }else{
              $(this).removeClass('choose');
          }

      });

    //打开PDF文件
      $('body').on('click','.open',function(e){
          e.stopPropagation();
         var formdata = {
             id:$(this).parent().find('span').attr('id')
         }

         if($(this).parent().find('input').attr('id')==""){
             G.ajax(G.devModePost,p.params.materialDetail,formdata,function(retdata){
                 var url = retdata.data.file_path;
                 window.location.href ="javascript/pdf/web/viewer.html?file="+url;

                 $(this).parent().attr('class','align-center')
             })
         }else{
             //文件超过20M
             if(p.english){
                 $.modal({
                     title: "",
                     text: '<span class="color-green">The file is too large to open. Please send it to your mailbox.</span>',
                     buttons: [{
                         text: "确定OK"
                     }]
                 });
             }else{
                 $.modal({
                     title: "",
                     text: '<span class="color-green">文件太大，建议发送至邮箱查看。</span>',
                     buttons: [{
                         text: "确定OK"
                     }]
                 });
             }
         }



      })

    var addComment = function () {
      //打开评论
      $('#btn-comment').click(function () {
        $('#send-comment').show();
      });
      //关闭评论
      $('#cancel').click(function () {
        $('#send-comment').hide();
      });
      //发送评论
      $('#submit').click(function () {

        var content = $('#comment').val();
        if (!content || content == '') {
          $.modal({
            title: "",
            text: '请输入评论内容！',
            buttons: [{
              text: "确定"
            }]
          });
          return false;
        }
        var formdata = {
          entity_id:cfApp.getQueryString('id'),
          accountsId: p.empInfo.accountsId,
          module_type: 0,
          content: content,
          images: "",
          openid: p.empInfo.openId
        }

        G.ajax(G.devModePost, p.params.addCommentApi, formdata, function (retdata) {
          if (retdata.errorNo == '0') {
            $.toast("评论成功！");
            $('#send-comment').hide();
            $('#comment').val('');

          }

        });

      });



    }
    //点赞
    var likeEvent = function () {
      //评论点赞
      $('#list').on('click', 'li .praise', function () {
        var obj = $(this);
        if (obj.hasClass('liked')) {
          var formdata = {
            accountsId: p.empInfo.accountsId,
            moduleType: 1,
            entityId: obj.attr('id'),
            type: 1,
            userId: p.empInfo.openId
          };
          G.ajax(G.devModePost, p.params.clearLikeApi, formdata, function (retdata) {
            if (retdata.errorNo == '0') {
              obj.removeClass('liked');
              obj.find('img').attr('src', 'image/praise.png');
              var num = parseInt(obj.find('p').text()) - 1;
              obj.find('p').text(num);
            }
          });
        } else {
          var formdata = {
            accountsId: p.empInfo.accountsId,
            moduleType: 1,
            entityId: obj.attr('id'),
            type: 0,
            userId: p.empInfo.openId
          };
          G.ajax(G.devModePost, p.params.likeApi, formdata, function (retdata) {
            if (retdata.errorNo == '0') {
              obj.addClass('liked');
              obj.find('img').attr('src', 'image/praised.png');
              var num = parseInt(obj.find('p').text()) + 1;
              obj.find('p').text(num);
            }
          });
        }
      });

      //文章点赞

      $('#btn-praise').click(function () {
        var obj = $(this);
        if (obj.hasClass('praised')) {
          var formdata = {
            accountsId: p.empInfo.accountsId,
            moduleType: 0,
            entityId: cfApp.getQueryString('id'),
            type: 1,
            userId: p.empInfo.openId
          };
          G.ajax(G.devModePost, p.params.clearLikeApi, formdata, function (retdata) {
            if (retdata.errorNo == '0') {
              obj.removeClass('praised');
              obj.find('img').attr('src', 'image/praise-empty.png');
              $('#detail-praise img').attr('src', 'image/praise.png');
              var num = parseInt($('#detail-praise').find('p').text()) - 1;
              $('#detail-praise').find('p').text(num);
            }
          });
        } else {
          var formdata = {
            accountsId: p.empInfo.accountsId,
            moduleType: 0,
            entityId: cfApp.getQueryString('id'),
            type: 0,
            userId: p.empInfo.openId
          };
          G.ajax(G.devModePost, p.params.likeApi, formdata, function (retdata) {
            if (retdata.errorNo == '0') {
              obj.addClass('praised');
              obj.find('img').attr('src', 'image/praise-white.png');
              $('#detail-praise img').attr('src', 'image/praised.png');
              var num = parseInt($('#detail-praise').find('p').text()) + 1;
              $('#detail-praise').find('p').text(num);
            }
          });
        }

      });
    }

  };

  return Exhibition;
})();