<template>
    <div class="contentBo">
        <Banner></Banner>
        <div class="reg-container">
            <h3>账号注册</h3>
            <div class="box">
                <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>
                <form>
                    <div class="main" v-if="flag">
                        <p>手机号</p>
                        <input type="tel" name="" v-model="phone" maxlength="11" @input="handleTelInput"
                               @blur="checkPhone">
                        <p>密码</p>
                        <input type="password" name="" v-model="psw" minlength="6" maxlength="16" @blur="checkPsw">
                        <p>联系人</p>
                        <!-- <input type="text" name="" v-model="contact" @input="handleContInput"> -->
                        <input type="text" name="" v-model="contact" maxlength="10" @blur="handleContInput">
                        <div class="yanzm">
                            <p>图形验证码</p>
                            <input type="text" name="" v-model="picCode" @blur="checkImgCode" maxlength="4">
                            <img :src='"data:image/png;base64,"+imgCode' @click="refreshCode">
                        </div>
                        <div class="yanzm">
                            <p>短信验证码</p>
                            <!-- <input type="text" name="" v-model="msgCode" maxlength="6" @input="handleMsg"> -->
                            <input type="text" name="" v-model="msgCode" maxlength="6" @blur="cheeckMsgCode">
                            <div v-if="timerFlag" type="primary" class="getMsg disabled">{{time + 's后重新发送'}}</div>
                            <div v-else class="getMsg" @click="getMsgCode">点击获取验证码</div>

                        </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-else>
                        <p>联系邮箱</p>
                        <input type="email" name="" v-model="email" @blur="checkEmail">
                        <p>机构名称</p>
                        <input type="text" name="" v-model="agencyName" maxlength="20">
                        <div class="next" v-if="submitCor">立即注册</div>
                        <div class="next nextCor" @click="submit" v-else>立即注册</div>
                    </div>
                </form>
            </div>
        </div>
    </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'

  export default {
    name: 'Register',
    data() {
      return {
        phone: '',
        contact: '',//联系人
        agencyName: '',
        email: '',
        psw: '',
        picCode: '',//用户输入
        msgCode: '',
        imgCode: '',//流
        imgId: '',
        flag: true,//切换下一页
        changCor: true,
        submitCor: true,
        imgCodeErr: false,
        time: 60,
        timer: null,//按钮倒计时
        timerFlag: false,//倒计时标识
        complete: false, //注册进度条
        picTimer: null,//图形验证码
        picTime: 600,
        msgCodeTimer:null,//短信验证码
        msgCodeTime:180,
        codeErrText:'',
        phoneRg:null
      }
    },
    created() {
      //localStorage.removeItem('token');
      this.getPicCode();
    },
    beforeDestroy() {
      window.clearInterval(this.picTimer);
      window.clearInterval(this.msgCodeTimer);
    },
    methods: {
      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.codeErrText = "联系人只能输入中文";
          this.contact = '';
        }else{
          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);
                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.codeErrText = "图形验证码错误";
            } else {
              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.imgCodeErr = true;
            this.codeErrText = "手机格式不正确";*/
            this.phone = "";
            this.phoneRg = 1;
          }else{
            this.phoneRg = null;
            // this.imgCodeErr = false;
            api.checkTel(this.phone).then((res)=>{
              if(+res.data.code == 0){
                
              }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.codeErrText = "手机号不能为空";
          /*this.$message({
            message: '手机号不能为空',
            type: 'warning'
          });*/
        }else if(!this.psw.trim()){
          this.imgCodeErr = true;
          this.codeErrText = "密码不能为空";
        }else if(!this.contact.trim()){
          this.imgCodeErr = true;
          this.codeErrText = "联系人不能为空";
        }else if(!this.picCode.trim()){
          this.imgCodeErr = true;
          this.codeErrText = "图形验证码不能为空";
        }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 = 60;
                  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);
                }
              }, 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.codeErrText = "密码长度为6-16位";
            this.psw = "";
          }
          else if (!pswlReg.test(psw)) {
            this.imgCodeErr = true;
            this.codeErrText = "密码过于简单";
            this.psw = "";
          }else{
            this.imgCodeErr = false;
          }
        }

      },
      cheeckMsgCode(){//验证短信验证码
        const params = {
          imgCode: this.picCode,
          imgId: this.imgId,
          mobile: this.phone,
          smsCode: this.msgCode
        }
        api.vertifyMobileCode(params).then((res) => {
          // 验证成功，切换下一页
          if (+res.data.code == 0) {
            // this.flag = false;
            this.imgCodeErr = false;
          } else {
            // this.$message.error('短信验证码错误');
            this.imgCodeErr = true;
            this.codeErrText = "短信验证码错误";
            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.codeErrText = "邮箱格式不正确";
            this.email = "";
          }else{
            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.contact.trim() && val.picCode.trim() && val.msgCode.trim() && !val.imgCodeErr) {
            this.changCor = false;
          } else {
            this.changCor = true;
          }

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