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/member/register',
      postCodeApi: G.baseUri() + '/mobile/auth/member/searchCode',
      vt: ''
    };

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

    if (p.params.devMode) {
      p.params.dataApi = 'json/code.json';
      p.params.postCodeApi = 'json/code.json';

    }


    var serverId;

    /**
     * 判断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();

        $('#company').val(cfApp.getQueryString('company'));
        $('#lastName').val(cfApp.getQueryString('surname'));
        $('#firstName').val(cfApp.getQueryString('name'));
        gender();
        uploadCard();
        getCode();
        agreement();
        submit();
        

        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 sex = cfApp.getQueryString('sex');
    if(sex == '女'){
      $('.gender #man').removeClass('choose');
      $('.gender #woman').addClass('choose');
    }
    //选择性别
    var gender = function () {
      $('.gender>div').click(function () {
        $('.gender>div').removeClass('choose');
        $(this).addClass('choose');
      });
    }
    //上传图片
    var uploadCard = function () {

      $('#upload').click(function () {
        var localIds;

        wx.chooseImage({
          count: 1, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            alert(res.localIds.toString());
            localIds = res.localIds.toString(); // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            wx.uploadImage({
              localId: localIds, // 需要上传的图片的本地ID，由chooseImage接口获得
              isShowProgressTips: 1, // 默认为1，显示进度提示
              success: function (res) {
                serverId = res.serverId; // 返回图片的服务器端ID
                $('#upload img').attr('src', localIds);
                $('#upload img').show();
                $("#upload .card-show").css("opacity","1");
              }
            });
          }
        });
      });

    }
    //获取验证码
    var getCode = function () {
      $('#getCode').click(function () {
        var phone = $('#phone').val();
        if (StringValidateUtils.isEmpty(phone)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入手机号！</span><br>Please input the<br>phone number',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        if (!StringValidateUtils.validMobile(phone)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入正确的手机号！</span><br>Please input the<br>correct phone number',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var formdata = {
          accountsId: p.params.accountsId,
          phone: phone
        };
        G.ajax(G.devModePost, p.params.postCodeApi, formdata, function (retdata) {
          if (retdata.errorNo == '0') {
            $.toast('验证码发送成功</br><span class="f12">The verification code was sent successfully</span>', "text");
          } else if (retdata.errorNo == '1') {
            $.toast('获取验证码异常</br><span class="f12">Gets the verification code exception</span>', "text");
          }
          var time = 60;
          $('#getCode').html((time--) + 's');
          $('#getCode').addClass('disable');
          var t = setInterval(function () {
            $('#getCode').html(time + 's');
            time--;
            if (time < -1) {
              $('#getCode').html('获取Receive');
              $('#getCode').removeClass('disable');
              window.clearInterval(t);
            }
          }, 1000);
        })
      });
    }

    var agreement=function(){
      $('#showAgreement').click(function(){
        $('#agreement-content').show();
        $('#maincontent').hide();
      });
      $('#return').click(function(){
        $('#agreement-content').hide();
        $('#maincontent').show();
      });

      $('#agreement').click(function(){
        $(this).toggleClass('choose');
      })
    }
    //提交注册
    var submit = function () {
      $('#submit').click(function () {

        var lastName = $('#lastName').val();
        if (StringValidateUtils.isEmpty(lastName)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入您的姓氏！</span><br>Please input the<br>last name',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;

        }
        var firstName = $('#firstName').val();
        if (StringValidateUtils.isEmpty(firstName)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入您的名字！</span><br>Please input the<br>first name',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var index = $('.gender .choose').index();
        var sex;
        if (index == 0) {
          sex = 1
        } else {
          sex = 0
        };

        var company = $('#company').val();
        if (StringValidateUtils.isEmpty(company)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入您的公司！</span><br>Please input the<br>company',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        var phone = $('#phone').val();
        /*if (StringValidateUtils.isEmpty(phone)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入手机号！</span><br>Please input the<br>phone number',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        if (!StringValidateUtils.validMobile(phone)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入正确的手机号！</span><br>Please input the<br>correct phone number',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }*/
        /*var code = $('#code').val();
        if (StringValidateUtils.isEmpty(code)) {
          $.modal({
            title: "",
            text: '<span class="color-green">请输入验证码！</span><br>Please input the<br>verification code',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }*/

        if(!$('#agreement').hasClass('choose')){
          $.modal({
            title: "",
            text: '<span class="color-green">请同意用户协议！</span><br>Please agree to</br>the user agreement',
            buttons: [{
              text: "确定OK"
            }]
          });
          return false;
        }
        $("#submit").css("pointer-events","none");
        var formdata = {
          accountsId: p.params.accountsId,
          code: null,
          phone: phone,
          openId: p.params.openId,
          name: firstName,
          surname: lastName,
          sex: sex,
          compan:company,
          storeid: serverId,
          invitcode: cfApp.getQueryString('invitcode'),
          imageurl:p.empInfo.imageUrl
        }
        G.ajax(G.devModePost, p.params.dataApi, formdata, function (retdata) {
            $("#submit").css("pointer-events","inherit");
          //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(){
                  localStorage.clear();
                  location.href='meeting-intro.html?appid='+p.params.appid+'&invitcode='+cfApp.getQueryString("invitcode")+"&id="+cfApp.getQueryString('id');
                  //location.href='personCenter.html?appid='+p.params.appid;
                }
              }]
            });
          } 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;
})();