<template>
    <div class="contentBo">
        <Banner></Banner>
         <div class="login-img fl"><img src="../../images/loginImg.png"/></div>
        <div :class="['reg-container', { 'box2': !flag}]">
            <!-- <h3>账号注册</h3> -->
            <div :class="['box', { 'box2': !flag}]">
                <!-- <div class="progress"> -->
                    <!-- <span class="apply">申请注册</span> -->
                    <!-- <span class="plan"></span> -->
                    <!-- <span :class="['plan plan_bg1',{'plan_bg2':complete}]"></span> -->
                    <!-- <span class="finished">完成</span> -->
                    <!-- <span :class="['finished',{'apply':complete}]">完成</span> -->
                     
                <!-- </div> -->
                <div v-if="flag" class="title-box clearfix"> <h3 class="login-title fl">注册</h3> <h4 class="num fr" @click="toLogin">登录</h4></div>
                <div v-else class="title-box clearfix"><span class="back-prev fl"><i class="el-icon-back" @click="backPrev"></i></span> <h3 class="login-title fl">其他信息</h3> <h4 class="num fr num2">2/2</h4></div>
                <form>
                    <div class="main" v-show="flag">
                        <!-- <p>手机号</p> -->
						<div class="phoneBox">
							<input type="tel" :class="[{ 'error': phoneErrText}]" name="" v-model="phone" maxlength="11" @input="handleTelInput"
                               @blur="checkPhone" placeholder="请输入手机号">
							<span class="tips" v-show="phoneErrText">{{phoneErrText}}</span>
						</div>
                        <div class="phoneBox">
                        	<input type="password" :class="[{ 'error': pswErrText}]" name="" v-model="psw" minlength="6" maxlength="16" @blur="checkPsw" placeholder="请输入密码">
							<span class="tips" v-show="pswErrText">{{pswErrText}}</span>
						</div>
                        
                        <!-- <p>密码</p> -->
                        
                        <div class="yanzm">
                            <!-- <p>图形验证码</p> -->
                            <input type="text" :class="[{ 'error': imgErrText}]" name="" v-model="picCode" @blur="checkImgCode" maxlength="4">
                            <img :src='"data:image/png;base64,"+imgCode' @click="refreshCode">
							<span class="tips" v-show="imgErrText">{{imgErrText}}</span>
                        </div>
                        <div class="yanzm">
                            <!-- <p>短信验证码</p> -->
                            <!-- <input type="text" name="" v-model="msgCode" maxlength="6" @input="handleMsg"> -->
                            <input type="text" :class="[{ 'error': SMSErrText}]" name="" v-model="msgCode" maxlength="6" @blur="cheeckMsgCode">
                            <div v-if="timerFlag" type="primary" class="getMsg disabled">{{ '再次发送('+ time+')'}}</div>
                            <div v-else class="getMsg" @click="getMsgCode">获取验证码</div>
							<span class="tips" v-show="SMSErrText">{{SMSErrText}}</span>

                        </div>
                        <!-- <span class="tips" v-show="imgCodeErr">图形验证码错误</span> -->
                        <!-- <span class="tips" v-show="imgCodeErr">{{codeErrText}}</span> -->

                        <div class="next" v-if="changCor">下一步</div>
                        <div class="next nextCor" @click="toNext" v-else>下一步</div>
                    </div>

                    <div class="main"  v-show="!flag">
                        <!-- <p>联系邮箱</p> -->
						<div class="phoneBox">
                        	<input type="email" :class="[{ 'error': emailErrText}]" name="" v-model="email" @blur="checkEmail"  placeholder="请输入联系邮箱" autocomplete="off">
							<span class="tips" v-show="emailErrText">{{emailErrText}}</span>
						</div>
                        <!-- <p>机构名称</p> -->
						<div class="phoneBox">
                        	<input type="text" :class="[{ 'error': agencyErrText}]" name="" v-model="agencyName" maxlength="20" placeholder="请输入机构名称" autocomplete="off">
							<span class="tips" v-show="agencyErrText">{{agencyErrText}}</span>
						</div>
						<div class="phoneBox">
                        	<input type="text" :class="[{ 'error': contactErrText}]" name="" v-model="contact" maxlength="10" @blur="handleContInput" placeholder="请输入联系人" autocomplete="off">
							<span class="tips" v-show="contactErrText">{{contactErrText}}</span>
						</div>
                        <!-- <p>联系人</p> -->
                        <!-- <input type="text" name="" v-model="contact" @input="handleContInput"> -->
                        <div class="next" v-if="submitCor">立即注册</div>
                        <div class="next nextCor" @click="submit" v-else>立即注册</div>
                    </div>
                </form>
            </div>
        </div>
        <copy-right-info></copy-right-info>
    </div>
