<script setup>
import { reactive, ref } from 'vue';
import {ElMessage} from 'element-plus'
import { useRouter } from 'vue-router';
import {registerApi} from '@/api/auth.js'
import md5 from 'md5'
// passwordDigitValidator-密码6位
import { passwordDigitValidator } from './utils/validators';
import { sendVerificationCode } from './utils/common';

  const router = useRouter()

  const registerRef = ref(null)
  
  // 隐私政策是否阅读
  const hasChecked=ref(false)
  const register=reactive({
    form:{
      userName:'',
      companyName:'',
      email:'',
      password:'',
      passwordConfirm:'',
      verificationCode:''
    },
    rules:{
      userName:{required: true, message:'User name cannot be null', trigger: 'blur'},
      companyName:{required: true, message:'Company name cannot be null', trigger: 'blur'},
      email:[{required: true, message:'Email address cannot be null', trigger: 'blur'},
      {type:'email',message:'Email address format is incorrect', trigger: 'blur'}],
      password:[{required: true, message:'Password cannot be null', trigger: 'blur'},
      {
        // 密码6位检验
        validator:passwordDigitValidator,trigger:'blur'
      }],
      passwordConfirm:[{required: true, message:'Password cannot be null', trigger: 'blur'},
      {validator:(rule,value,callback)=>{
        if(register.form.passwordConfirm!==register.form.password){
          callback(new Error('Passwords do not match'))
        }else{
          callback()
        }
      }, trigger: 'blur'}],
      verificationCode:{required: true, message:'Verification code cannot be null', trigger: 'blur'}
    }
  })

  const codeInfo=reactive({
    timeout:0,// 秒
    isRequesting:false
  })

// ----------------------------------------------------方法

  const sendVerCode=()=>{
    registerRef.value.validateField(['userName','email']).then(res=>{
      let codeParams={
        Name:register.form.userName,
        Email:register.form.email
      }
      sendVerificationCode(codeParams,1,codeInfo)
    }).catch(err=>{
      let errMessage=''
      errMessage=err.userName?err.userName[0].message:
                  err.email?err.email[0].message:''
      if(errMessage){
        ElMessage.warning(errMessage)
      }
    })
  }
  // 移动端的注册 在登录页面
  const registerSubmit=()=>{
    registerRef.value.validate(valid=>{
      if(valid){
        // if(!hasChecked.value){
        //   ElMessage.warning('Please check the Privacy policy')
        //   return
        // }
        let params={
          CompanyName:register.form.companyName,
          Name:register.form.userName,
          Email:register.form.email,
          SmsCode:register.form.verificationCode,
          Password:md5(register.form.password)
        }
        registerApi(params).then(res=>{
          if(res.code == 200){
            localStorage.setItem('yben_token',res.data.access_token)
            let userInfo = {
              user_id:res.data.user_id,
              Name:res.data.Name,
              Email:res.data.Email,
              Mobile:res.data.Mobile,
              CountryCode:res.data.CountryCode
            }
            localStorage.setItem('user_info',JSON.stringify(userInfo))
            sessionStorage.setItem('transitionPageMessage','register')
            router.replace('/transitionPage')
          }
        })
      }
    })
  }
  const loginPageGo=()=>{
    let {href} = router.resolve("/login");
    window.open(href,'_blank');
  }

  const privacyPolicy=()=>{
    //TODO 去查看隐私政策
  }

</script>

<template>
    <div class="register-container">
      <div class="fixed-header">
        <span>
          HORIZON INSIGHTS
        </span>
      </div>
      <div class="page-title">
        Create account
      </div>
      <div class="regitser-form-box" id="regitser-form-box">
        <el-form :model="register.form" :rules="register.rules" ref="registerRef">
          <el-form-item prop="userName">
            <el-input v-model="register.form.userName" size="large" placeholder="Enter your name"></el-input>
          </el-form-item>
          <el-form-item prop="companyName">
            <el-input v-model="register.form.companyName" size="large" placeholder="Enter a company name"></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input v-model="register.form.email" size="large" placeholder="Enter email address">
              <template #suffix>
                <span style=" color: var(--el-color-primary);cursor: pointer;white-space: nowrap;" 
                @click="sendVerCode" v-if="!codeInfo.isRequesting">Get verification code</span>
                <span style=" color: #999999;white-space: nowrap;" v-else>{{ codeInfo.timeout }}s</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="verificationCode" >
            <el-input v-model.trim="register.form.verificationCode" size="large" placeholder="Enter code received"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="register.form.password" size="large" type="password" placeholder="At least 6 digits"></el-input>
          </el-form-item>
          <el-form-item prop="passwordConfirm" style="margin-bottom: 0;">
            <el-input v-model.trim="register.form.passwordConfirm" size="large" type="password" placeholder="Re-enter your password"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="registerSubmit" class="register-button" size="large">Submit</el-button>
        <div class="login-row">Existing account <span @click="loginPageGo">Log in instead</span></div>
        <!-- <div class="privacy-policy">
          <el-checkbox v-model="hasChecked" label="I have read and agree" style="color:#333333"></el-checkbox>
          <span @click="privacyPolicy" class="policy">the Horizon Insights Privacy Policy</span>
        </div> -->
        <div class="question-hint">For technical assistance, please contact stephanie@hzinsights.com</div>
      </div>
    </div>
</template>
  
<style lang="scss" scoped> 
  .register-container{
    padding-top: 68px;
    .page-title{
      text-align: center;
      font-weight: 600;
      font-size: 20px;
      line-height: 28px;
      color: #1856A7;
      padding: 56px 0 48px;
    }
    .regitser-form-box{
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      .register-button{
        margin-top: 40px;
        width: 100%;
        width: 360px;
        background-color: #1856A7;
      }
      .login-row{
        font-weight: 400;
        font-size: 14px;
        line-height: 20px;
        color: #333333;
        margin: 20px 0 30px;
        span{
          color: #1856A7;
          cursor: pointer;
          margin-left: 12px;
        }
      }
      .privacy-policy{
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        .policy{
          color: #1856A7;
          cursor: pointer;
          margin-left: 12px;
        }
      }
      .question-hint{
        font-weight: 400;
        font-size: 14px;
        line-height: 20px;
        color: #999999;
      }
    }
  }
</style>
<style lang="scss">
  #regitser-form-box{
    .el-input,.el-input__wrapper{
      width: 360px;
    }
  }
</style>