<template>
  <div class="container animated swing">
    <!-- 头部logo部分 -->
    <div class="top">
      <img
        src="../../../static/imgs/doctorRegister/login-logo.png"
        alt
      />
      <p class="register-text">注册认证</p>
    </div>
    <!-- 表单部分 -->
    <div class="middle">
      <van-field
        v-model="tel"
        type="number"
        label="手机号"
        placeholder="请输入手机号"
        maxlength="11"
      />
      <van-field
        v-model="imgCode"
        label="图片码"
        class="flex-center"
        placeholder="请输入图片码"
        maxlength="4"
      >
        <template #button>
          <img
            class="auth-code-img"
            :src="authImgUrl?authImgUrl:'暂无'"
            alt
            @click="handleChangeAuthImg"
          />
        </template>
      </van-field>

      <van-field
        v-model="authCode"
        label="验证码"
        type="number"
        placeholder="请输入验证码"
        maxlength="6"
      >
        <template #button>
          <span
            v-if="!downTimeStatus"
            class="auth-code"
            @click="sendSMS"
          >获取验证码</span>
          <span v-if="downTimeStatus">
            {{downTimeNum}}s后重试
          </span>
        </template>
      </van-field>
    </div>
    <!-- 表单部分 -->
    <div class="bottom">
      <van-button
        type="info"
        round
        size="large"
        class="lj-button"
        @click="handleSubmit"
      >提交</van-button>
    </div>
  </div>
</template>

<script>
import { reqDoctorRegister, reqGetImgCode, reqSendSMS, reqVerifyCode } from '../../../api/doctorRegister/doctorRegister'
export default {
  data() {
    return {
      redirectCode: '', // 从cookie中获取的跳转code值
      // 手机号
      tel: "",
      // 图片验证码值
      imgCode: "",
      // 短信验证码
      authCode: "",
      time: "",   // 图形验证码时间戳
      authImgUrl: "",   // 图片验证码图片路径
      downTimeStatus: false,    // 是否显示短信验证码倒计时
      downTimeNum: 60,    // 短信倒计时
      id: null,    // 从好友助力页面传递过来的ID
    };
  },
  methods: {
    // 提交表单
    async handleSubmit() {
      let obj = {
        Mobile: this.tel,
        verificationCode: this.imgCode,
        MoblieCode: this.authCode
      }
      let isSuccess = this.CheckSignUpData(obj)
      if (!isSuccess.state) return this.$toast(isSuccess.msg)
      obj = {
        phone: this.tel,
        phoneCode: this.authCode,
      }
      // 发送请求校验短信验证码
      const { data: response } = await reqVerifyCode(obj)
      if (response.success != 1) {
        console.log("comming")
        this.getCode()
        return this.$toast(response.message)
      }
      this.$toast({
        message: '注册中...',
        type: 'loading',
        duration: 30000,
        forbidClick: true
      })
      const { data: result } = await reqDoctorRegister({ phone: this.tel, redirectCode:this.redirectCode })
      if (result.success !== 1) return this.$toast(result.message)
      this.$toast(result.message)
      setTimeout(() => {
        this.$toast.clear()
        window.sessionStorage.setItem('phone', this.tel)
        const redirectCode = this.getCookie('redirectCode')
        const token = this.getCookie('token')
        console.log("redirectCode：", redirectCode)
        console.log("token", token)
        // 开发环境
        const currentMode = process.env.VUE_APP_Name
        var host2 = process.env.VUE_APP_Url; 
        if(currentMode === '开发环境') {
          window.location.href= host2+`/ymallWechat/skip?redirectCode=${redirectCode}&token=${token}&id=${this.id}`
        }else if(currentMode === '测试环境') {
          window.location.href= host2+`/ymallWechat/skip?redirectCode=${redirectCode}&token=${token}&id=${this.id}`
        }else {
          window.location.href= host2+`/ymallWechat/skip?redirectCode=${redirectCode}&token=${token}&id=${this.id}`
        }
      }, 2000);
    },

    // 发送短信获取验证码
    sendSMS() {
      let obj = {
        phone: this.tel,
        imgCode: this.imgCode,
        timestamp: this.time
      }

      let isSuccess = this.CheckSignUpData(obj)
      if (!isSuccess.state) return this.$toast(isSuccess.msg)
      this.$toast({
        message: '发送中...',
        type: "loading",
        duration: 30000,
        forbidClick: true   // 禁用背景点击
      })
      reqSendSMS(obj).then(res => {
        console.log("send sms res: ", res)
        this.$toast.clear()
        if (res.data.success === 1) {
          this.$toast({
            message: res.data.message,
            type: 'success',
            duration: 2000
          })
          this.downTime()
        } else {
          this.$toast({
            message: res.data.message,
            type: 'fail',
            duration: 2000
          })
          this.getCode()
        }
      })
    },

    // 短信验证码倒计时
    downTime() {
      this.downTimeStatus = true
      let timer = setInterval(() => {
        this.downTimeNum--
        if (this.downTimeNum <= 0) {
          clearInterval(timer)
          timer = null
          this.getCode()
          this.downTimeNum = 60
          this.downTimeStatus = false
        }
      }, 1000)
    },

    // 验证注册数据
    CheckSignUpData(obj) {
      var state = { state: true, msg: "" };

      var MobileReg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      var CodeReg = /^[0-9a-zA-Z]{4}$/;
      var SMSReg = /^[0-9]{6}$/;

      if ("Mobile" in obj && !MobileReg.test(obj.Mobile)) {
        state.state = false;
        state.msg = "请输入正确的手机号";
        return state;
      }

      if ("verificationCode" in obj && !CodeReg.test(obj.verificationCode)) {
        state.state = false;
        state.msg = "图片验证码格式不正确";
        return state
      }

      if ("MoblieCode" in obj && !SMSReg.test(obj.MoblieCode)) {
        state.state = false;
        state.msg = "短信验证码格式不正确";
        return state;
      }
      return state;
    },

    // 点击后更换图片验证码
    handleChangeAuthImg() {
      this.getCode()
    },

    // 获取图片验证码
    async getCode() {
      this.time = Date.parse(new Date()) / 1000
      const { data: response } = await reqGetImgCode(this.time)
      if (response.success !== 1) return this.$toast('获取图片验证码失败!')
      this.authImgUrl = response.result.url
    }
  },
  created() {
    this.getCode()
    this.redirectCode = this.getCookie('redirectCode')
    this.$toast('欢迎进入注册页面')
    this.id = window.sessionStorage.getItem('id')
  }
};
</script>

<style lang="less" scoped>
@borderColor: #ebebeb;
@themeColor: #478bfb;
.container {
  padding: 0.5rem 0.4rem;
  height: 100vh;
}
/* 头部logo部分 */
.top {
  img {
    width: 3.5rem;
    height: 2.78rem;
    margin: 0 auto;
    display: block;
    margin: 0 auto 1rem;
  }
  .register-text {
    font-size: 0.5rem;
    color: #478bfb;
  }
}

/* 表单部分 */
.middle {
  margin-top: 1.2rem;

  .auth-code-img {
    width: 1.68rem;
    height: 0.64rem;
    border: 1px solid @themeColor;
    display: block;
  }

  /deep/.van-cell__title {
    text-align: left;
    color: #000;
    font-size: 0.3rem;
  }
}

/* 底部提交按钮 */
.bottom {
  margin-top: 1rem;
  .lj-button {
    border-radius: 0.1rem;
    background-color: #478bfb;
  }
}

.auth-code {
  color: @themeColor;
  font-size: 0.3rem;
}

.van-cell {
  border-bottom: 1px solid @borderColor;
}
</style>