</template>
<script>
  import api from '@api/index.js';
  import utils from '@api/utils.js';

  import '@components/register/register.less';
  import Banner from '@components/common/Banner.vue';
  import md5 from 'js-md5'
  import copyRightInfo from '../common/CopyRightInfo.vue';
  export default {
    name: 'Register',
    data() {
      return {
        phone: '',
        contact: '',//联系人
        agencyName: '',
        email: '',
        psw: '',
        picCode: '',//用户输入
        msgCode: '',
        imgCode: '',//流
        imgId: '',
        flag: true,//切换下一页
        changCor: true,
        submitCor: true,
        imgCodeErr: false,
        time: 180,
        timer: null,//按钮倒计时
        timerFlag: false,//倒计时标识
        complete: false, //注册进度条
        picTimer: null,//图形验证码
        picTime: 600,
        msgCodeTimer:null,//短信验证码
        msgCodeTime:180,
        codeErrText:'',
        phoneRg:null, 
        phoneErrText: '', // 手机号错误提示
        pswErrText: '', //密码错误提示
        imgErrText: '', //图像码错误信息
        SMSErrText: '', //短信验证码错误信息
        emailErrText:'', //邮箱错误信息提示
        agencyErrText: '', //机构错误信息提示
        contactErrText: '' //联系人错误信息提示
      }
    },
    created() {
      //localStorage.removeItem('token');
      this.getPicCode();
    },
    beforeDestroy() {
      window.clearInterval(this.picTimer);
      window.clearInterval(this.msgCodeTimer);
    },
    methods: {
      toLogin() {
        this.$router.push({
          path: '/'
        });
      },
      backPrev() {
        this.flag = true;
      },
      CalcuMD5(password){
        // password = password.toUpperCase();
        password = md5(password);
        return password;
      },
      handleTelInput(e) {//手机号输入验证
        this.phone = e.target.value.replace(/[^\d]/g, ''); //只能输入数字
        let firstNum = this.phone.substring(0, 1);//第一位1
        if (firstNum != 1) {
          this.phone = "";
        }
      },
      handleContInput() {//联系人--提示只能输入汉字
        // this.contact = e.target.value.replace(/[^\u4e00-\u9fa5]/g, '');
        const contactReg = new RegExp(/[^\u4e00-\u9fa5]$/g);
        // if (!contactReg.test(this.contact)) {
        if (contactReg.test(this.contact)) {
          /*this.$message({
            message: '联系人只能输入中文',
            type: 'warning'
          });*/
          this.imgCodeErr = true;
          this.contactErrText = "联系人只能输入中文";
          this.contact = '';
        }else{
		this.contactErrText = "";
          this.imgCodeErr = false;
        }
      },
      handleMsg(e) {//短信验证码输入验证
        this.phone = e.target.value.replace(/[^\d]{6}/g, '');
      },
      getPicCode() {//获取图形验证码
        api.getImgCode().then((res) => {
          if (+res.data.code == 0) {
            const imgCodeInfo = res.data.data;
            this.imgCode = imgCodeInfo.imgByte;
            this.imgId = imgCodeInfo.imgId;

            let that = this;
            this.picTimer = window.setInterval(() => {
              if ((that.picTime--) <= 0) {
                this.$message({
                  message: '图形验证码已过期',
                  type: 'warning'
                });
                that.picCode = '';
                that.picTime = 600//图形验证码过期时间10分钟;
                window.clearInterval(that.picTimer);
                this.picTimer = null
                that.getPicCode();//过期刷新验证码
              }
            }, 1000);

          } else {
            console.log(res.data.msg);
          }
        }).catch((err) => {
          console.log(err);
        })
      },
      refreshCode() {//刷新图形验证码
        window.clearInterval(this.picTimer);
        this.picTime = 600//图形验证码过期时间10分钟;
        this.getPicCode();
      },
      checkImgCode() {//验证图片验证码
        if (this.picCode) {
          const params = {
            imgCode: this.picCode,
            imgId: this.imgId
          }
          api.vertifyImgCode(params).then((res) => {
            if (+res.data.code != 0) {//验证失败
              this.imgCodeErr = true
              this.imgErrText = "图形验证码错误";
            } else {
			  this.imgErrText = "";
              this.imgCodeErr = false
            }
          }).catch((err) => {
            console.log(err);
          })
        }

      },
      checkPhone() {//验证手机号
        // const reg = new RegExp(/^((13|14|15|16|17|18|19)\d{9})$/);
        const reg = utils.phoneReg;
        if(this.phone.trim()){
          if (!reg.test(this.phone)) {
            // this.$message({
            //   message: '手机格式不正确',
            //   type: 'warning'
			// });
			this.phoneErrText = '手机号格式有误'
          
            this.phone = "";
            this.phoneRg = 1;
          }else{
            this.phoneRg = null;
            // this.imgCodeErr = false;
            api.checkTel(this.phone).then((res)=>{
              if(+res.data.code == 0){
                this.phoneErrText = ''
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'warning'
                });
                this.phone = "";
              }
            })
          }
        }else{
          /*this.$message({
            message: '手机号不能为空',
            type: 'warning'
          });*/
        }
      },
      getMsgCode() {//获取短信验证码
        //手机号、密码、联系人、图形验证码不为空且符合规则且图形验证码正确--shenq10.26
        if(!this.phone.trim() && !this.phoneRg){
          this.imgCodeErr = true;
          this.phoneErrText = "手机号不能为空";
          /*this.$message({
            message: '手机号不能为空',
            type: 'warning'
          });*/
        }else if(!this.psw.trim()){
          this.imgCodeErr = true;
          this.pswErrText = "密码不能为空";
        }else if(!this.picCode.trim()){
          this.imgCodeErr = true;
          this.imgErrText = "图形验证码不能为空";
        }else{//调请求接口
          this.imgCodeErr = false;
          const params = {
            imgCode: this.picCode,
            imgId: this.imgId,
            mobile: this.phone
          }
          api.getMobileCode(params).then((res) => {
            if (+res.data.code == 0) {

              this.$message({
                message: '验证码发送成功',
                type: 'success'
              });

              //按钮倒计时
              this.timerFlag = true;
              let that = this;
              this.timer = window.setInterval(() => {
                if ((that.time--) <= 0) {
                  that.time = 180;
                  that.timerFlag = false;
                  window.clearInterval(that.timer);
                }
              }, 1000)


              //短信验证码180s过期时间
              this.msgCodeTimer = window.setInterval(() => {
                if ((that.msgCodeTime--) <= 0) {
                  this.$message({
                    message: '短信验证码已过期，请重新获取',
                    type: 'warning'
                  });
                  that.msgCode = '';
                  that.msgCodeTime = 180;
                  window.clearInterval(that.msgCodeTimer);
                  that.msgCodeTimer = null;
                }
              }, 1000);


            } else {
              console.log(res.data);
              this.$message({
                message: res.data.msg,
                type: 'warning'
              });
              // return
            }
          }).catch((err) => {
            console.log(err);
          })
        }

        

      },
      checkPsw() {//校验密码
        const pswlReg = utils.pswReg;
        const psw = this.psw;
        if (psw) {
          if (psw.trim().length < 6 || psw.trim().length > 16) {
            this.imgCodeErr = true;
            this.pswErrText = "密码长度为6-16位";
            this.psw = "";
          }
          else if (!pswlReg.test(psw)) {
            this.imgCodeErr = true;
            this.pswErrText = "密码过于简单";
            this.psw = "";
          }else{
            this.pswErrText = "";
            this.imgCodeErr = false;
            console.log()
          }
        }

      },
      cheeckMsgCode(){//验证短信验证码
        const params = {
          imgCode: this.picCode,
          imgId: this.imgId,
          mobile: this.phone,
          smsCode: this.msgCode
        }
        if(!this.msgCode.trim()) {
          return
        }
        api.vertifyMobileCode(params).then((res) => {
          // 验证成功，切换下一页
          if (+res.data.code == 0) {
            // this.flag = false;
            this.imgCodeErr = false;
          } else {
            // this.$message.error('短信验证码错误');
            this.imgCodeErr = true;
            this.SMSErrText = "短信验证码错误";
            this.msgCode = "";
          }
        }).catch((err) => {
          console.log(err);
        })
      },
      toNext() {
        this.flag = false;
      },
      checkEmail() {
        const emailReg = utils.emailReg;
        const email = this.email;
        if (email.trim()) {
          if (!emailReg.test(email)) {
          //   this.$message({
          //     message: '邮箱格式不正确',
          //     type: 'warning'
          //   });

            this.imgCodeErr = true;
            this.emailErrText = "邮箱格式不正确";
            this.email = "";
          }else{
			this.emailErrText = "";
            this.imgCodeErr = false;
          }
        }
      },
      submit() {
        //清除图形验证码定时器
        const mdPsw = this.CalcuMD5(this.psw);
        const params = {
          code: this.picCode,
          email: this.email,
          gmtCreate: '',
          gmtModified: '',
          id: 0,
          imgId: this.imgId,
          isDeleted: '',
          linkman: this.contact,
          modifier: '',
          organization: this.agencyName,
          // password: this.psw,
          password: mdPsw,
          username: this.phone
        }

        api.regidtry(params).then((res) => {
          if (+res.data.code == 0) {
            this.$message({
              message: '恭喜您，注册成功！',
              type: 'success'
            });
            //注册成功，跳转登录
            this.$router.push({path: '/'})
          } else {
            this.submitCor = true;//注册失败,按钮变灰
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        }).catch((err) => {
          console.log(err);
        })
      },

    },
    computed: {
      nextButton() {
        const {phone, psw, contact, picCode, msgCode, email, agencyName,imgCodeErr} = this;
        return {
          phone,
          psw,
          contact,
          picCode,
          msgCode,
          email,
          agencyName,
          imgCodeErr
        }
      }
    },
    watch: {
      nextButton: {
        handler: function (val) {//所有数据不为空，且手机格式正确、图形验证码正确
          if (val.phone.trim() && val.psw.trim() && val.picCode.trim() && val.msgCode.trim() && !val.imgCodeErr) {
            this.changCor = false;
          } else {
            this.changCor = true;
          }

          if (val.email.trim() && val.agencyName.trim() && val.contact.trim()) {
            this.submitCor = false;
            this.complete = true;//完成
          } else {
            this.submitCor = true
          }
        },
        deep: true
      }
    },
    filters: {},
    components: {
      Banner,
      copyRightInfo
    },
  }
</script>
