var activityAgenda = (function () {
  'use strict';
  var ActivityAgenda = function (params) {
    var p = this;
    p.params = {
      appid: '',
      accountsId: '',
      cfApp: null,
      devMode: false,
      dataApi: G.baseUri() + '/mobile/auth/agenda/getagenda',
      chooseDateApi: G.baseUri() + '/mobile/auth/agenda/selectagendacustomiz',
      chooseRoomApi: G.baseUri() + '/mobile/auth/agenda/clickcustomizagenda',
      postApi: G.baseUri() + '/mobile/auth/agenda/inseragendasroe',
      clickspeech: G.baseUri() + '/mobile/auth/speech/getspeechdetails',
      vt: ''
    };

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

    if (p.params.devMode) {
      p.params.dataApi = 'json/agenda-special.json';
      p.params.chooseDateApi = 'json/agenda-date.json';
      p.params.chooseRoomApi = 'json/choose-room.json';
      p.params.clickspeech = 'json/guest-information.json';

      p.params.postApi = 'json/code.json';

    }
    p.pageNo = 0;
    p.loading = false;
    p.agenda_time = '';
    p.english = cfApp.getQueryString('english') == 1 ? true : false;
    var weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    var enWeeks=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    console.log(p.english);
    Handlebars.registerHelper({
      'datapost': function (t) {
        var date = new Date(t);
        return dataUtils.dateFormat(date, 'yyyy-MM-dd');

      },
      'datetimeformat': function (t) {
        var date = new Date(t);

        if(p.english){
          return dataUtils.dateFormat(date, 'MM-dd') ;
        }else{
          return dataUtils.dateFormat(date, 'MM-dd') + '（' + weeks[date.getDay()] + '）';
        }
        

      },
      'scoreHtml': function (s) {

        if (s == 1) {
          var html = '<img src="image/star-green.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '</div>' +
            '<p class="color-green">1.0</p>';

        } else if (s == 2) {
          var html = '<div class="stars align-center">' + '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '</div>' +
            '<p class="color-green">2.0</p>';

        } else if (s == 3) {
          var html = '<div class="stars align-center">' + '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '</div>' +
            '<p class="color-green">3.0</p>';

        } else if (s == 4) {
          var html = '<div class="stars align-center">' + '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '</div>' +
            '<p class="color-green">4.0</p>';

        } else if (s == 5) {
          var html = '<div class="stars align-center">' + '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '<img src="image/star-green.png" alt="">' +
            '</div>' +
            '<p class="color-green">5.0</p>';

        } else if (!s || s == '') {
          var html = '<div class="stars align-center">' + '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '<img src="image/star.png" alt="">' +
            '</div>' +
            '<p class="color-green">0.0</p>';
        }
        return html
      },
      'isScore': function (s) {
        if (!s || s == '') {
          return 'noscored';
        }

      }
    });
    /**
     * 判断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: '0',
          cfApp: cfApp
        });
        sideDiv.init();

        var modal = cfApp.getQueryString('modal');
        if (modal == 1) {
          $.modal({
            title: "",
            text: '<span style="color:#000">请及时提交个人行程！</span>',
            buttons: [{
                text: "暂不",
                className: "leftBtn"
              },
              {
                text: "前往",
                onClick: function () {
                  if (p.english) {
                    location.href = 'my-schedule-form-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
                  } else {
                    location.href = 'my-schedule-form.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
                  }

                }
              }
            ]
          });
        }
        log();
        loadData();
        initInfinite();
        StarEvent();
        //submit();

        $('.language').click(function () {
          if (!p.english) {
            location.href = 'agenda-special-english.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id') + '&english=1';
          } else {
            location.href = 'agenda-special.html?appid=' + p.params.appid + '&id=' + cfApp.getQueryString('id');
          }

        });




          $('#list').on('click', '.agenda-list li span', function () {
            var obj = this;
           /* var formdata = {
              member_uid: p.empInfo.memberId,
              id: $(obj).attr("data-speech"),
              accountsId: p.empInfo.accountsId
            };
            G.ajax('get',p.params.clickspeech,formdata,function(retdata){
              $.hideLoading();
              if(retdata.errorNo == '0'){

              }
            })*/

            if(p.english){
              location.href = 'guest-information-english.html?appid=' + p.params.appid+'&id='+cfApp.getQueryString('id')+'&speechId='+$(obj).attr("data-speech")+"&english=1";
            }else{
              location.href = 'guest-information.html?appid=' + p.params.appid+'&id='+cfApp.getQueryString('id')+'&speechId='+$(obj).attr("data-speech");
            }
          })


        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 () {
      if(p.english){
        $.showLoading("Loading");
      }else{
        $.showLoading();
      }

      var formdata = {
        meetingId: cfApp.getQueryString('id'),
        page: 0,
        pagesize: 0,
        member_uid: p.empInfo.memberId,
        type: 1 //0正常，1定制
      };
      G.ajax('get', p.params.dataApi, formdata, function (retdata) {
        $.hideLoading();
        if (retdata.errorNo == '3') {
          if (p.english) {
            $('#title').text(retdata.workshop_title_en);
          } else {
            $('#title').text(retdata.workshop_title);
          }

          initDate(retdata.data);
          if (retdata.data.length > 0) {
            var date = new Date(retdata.data[0].agenda_time);
            p.agenda_time = dataUtils.dateFormat(date, 'yyyy-MM-dd');
            $('#date .swiper-slide:first-child').addClass('choose');
            loadRoom();
          }

          chooseDate();
          chooseRoom();

          // for (var i = 0, j = retdata.agenda.length; i < j; i++) {
          //   for (var m = 0, n = retdata.data.length; m < n; m++) {
          //     if (retdata.agenda[i].id == retdata.data[m].id) {
          //       retdata.agenda[i].score = retdata.data[m].score
          //     }
          //   }
          // }
          // console.log(retdata)
          // 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 initDate = function (data) {

      var content = $('#slide-template').html();
      p.template = Handlebars.compile(content);
      var htmlStr = p.template(data);
      //$('.content').append(htmlStr);
      $(htmlStr).insertAfter('#title');
      var mySwiper = new Swiper('.swiper-container', {
        slidesPerView: 3,

        spaceBetween: 10,
      });

    }

    var loadRoom = function () {

      var formdata = {
        meetingId: cfApp.getQueryString('id'),
        page: p.pageNo,
        pagesize: 10,
        agenda_time: p.agenda_time,

      };
      G.ajax('get', p.params.chooseDateApi, formdata, function (retdata) {

        if (retdata.errorNo == '0') {


          var content = $('#room-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;
          }

        }else{
          return;
        }

      });

    }
    var chooseDate = function () {


      $('#date .swiper-slide').click(function () {
        $('#date .swiper-slide').removeClass('choose');
        $(this).addClass('choose');
        p.pageNo = 0;
        p.agenda_time = $(this).attr('data-time');
        $('#list').html('');
        loadRoom();
      });
    }

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

        setTimeout(function () {

          loadRoom();

        }, 800);
      });
    };






    var chooseRoom = function () {

      $('.content').on('click', '.item-form', function () {
        var obj = $(this);
        if (obj.next('ul').find('li').length > 0) {
          var triangel = obj.find('.triangle');
          if (triangel.hasClass('up')) {
            triangel.removeClass('up');
            obj.next('ul').hide();
          } else {
            triangel.addClass('up');
            obj.next('ul').show();
          }
        } else {
          var id = obj.attr('id'); //会场id
          var ids = obj.attr('data-title'); //会议
          var formdata = {
            agenda_id: id,
            ids:ids,
            meetingId: cfApp.getQueryString('id'),
            member_uid: p.empInfo.memberId,
            agenda_time:p.agenda_time
          }

          G.ajax('get', p.params.chooseRoomApi, formdata, function (retdata) {

            if (retdata.errorNo == '0') {
              for(var k=0;k<retdata.data.length;k++){
                var id = retdata.data[k].id;
                for (var i=0; i< retdata.score1.length;  i++) {
                  if (retdata.score1[i].id == id) {
                    retdata.data[k].score = retdata.score1[i].score
                  }
                }
                  retdata.data[k].isSpeech=false;//是否显示演讲嘉宾
                  if(!retdata.data[k].speech_name|| retdata.data[k].speech_name==null || retdata.data[k].speech_name==""){
                      retdata.data[k].isSpeech=true;
                  }
                  retdata.data[k].agenda_title=retdata.data[k].agenda_title.replace("&amp;","&");
                  retdata.data[k].agenda_title_en=retdata.data[k].agenda_title_en.replace("&amp;","&");

              }
              var content = $('#list-template').html();
              p.template = Handlebars.compile(content);
              var htmlStr = p.template(retdata);
              obj.find('.triangle').addClass('up');
              obj.next('ul').append(htmlStr);
              //var id = retdata.data.id;



            }

          });

        }


      });

    }
    var StarEvent = function () {

      $('body').on('click', '.stars img', function () {
        //$.showLoading();
        var obj = $(this);
        var index = obj.index();
        console.log(index);
        obj.attr('src', 'image/star-green.png');
        obj.prevAll('img').attr('src', 'image/star-green.png');
        obj.nextAll('img').attr('src', 'image/star.png');
        
        obj.parent('.stars').next('p').text((index + 1) + '.0');
        // obj.parents('li').attr('data-score', (index + 1));
        // obj.parents('li').removeClass('noscored');
        // obj.parents('li').addClass('changed');



        var agendascore = {

          accountsid: p.empInfo.accountsId,
          member_uid: p.empInfo.memberId,
          scroe: ""
        }
        var scoreArr = [];
        
          var data = new Object;
          //var scroe = $(this).attr('data-score');
          var id = obj.parents('li').attr('id');
          data.agenda_id = id;
          data.scroe = index+1;
          scoreArr.push(data);


          agendascore.scroe = JSON.stringify(scoreArr);
          agendascore = JSON.stringify(agendascore);

          var formdata = {
            agendascore: agendascore
          }

       
          G.ajax(G.devModePost, p.params.postApi, formdata, function (retdata) {
            if (retdata.errorNo == '0') {
              /*$.modal({
                title: "",
                text: '<span class="color-green">提交成功！</span><br>Success',
                buttons: [{
                  text: "确定OK"
                }]
              });*/
              return;
            }
          })



      });
    }



  };

  return ActivityAgenda;
})();
