<script setup>
import { reactive, ref } from 'vue';
import {ElMessage} from 'element-plus'
import { useRouter } from 'vue-router';
import {CaretBottom} from '@element-plus/icons-vue'
import {psdMissingApi} from '@/api/auth.js'
import md5 from 'md5';
import { passwordDigitValidator,phoneNoValidator } from './utils/validators';
import { TEL_CODE_ARR } from '../../utils/constant';
import { sendVerificationCode } from './utils/common';
import { isMobile } from '../../utils/common';

  const router = useRouter()

  const psdMissingRef = ref(null)
  const psdMissingMobileRef = ref(null)

  const psdMissing=reactive({
    form:{
      email:'',
      phone:'',
      phonePre:'86',
      password:'',
      passwordConfirm:'',
      verificationCode:''
    },
    rules:{
      email:[{required: true, message:'Email address cannot be null', trigger: 'blur'},
      {type:'email',message:'Email address format is incorrect', trigger: 'blur'}],
      phone:[{required: true,message:'Mobile phone No. cannot be null', trigger: 'blur'},
      {validator:phoneNoValidator, trigger: 'blur'}],
      password:[{required: true, message:'Password cannot be null', trigger: 'blur'},
      {validator:passwordDigitValidator,trigger:'blur'}],
      passwordConfirm:[{required: true, message:'Password cannot be null', trigger: 'blur'},
      {validator:(rule,value,callback)=>{
        if(psdMissing.form.passwordConfirm!==psdMissing.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 loginType=ref(1)
const changeLoginType=(type)=>{
  if(type == loginType.value) return 
  loginType.value=type
  // 重置数据
  psdMissing.form={
    email:'',
    phone:'',
    phonePre:'86',
    password:'',
    passwordConfirm:'',
    verificationCode:''
  }
  
  codeInfo.isRequesting=false
  let refTemp;
  if(isMobile()){
    refTemp=psdMissingMobileRef.value
  }else{
    refTemp=psdMissingRef.value
  }
  refTemp.clearValidate()
}

  const sendVerCode=()=>{
    let refTemp = ''
    if(isMobile()){
      refTemp=psdMissingMobileRef.value
    }else{
      refTemp=psdMissingRef.value
    }
    refTemp.validateField(['phone','email']).then(async res=>{
      // let resp=''
      let params={}
      // 邮箱验证
      if(loginType.value==1){
        params={
          Name:psdMissing.form.userName||'',
          Email:psdMissing.form.email
        }
      }else{
        params={
          Mobile:psdMissing.form.phone,
          AreaNum:psdMissing.form.phonePre ||'86'
        }
      }

      sendVerificationCode(params,loginType.value,codeInfo)

    }).catch(err=>{
      let errMessage=''
      errMessage=err.phone?err.phone[0].message:
                  err.email?err.email[0].message:''
      if(errMessage){
        ElMessage.warning(errMessage)
      }
    })
  }

  const psdMissingSubmit=()=>{
    let refTemp = ''
    if(isMobile()){
      refTemp=psdMissingMobileRef.value
    }else{
      refTemp=psdMissingRef.value
    }
    refTemp.validate(valid=>{
      if(valid){
        let params={
          CountryCode:loginType.value==1?undefined:psdMissing.form.phonePre,
          type:loginType.value,
          Account:loginType.value==1?psdMissing.form.email:psdMissing.form.phone,
          Password:md5(psdMissing.form.password),
          SmsCode:psdMissing.form.verificationCode
        }
        psdMissingApi(params).then(res=>{
          if(res.code==200){
            ElMessage({
              message: 'Modified successfully',
              type: 'success',
              duration:1000
            })
            setTimeout(()=>{
              localStorage.removeItem('yben_token')
              localStorage.removeItem('user_info')
              router.replace('/login')
            },1000)
          }
        })
      }
    })
  }
  const loginPageGo=()=>{
    let {href} = router.resolve("/login");
    window.open(href,'_blank');
  }

</script>

<template>
    <div class="psdMissing-container">
      <div class="fixed-header">
        <span>
          HORIZON INSIGHTS
        </span>
      </div>
      <div class="login-type-tab">
        <span :class="loginType==1?'active-tab':''" @click="changeLoginType(1)">Email verification</span>
        <div class="tab-split"></div>
        <span :class="loginType==2?'active-tab':''" @click="changeLoginType(2)">Phone number verification</span>
      </div>
      <div class="regitser-form-box" id="regitser-form-box">
        <!-- PC端表单 -->
        <el-form :model="psdMissing.form" class="missing-psd-form" :rules="psdMissing.rules" ref="psdMissingRef">
          <el-form-item prop="phone" v-if="loginType==2">
            <div class="phone-item">
              <el-select v-model="psdMissing.form.phonePre" size="large" style="max-width: 90px;margin-right: 10px;" placeholder="Please select">
                <el-option :label="item.label" :value="item.value" v-for="item in TEL_CODE_ARR" />
              </el-select>
              <el-input v-model.trim="psdMissing.form.phone" size="large" style="flex-grow: 1;height: 40px;" placeholder="Enter phone number">
                <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>
            </div>
          </el-form-item>
          <el-form-item prop="email" v-else>
            <el-input v-model="psdMissing.form.email" size="large" style="height: 40px;" placeholder="Enter email address" class="form-item">
              <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="psdMissing.form.verificationCode" size="large" placeholder="Enter code received" class="form-item"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="psdMissing.form.password" size="large" type="password" placeholder="At least 6 digits" class="form-item"></el-input>
          </el-form-item>
          <el-form-item prop="passwordConfirm" style="margin-bottom: 0;">
            <el-input v-model="psdMissing.form.passwordConfirm" size="large" type="password" placeholder="Re-enter your password" class="form-item"></el-input>
          </el-form-item>
        </el-form>
        <!-- 移动端表单 -->
        <el-form :model="psdMissing.form" class="mobile-missing-psd-form" id="mobile-form-field"
        label-position="top" :rules="psdMissing.rules" ref="psdMissingMobileRef" hide-required-asterisk>
          <el-form-item prop="phone" v-if="loginType==2" size="large">
            <template #label>
              <span style="margin-right: 10px;">Area Code</span>
              <el-select v-model="psdMissing.form.phonePre" :suffix-icon="CaretBottom"
              style="max-width: 55px;" placeholder="Please select" size="large">
                <el-option :label="item.label" :value="item.value" v-for="item in TEL_CODE_ARR" />
              </el-select>
            </template>
            <el-input v-model.trim="psdMissing.form.phone" size="large" style="flex-grow: 1;height: 40px;" placeholder="Enter phone number">
              <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="email" v-else label="Email Address" size="large">
            <el-input v-model="psdMissing.form.email" size="large" style="height: 40px;" placeholder="Enter email address" class="form-item">
              <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" size="large" label="Verification Code">
            <el-input v-model="psdMissing.form.verificationCode" size="large" placeholder="Enter code received" class="form-item"></el-input>
          </el-form-item>
          <el-form-item prop="password" size="large" label="Password">
            <el-input v-model="psdMissing.form.password" size="large" type="password" placeholder="At least 6 digits" class="form-item"></el-input>
          </el-form-item>
          <el-form-item prop="passwordConfirm" style="margin-bottom: 0;" size="large" label="Password">
            <el-input v-model="psdMissing.form.passwordConfirm" size="large" type="password" placeholder="Re-enter your password" class="form-item"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="psdMissingSubmit" class="psdMissing-button" size="large">Submit</el-button>
        <div class="login-row">Remember your password? <span @click="loginPageGo">Log in instead</span></div>
      </div>
    </div>
</template>
  
<style lang="scss" scoped> 
  .psdMissing-container{
    padding-top: 68px;
    .login-type-tab{
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 60px 48px;
      .tab-split{
        height: 18px;
        width: 1px;
        background-color: #1856A7;
        margin: 0 20px;
      }
      span{
        display: inline-block;
        cursor: pointer;
        font-size: 18px;
        line-height: 25px;
        color: #999999;
      }
      .active-tab{
        color: #1856A7;
        font-weight: 600;
      }
    }
    .regitser-form-box{
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      .missing-psd-form{
        width: 360px;
        .phone-item{
          width: 100%;
          display: flex;
          align-items: center;
        }
      }
      .mobile-missing-psd-form{
        display: none;
      }
      .psdMissing-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;
        }
      }
    }
  }
  // 移动端样式
  @media screen and (max-width: 768px) {
    .psdMissing-container{
      padding: 100px 30px 30px;
      .login-type-tab{
        display: flex;
        justify-content: flex-start;
        margin: 0 0 30px 0;
        .tab-split{
          height: 18px;
          width: 1px;
          background-color: #1856A7;
          margin: 0 20px;
        }
        span{
          display: inline-block;
          cursor: pointer;
          font-size: 18px;
          line-height: 25px;
          color: #999999;
        }
        .active-tab{
          color: #1856A7;
          font-weight: 600;
        }
      }
      .regitser-form-box{
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;    
        .missing-psd-form{
          display: none;
        }
        .mobile-missing-psd-form{
          display: block;
          width: 100%;
        }
        .psdMissing-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;
          }
        }
      }
    }
  }
</style>