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

  const router = useRouter()
  const route = useRoute()
  const loginFormRef=ref(null)
  const loginFormMobileRef=ref(null)
  
  const loginForm=reactive({
    email:'',
    phone:'',
    phonePre:'86',
    password:'',
  })

  // 隐私政策是否阅读
  const hasChecked=ref(false)

  const loginFormRules=reactive({
    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'}]
  })

  const login=()=>{
    let refTemp = ''
    if(isMobile()){
      refTemp=loginFormMobileRef.value
    }else{
      refTemp=loginFormRef.value
    }
    refTemp.validate(valid =>{
      if(valid){
        // if(!hasChecked.value){
        //   ElMessage.warning('Please check the Privacy policy')
        //   return
        // }
        let params={
          CountryCode:loginForm.phonePre,
          Account:loginType.value==1?loginForm.email:loginForm.phone,
          Type:loginType.value,
          Password:md5(loginForm.password)
        }
        loginApi(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))

            let redirectPath=sessionStorage.getItem('login_redirect') || '/'
            sessionStorage.removeItem('login_redirect')
            router.replace(redirectPath)
          }
        })
      }
    })
  }
  // 去注册页
  const registerPageGo=()=>{
    let {href} = router.resolve("/register");
    window.open(href,'_blank');
  }
  const psdMissingPageGo=()=>{
    let {href} = router.resolve("/passwordMissing");
    window.open(href,'_blank');
  } 
  // 登录方式 1-邮箱 2-手机号
  const loginType=ref(1)
  // 操作方式 1-登录 2-注册
  const operationType=ref(1)
  const changeLoginType=(type)=>{
    if(type == loginType.value) return 
    loginType.value=type
  }
  const changeOperationType=(type)=>{
    if(type == operationType.value) return 
    operationType.value=type
  }

  // --------------------------------------------------移动端 - 注册
  // 第几步
  const step=ref(1)

  const registerForm=reactive({
    userName:'',
    companyName:'',
    email:'',
    verificationCode:'',
    password:'',
    passwordConfirm:''
  })
  const registerFormRef=ref(null)
  const registerFormRules=reactive({
    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'}],
    verificationCode:{required: true, message:'Verification code cannot be null', 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(registerForm.passwordConfirm!==registerForm.password){
        callback(new Error('Passwords do not match'))
      }else{
        callback()
      }
    }, trigger: 'blur'}]
  })

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

  const sendVerCode=()=>{
    registerFormRef.value.validateField(['userName','email']).then(res=>{
      let codeParams={
        Name:registerForm.userName,
        Email:registerForm.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 register=()=>{
    registerFormRef.value.validate(valid=>{
      if(valid){
        if(step.value==1){
          // 进入下一步
          step.value=2
          return
        }
        // if(!hasChecked.value){
        //   ElMessage.warning('Please check the Privacy policy')
        //   return
        // }
        let params={
          CompanyName:registerForm.companyName,
          Name:registerForm.userName,
          Email:registerForm.email,
          SmsCode:registerForm.verificationCode,
          Password:md5(registerForm.password)
        }
        registerApi(params).then(res=>{
          // console.log(res.code);
          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')
          }
        })
      }
    })
  }

  onMounted(()=>{
    if(route.query.isRegister){
        operationType.value = 2
    }
  })
</script>
<template>
  <div class="login-container" id="login-container">
    <!-- PC端 -->
    <div id="PC-part">
      <div class="login_background_image">
      </div>
      <div class="login-container-main">
        <div class="login-container-right">
          <div class="login-container-header">
            <span>HORIZON INSIGHTS</span>
          </div>
          <div class="login-container-body">
            <div class="login-type-tab">
              <span :class="loginType==1?'active-tab':''" @click="changeLoginType(1)">Login with email</span>
              <div class="tab-split"></div>
              <span :class="loginType==2?'active-tab':''" @click="changeLoginType(2)">phone number</span>
            </div>
            <el-form :model="loginForm" class="login-form" :rules="loginFormRules" ref="loginFormRef" style="width: 360px;">
              <el-form-item prop="email" v-if="loginType==1">
                <el-input v-model.trim="loginForm.email" size="large" placeholder="Please enter your email address" style="width: 360px;"></el-input>
              </el-form-item>
              <el-form-item prop="phone" v-else >
                <div class="phone-item">
                  <el-select v-model="loginForm.phonePre" style="max-width: 90px;margin-right: 10px;" placeholder="Please select" size="large">
                    <el-option :label="item.label" :value="item.value" v-for="item in TEL_CODE_ARR" />
                  </el-select>
                  <el-input v-model.trim="loginForm.phone" style="flex-grow: 1;" placeholder="Please enter your phone number" size="large">
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item prop="password" style="width: 360px;">
                <el-input v-model.trim="loginForm.password" size="large" type="password" placeholder="Please enter a password"></el-input>
              </el-form-item>
            </el-form>
            <div class="register-message-row">
              <div class="register-message">
                New to Horizon Insights? <span @click="registerPageGo">Create an account</span>
              </div>
              <div class="password-miss" @click="psdMissingPageGo">
                Forgot your password?
              </div>
            </div>
            <el-button class="submit-button" type="primary" size="large" @click="login">Log in now</el-button>
            <!-- <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="login-hint">For technical assistance, please contact stephanie@hzinsights.com</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 移动端 -->
    <div id="mobile-part">
      <div class="fixed-header">
        <span>
          HORIZON INSIGHTS
        </span>
      </div>
      <div class="verification-body">
        <div class="login-type-tab" v-if="step==1 || operationType==1">
          <span :class="operationType==1?'active-tab':''" @click="changeOperationType(1)">Login</span>
          <div class="tab-split"></div>
          <span :class="operationType==2?'active-tab':''" @click="changeOperationType(2)">Create account</span>
        </div>
        <div class="register-psd-hint" v-else>
          Please set password
        </div>
        <!-- 登录 -->
        <div class="mobile-login-box" v-if="operationType==1">
          <el-form :model="loginForm" label-width="55px" label-position="top" id="mobile-form-field" :rules="loginFormRules" 
          ref="loginFormMobileRef" hide-required-asterisk>
            <el-form-item prop="email" v-if="loginType==1" label="Email Address" size="large" >
              <el-input v-model.trim="loginForm.email" size="large" placeholder="Please enter your email address"></el-input>
            </el-form-item>
            <el-form-item prop="phone" v-else >
              <template #label>
                <span style="margin-right: 10px;">Area Code</span>
                <el-select v-model="loginForm.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="loginForm.phone" style="flex-grow: 1;" placeholder="Please enter your phone number" size="large"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="Password" size="large">
              <el-input v-model.trim="loginForm.password" size="large"  type="password" placeholder="Enter your password"></el-input>
            </el-form-item>
          </el-form>
          <div class="mobile-login-type-change">
            <span @click="changeLoginType(loginType==1?2:1)">Login with {{ loginType==1?"phone number":"email" }} instead</span>
            <span @click="psdMissingPageGo" style="color:#1856A7">Forgot your password?</span>
          </div>
          <el-button type="primary" class="submit-button" @click="login" size="large">Log in now</el-button>
          <!-- <div class="privacy-policy">
            <el-checkbox v-model="hasChecked" label="I have read and agree"></el-checkbox>
            <span @click="privacyPolicy" class="policy">the Horizon Insights Privacy Policy</span>
          </div> -->
          <div class="mobile-login-hint">For technical assistance, please contact stephanie@hzinsights.com</div>
        </div>
        <!-- 注册 -->
        <div class="mobile-register-box" v-else>
          <el-form :model="registerForm" label-position="top" id="mobile-form-field" 
          :rules="registerFormRules" ref="registerFormRef" hide-required-asterisk>
            <el-form-item prop="userName" label="Name" size="large" v-if="step==1">
              <el-input v-model.trim="registerForm.userName" size="large" placeholder="Enter your name"></el-input>
            </el-form-item>
            <el-form-item prop="companyName" label="Company" size="large" v-if="step==1">
              <el-input v-model="registerForm.companyName" size="large" placeholder="Enter a company name"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="Email Address" size="large" v-if="step==1">
              <el-input v-model="registerForm.email" size="large" placeholder="Enter email address">
                <template #suffix>
                  <span style="color: var(--el-color-primary);cursor: pointer;" 
                  @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" label="Verification code" size="large" v-if="step==1">
              <el-input v-model="registerForm.verificationCode" size="large" placeholder="Enter code received"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="Password" size="large" v-if="step==2">
              <el-input v-model.trim="registerForm.password" size="large" type="password" placeholder="At least 6 digits"></el-input>
            </el-form-item>
            <el-form-item prop="passwordConfirm" style="margin-bottom: 0;" label="Password" size="large" v-if="step==2">
              <el-input v-model.trim="registerForm.passwordConfirm" size="large" type="password" placeholder="Re-enter your password"></el-input>
            </el-form-item>
          </el-form>
          <el-button type="primary" class="submit-button" @click="register" size="large" v-if="step==1">Next</el-button>
          <el-button type="primary" class="submit-button" size="large" v-if="step==2" @click="register">Submit</el-button>
          <!-- <div class="privacy-policy" v-if="step==2">
            <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="mobile-login-hint">For technical assistance, please contact stephanie@hzinsights.com</div>
        </div>
      </div>
    </div>
  </div>
</template>
  
<style lang="scss" scoped>
  .login-container{
    .login-type-tab{
      display: flex;
      align-items: center;
      margin-bottom: 36px;
      .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;
      }
    }
    .privacy-policy{
      font-weight: 400;
      font-size: 14px;
      line-height: 22px;
      margin-top: 25px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .policy{
        color: #1856A7;
        cursor: pointer;
        margin-left: 12px;
      }
    }
    .submit-button{
      margin-top: 26px;
      width: 100%;
      background-color: #1856A7;
    }
    #PC-part{
      width: 100%;
      height:100vh;
      .login_background_image{
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        width: 100vw;
        background-color: rgba(24, 86, 167, 0.2);
        z-index: -1;
        background-image: url('@/assets/login_bci.png');
        background-repeat: no-repeat;
        background-size: cover;
      }
      .login-container-main{
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;

        .login-container-right{
          background-color: white;
          width: 650px;
          height: 550px;
          opacity: 0.95;
          border: 1px solid #DCDFE6;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          align-items: center;
          .login-container-header{
            height: 68px;
            border-bottom:  solid 1px #DCDFE6;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            span{
              font-weight: 600;
              font-size: 20px;
              color: #1856A7;
            }
          }
          .login-container-body{
            width: 430px;
            padding-top: 45px;
            .login-form{
              .phone-item{
                width: 100%;
                display: flex;
                align-items: center;
              }
            }
            .register-message-row{
              display: flex;
              align-items: center;
              justify-content: space-between;
              .register-message{
                font-size: 14px;
                color: #333333;
                span{
                  color: #1856A7;
                  cursor: pointer;
                }
              }
              .password-miss{
                font-size: 14px;
                // color: #333333;;
                cursor: pointer;
                color: #1856A7;
              }
            }      
            .login-hint{
              font-size: 14px;
              line-height: 20px;
              color: #999999;
              margin-top: 25px;
            }
          }
        }
      }
    }
    #mobile-part{
      display: none;
    }
  }
  // 移动端样式
  @media screen and (max-width: 768px) {
    .login-container{
      #PC-part{
        display: none;
      }
      #mobile-part{
        background-color: white;
        display:block ;
        width: 100%;
        height:100%;
        min-height: 100%;
        .verification-body{
          width: 100%;
          height: 100%;
          padding: 100px 30px 30px;
          .login-type-tab{
            margin-bottom: 30px;
            .tab-split{
              height: 16px;
              width: 2px;
              background-color: #1856A7;
              margin: 0 20px;
            }
            span{
              font-size: 16px;
              line-height: 22px;
            }
          }
          .register-psd-hint{
            font-weight: 400;
            font-size: 16px;
            line-height: 22px;
            color: #333333;
            margin-bottom: 40px;
          }
          .mobile-login-box{
            .mobile-login-type-change{
              display: flex;
              align-items: center;
              justify-content: space-between;
              span{
                font-weight: 400;
                font-size: 12px;
                line-height: 17px;
                color: #1856A7;
              }
            }
            .mobile-login-hint{
              font-weight: 400;
              font-size: 12px;
              line-height: 17px;
              color: #999999;
              margin-top: 20px;
            }
          }
          .mobile-register-box{
            .mobile-login-type-change{
              display: flex;
              align-items: center;
              justify-content: space-between;
              span{
                font-weight: 400;
                font-size: 12px;
                line-height: 17px;
                color: #1856A7;
              }
            }
            .mobile-login-hint{
              font-weight: 400;
              font-size: 12px;
              line-height: 17px;
              color: #999999;
              margin-top: 20px;
            }
          }
        }
      }
    }
  }
</style>