<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 {bindMobile,modifyMobile} from '@/api/auth.js'
import { TEL_CODE_ARR } from '../../utils/constant';
import { isMobile } from '../../utils/common';
import { phoneNoValidator } from './utils/validators';
import { sendVerificationCode } from './utils/common';

  const router = useRouter()

  const bindPhoneRef = ref(null)
  const bindPhoneMobileRef = ref(null)
  
  const newPhoneNoRef = ref(null)
  const newPhoneNoMobileRef = ref(null)
  
  const userInfo = localStorage.getItem('user_info')?JSON.parse(localStorage.getItem('user_info')):{}

  const bindPhone=reactive({
    form:{
      newPhoneNo:'',
      newPhoneNoPre:'86',
      verificationCode:''
    },
    rules:{
      newPhoneNo:[{required: true, message:'Mobile phone No. cannot be null', trigger: 'blur'},
      {validator:phoneNoValidator, trigger: 'blur'}],
      verificationCode:{required: true, message:'Verification code cannot be null', trigger: 'blur'}
    }
  })

  const codeInfo=reactive({
    timeout:0,// 秒
    isRequesting:false
  })
// ----------------------------------------------------方法
  const sendVerCode=()=>{
    let refTemp = ''
    if(isMobile()){
      refTemp=bindPhoneMobileRef.value
    }else{
      refTemp=bindPhoneRef.value
    }
    refTemp.validateField(['newPhoneNo']).then(res=>{
      let codeParams={
        Mobile:bindPhone.form.newPhoneNo,
        AreaNum:bindPhone.form.newPhoneNoPre || '86'
      }
      sendVerificationCode(codeParams,2,codeInfo)

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

  const bindSubmit=()=>{
    let isPhoneVar = isMobile()
    let refTemp = ''
    if(isPhoneVar){
      refTemp=bindPhoneMobileRef.value
    }else{
      refTemp=bindPhoneRef.value
    }
    refTemp.validate(valid=>{
      if(valid){
        let params=''
        let mobileApi=''
        if(userInfo.Mobile){
          // 换绑
          params={
            OldMobile:userInfo.Mobile,
            NewMobile:bindPhone.form.newPhoneNo,
            SmsCode:bindPhone.form.verificationCode,
            CountryCode:bindPhone.form.newPhoneNoPre || '86'
          }
          mobileApi = modifyMobile
        }else{
          params={
            Mobile:bindPhone.form.newPhoneNo,
            SmsCode:bindPhone.form.verificationCode,
            CountryCode:bindPhone.form.newPhoneNoPre || '86'
          }
          mobileApi= bindMobile
        }

        mobileApi(params).then(res=>{
          if(res.code==200){
            userInfo.Mobile=bindPhone.form.newPhoneNo
            localStorage.setItem('user_info',JSON.stringify(userInfo))
            sessionStorage.setItem('transitionPageMessage','bindPhone')
            router.replace('/transitionPage')
          }
          else if(res.code==4016){
            if(isPhoneVar){
              newPhoneNoMobileRef.value.validateMessage='Has been bound to another account.'
              newPhoneNoMobileRef.value.validateState='error'
            }else{
              newPhoneNoRef.value.validateMessage='This mobile phone No. has been bound to another account.'
              newPhoneNoRef.value.validateState='error'
            }
          }
        })
      }
    })
  }

</script>

<template>
    <div class="bind-phone-container">
      <div class="fixed-header">
        <span @click="$router.replace('/')" style="cursor: pointer;">
          HORIZON INSIGHTS
        </span>
      </div>
      <div class="page-title">
        Add a phone number to your account
      </div>
      <div class="bind-phone-form-box" id="bind-phone-form-box">
        <!-- PC端的表单 -->
        <el-form :model="bindPhone.form" class="bind-phone-form" :rules="bindPhone.rules" ref="bindPhoneRef">
          <el-form-item label="Original Mobile Phone No." label-width="176px" style="border: none;" v-if="userInfo.Mobile">
            +{{ userInfo.CountryCode+' '+userInfo.Mobile }}
          </el-form-item>
          <el-form-item prop="newPhoneNo" ref="newPhoneNoRef" size="large">
            <div class="phone-item">
              <el-select v-model="bindPhone.form.newPhoneNoPre" 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="bindPhone.form.newPhoneNo" size="large" style="flex-grow: 1;" placeholder="Please enter your 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="verificationCode" style="margin-bottom: 0;" size="large">
            <el-input v-model="bindPhone.form.verificationCode" size="large" style="width: 360px;" placeholder="Please enter the verification code" class="form-item">
            </el-input>
          </el-form-item>
        </el-form>
        <!-- 移动端的表单 -->
        <el-form :model="bindPhone.form" class="mobile-bind-phone-form" id="mobile-form-field" hide-required-asterisk label-position="top"
        :rules="bindPhone.rules" label-width="70px" ref="bindPhoneMobileRef">
          <el-form-item label="Original Mobile Phone No." label-width="165px" v-if="userInfo.Mobile">
            <span style="margin-left: 15px;">{{ userInfo.CountryCode+' '+userInfo.Mobile }}</span>
          </el-form-item>
          <el-form-item prop="newPhoneNo" ref="newPhoneNoMobileRef" size="large" label-position="left">
            <template #label>
              <span style="margin-right: 10px;">Area Code</span>
              <el-select v-model="bindPhone.form.newPhoneNoPre" :suffix-icon="CaretBottom"
              style="max-width: 60px;" 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="bindPhone.form.newPhoneNo" size="large" style="flex-grow: 1;" placeholder="Please enter your 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="verificationCode" label="Verification code" style="margin-bottom: 0;" size="large">
            <el-input v-model="bindPhone.form.verificationCode" size="large" style="width: 360px;" placeholder="Please enter the verification code" class="form-item">
            </el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="bindSubmit" class="submit-button" size="large">Submit</el-button>
        <div class="question-hint">For technical assistance, please contact stephanie@hzinsights.com</div>
      </div>
    </div>
</template>
  
<style lang="scss" scoped> 
  .bind-phone-container{
    padding-top: 60px;
    .page-title{
      text-align: center;
      font-weight: 600;
      font-size: 20px;
      line-height: 28px;
      color: #1856A7;
      padding: 56px 0 48px;
    }
    .bind-phone-form-box{
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      .bind-phone-form{
        width: 360px;
        .phone-item{
          width: 100%;
          display: flex;
          align-items: center;
        }
      }
      .mobile-bind-phone-form{
        display: none;
      }
      .submit-button{
        margin: 40px 0 30px;
        width: 360px;
        background-color: #1856A7;
      }
      .question-hint{
        font-weight: 400;
        font-size: 14px;
        line-height: 20px;
        color: #999999;
      }
    }
  }
  @media screen and (max-width: 768px) {
    .bind-phone-container{
      padding: 50px 30px 30px;
      .page-title{
        text-align: left;
        padding: 50px 0 30px;
        font-weight: 400;
        font-size: 16px;
        line-height: 22px;
        color: #333333;
      }
      .bind-phone-form-box{
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        .bind-phone-form{
          display: none;
        }
        .mobile-bind-phone-form{
          display: block;
          width: 100%;
        }
        .submit-button{
          margin: 20px 0;
          width: 100%;
        }
        .question-hint{
          font-size: 12px;
          line-height: 17px;
        }
      }
    }
  }
</style>