<template>
  <div class="container" style="justify-content: space-between;">
    <div class="login-header">
      <svg-icon icon-class="logo" class="logo-img" />
        <i18n class="lang-menu" @change="changeLang"/>
    </div>
    <div class="login">
      <div class="title">{{ t('login.pageDescription') }}</div>
      <div class="login-tabs">
        <div class="tab-items">
          <div :class="['tab-item', { 'tab-item-active': activeName === 'login'}]" @click="tabClick('login')">{{ t('common.login') }}</div>
          <div :class="['tab-item', { 'tab-item-active': activeName === 'signUp'}]" @click="tabClick('signUp')">{{ t('common.signUp') }}</div>
        </div>
        <div class="tab-active-bar"></div>
      </div>
      <el-form v-if="activeName === 'login'" ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form" label-position="top" hide-required-asterisk>
        <el-form-item prop="username" :label="t('form.email.label')">
          <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item prop="password" :label="t('form.password.label')">
          <el-input v-model="loginForm.password" type="password" show-password size="large" auto-complete="off" @keyup.enter="handleLogin" ></el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaNeed" :label="t('form.captcha.label')">
          <el-input v-model="loginForm.code" size="large" auto-complete="off" style="width: 400px" @keyup.enter="handleLogin" ></el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">{{ t('common.rememberMe') }}</el-checkbox>
        <el-form-item>
          <el-button class="login-btn" :loading="loading" size="large" type="primary" @click.prevent="handleLogin" >
            <span v-if="!loading">{{ t('common.login') }}</span>
            <span v-else>{{ t('login.beLoggingIn') }}</span>
            <template #loading>
              <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="white" style="margin-right: 17px;" ></l-ring-2>
            </template>
          </el-button>
          <div style="width: 100%;text-align: center;margin-top: 24px;font-size: 18px;user-select: none;">
            <router-link class="link-type" :to="'/forgotPassword'">{{ t('login.forgotPassword') }}</router-link>
          </div>
        </el-form-item>
      </el-form>
      <el-form v-else-if="activeName == 'signUp'" ref="signUpRef" :model="signUpForm" :rules="signUpRules" class="login-form" label-position="top" hide-required-asterisk>
        <el-form-item prop="firstName" :label="t('form.firstName.label')">
          <el-input v-model="signUpForm.firstName" type="text" size="large" auto-complete="off" :placeholder="t('form.firstName.placeholder')" 
          @keyup.enter="handleSignUp" @input="signUpForm.firstName=signUpForm.firstName.replace(/[^a-zA-Z' @\-/]/g,'')" ></el-input>
        </el-form-item>
        <el-form-item prop="lastName" :label="t('form.lastName.label')">
          <el-input v-model="signUpForm.lastName" type="text" size="large" auto-complete="off" :placeholder="t('form.lastName.placeholder')"
          @keyup.enter="handleSignUp" @input="signUpForm.lastName=signUpForm.lastName.replace(/[^a-zA-Z' @\-/]/g,'')" ></el-input>
        </el-form-item>
        <el-form-item prop="country" :label="t('form.countryLabel.label')">
          <el-select v-model="signUpForm.country" size="large" auto-complete="off" placeholder=" " @change="handleCountry" >
            <el-option v-for="item in countries" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <div style="display: flex;">
          <el-form-item prop="phone_prefix" :label="t('form.phoneNumber.label')" style="width: 120px;margin-right: 10px;" >
            <el-input v-model="signUpForm.phone_prefix" type="text" size="large" maxlength="10" auto-complete="off" @keyup.enter="handleSignUp" ></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="&emsp;" style="width: calc(100% - 130px);" >
            <el-input v-model="signUpForm.phone" type="text" size="large" maxlength="20" auto-complete="off" @keyup.enter="handleSignUp" ></el-input>
          </el-form-item>
        </div>
        <el-form-item prop="email" :label="t('form.email.label')">
          <el-input v-model="signUpForm.email" type="text" size="large" auto-complete="off" @keyup.enter="handleSignUp" ></el-input>
        </el-form-item>
        <el-form-item prop="password" :label="t('form.password.label')">
          <el-input v-model="signUpForm.password" type="password" show-password size="large" auto-complete="off" @keyup.enter="handleSignUp" ></el-input>
        </el-form-item>
        <el-form-item>
          <password-validator v-if="signUpForm.password" ref="pv1" v-model="signUpForm.password" />
        </el-form-item>
        <el-form-item prop="shareCode" :label="t('register.sc')">
          <el-input :readonly="scReadOnly" v-model="signUpForm.shareCode" type="text" size="large" auto-complete="off" @keyup.enter="handleSignUp" ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="readingTxt" size="large" :true-value="true" :false-value="false" style="margin-right: 8px;">
            <span>{{ t('register.registerText.acceptPolicy') }}</span>
          </el-checkbox>
          <el-link href="https://www.htfx.co/wp-content/uploads/2024/09/Conflict-of-Interest-Policy.pdf" target="_blank" :underline="false">{{ t('register.registerText.interestPolicy') }}</el-link>,&ensp;
            <el-link href="https://www.htfx.co/wp-content/uploads/2024/09/Order-Execution-Policy.pdf" target="_blank" :underline="false">{{ t('register.registerText.executionPolicy') }}</el-link>,&ensp;
            <el-link href="https://www.htfx.co/wp-content/uploads/2024/09/Private-Policy-.pdf" target="_blank" :underline="false">{{ t('register.registerText.privatePolicy') }}</el-link>,&ensp;
            <el-link href="https://www.htfx.co/wp-content/uploads/2024/09/Risk-Disclosure.pdf" target="_blank" :underline="false">{{ t('register.registerText.riskDisclosure') }}</el-link>,&ensp;
            <el-link href="https://www.htfx.co/wp-content/uploads/2024/09/Client-Agrement.pdf" target="_blank" :underline="false">{{ t('register.registerText.termsConditions') }}</el-link>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="!readingTxt" class="sign-btn" :loading="loading" size="large" type="primary" @click.prevent="handleSignUp" >
            <span v-if="!loading">{{ t('common.signUp') }}</span>
            <span v-else>{{ t('register.beRegistering') }}</span>
            <template #loading>
              <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="white" style="margin-right: 17px;" ></l-ring-2>
            </template>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="login-footer">
      <el-divider />
      <div v-html="footerText"></div>
    </div>
  </div>
</template>

<script setup>
import { inject, ref } from "vue";
import { getCodeImg, checkCountryByIP } from "@/api/login";
import useUserStore from '@/store/modules/user'
import { useLocale } from 'element-plus'
import { getTemplateDetailByCode, getCountry } from "@/api/common";
import { serverLang, clientLang } from '@/utils/i18n'
import I18n from "@/components/I18n"
import PasswordValidator from "@/components/PasswordValidator"
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { isEmpty } from '@/utils/htfx'

const { t } = useLocale()
const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const changeLanguage = inject('changeLanguage')
const pv1 = ref(null)
const urlSc = route.params.sc || route.query.sc || ''
const activeName = ref((urlSc || route.path.startsWith('/signUp'))?'signUp':'login')
const scReadOnly = ref(!isEmpty(urlSc))

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});

const signUpForm = ref({
  firstName: undefined,
  lastName: undefined,
  country: undefined,
  phone_prefix: undefined,
  phone: undefined,
  email: undefined,
  password: undefined,
  shareCode: urlSc,
  utm_source: route.query.utm_source,
  utm_medium: route.query.utm_medium,
  utm_content: route.query.utm_content,
  utm_campaign: route.query.utm_campaign,
  utm_blocka: route.query.utm_blocka
});

let country = ref(null)

const checkEmail = (rule, value, callback) => {
  const pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  if (!value) {
    return callback(new Error(t('form.email.required')))
  }
  if (!pattern.test(value)) {
    return callback(new Error(t('form.email.invalid')))
  }
  callback()
}

const loginRules = {
  username: [{ required: true, trigger: "blur", message: t('form.account.required') }],
  password: [{ required: true, trigger: "blur", message: t('form.password.required') }],
  code: [{ required: true, trigger: "change", message: t('form.captcha.required') }]
};

const signUpRules = {
  firstName: [{ required: true, trigger: "blur", message: t('form.firstName.required') }],
  lastName: [{ required: true, trigger: "blur", message: t('form.lastName.required') }],
  country: [{ required: true, trigger: "change", message: t('form.countryLabel.required') }],
  email: [
    { required: true, trigger: "blur", message: t('form.email.required') },
    { validator: checkEmail, trigger: 'blur' }
  ],
  phone: [{ required: true, trigger: "blur", message: t('form.phoneNumber.required') }],
  phone_prefix: [{ required: true, trigger: "blur", message: '' }],
  password: [{ required: true, trigger: "blur", message: t('form.password.required') }]
};

const readingTxt = ref(false)

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);
const captchaNeed = ref(false);
const loadCaptcha = ref(false);

const redirect = ref(undefined);

const footerText = ref('')

const countries = ref([])

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(res => {
        if (res.data.loveMap && res.data.loveMap.language) {
          changeLanguage(clientLang(res.data.loveMap.language))
        } else {
          changeLanguage('en')
        }
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        delete otherQueryParams.language
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        // 重新获取验证码
        getCode();
      });
    }
  });
}

function handleSignUp() {
  proxy.$refs.signUpRef.validate(valid => {
    if (valid && pv1.value.check()) {
      loading.value = true;
      // 注册
      userStore.signUp(signUpForm.value).then(res => {
        if (res.data.loveMap && res.data.loveMap.language) {
          changeLanguage(clientLang(res.data.loveMap.language))
        } else {
          changeLanguage('en')
        }
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        delete otherQueryParams.language
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      captchaNeed.value = res.data.captchaStatus == 1
      codeUrl.value = "data:image/gif;base64," + res.data.img;
      loginForm.value.uuid = res.data.uuid;
      loadCaptcha.value = true
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

function getFooterText() {
  getTemplateDetailByCode({
    qcc_language: serverLang(),
    templateCode: 'COMPANY_INFO'
  }).then(resp => {
    if (resp.data && resp.data.content) {
      footerText.value = resp.data.content
    }
  })
}

function changeLang(lang) {
  // getFooterText();
  let url = new URL(window.location)
  url.searchParams.delete("language")
  window.history.replaceState({},"",url)
  window.location.reload()
}

function tabClick(data) {
  if (activeName.value == data) {
    return
  }
  activeName.value = data
  if (data === 'signUp') {
    loadCountry()
  }
}

function handleCountry(e) {
  countries.value.forEach(i => {
    if (i.id == e) {
      signUpForm.value.phone_prefix = i.phonecode
      return
    }
  })
}

function loadCountry() {
  getCountry().then(resp => {
    countries.value = resp.data
    if (country && countries.value.length) {
      autoSelectCountry()
    }
  })
}

function loadCountryByIP() {
  checkCountryByIP().then(resp => {
    if (resp.data) {
      country = resp.data.country;
      if (country && countries.value.length) {
        autoSelectCountry()
      }
    }
  })
}

function autoSelectCountry() {
  if (signUpForm.value.country) {
    return
  }
  countries.value.forEach(i => {
    if (i.iso2 == country) {
      signUpForm.value.country = i.id
      signUpForm.value.phone_prefix = i.phonecode
      return
    }
  })
}

loadCountryByIP()

getFooterText();
getCode();
getCookie();
loadCountry();
// getCookie();
</script>

<style lang='scss' scoped>
.login-header, .login-footer {
  height: 60px;
  flex-shrink: 0;
  width: 100%;
}

.login-header {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  padding: 0 3.85%;

  .logo-img {
    align-self: center;
    width: 120px;
    height: 45px;
  }

  .lang-menu {
    margin-top: 30px;
  }
}

.login-footer {
  padding: 0 3.85%  1%;
  font-size: 12px;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 27px;
  color: rgba(184, 184, 184, 1);
  text-align: left;
  vertical-align: top;
  flex-shrink: 0;
  height: auto;
}

.login {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  width: 564px;
}

.login-tabs {
  width: 100%;
  .tab-items {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    height: 56px;
    justify-content: space-between;
    color: rgba(102, 102, 102, 1);
    user-select: none;

    .tab-item {
      width: 50%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26px;
      cursor: pointer;
    }

    .tab-item-active {
      color: rgba(51, 51, 51, 1);
      font-weight: 700;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        bottom: -2px;
        height: 2px;
        width: 100%;
        background-color: rgba(51, 51, 51, 1);
      }
    }
  }

  .tab-active-bar {
    width: 100%;
    height: 2px;
    background: rgba(236, 236, 236, 1);
  }
}

.title {
  width: 100%;
  text-align: left;
  margin-bottom: 20px;
  font-weight: 700;
  font-size: 40px;
  color: rgba(51, 51, 51, 1);
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 100%;

  :deep(.el-form-item__label) {
    margin-top: 25px;
    font-size: 20px;
    font-weight: 400;
    letter-spacing: 0px;
    color: rgba(51, 51, 51, 1);
  }

  :deep(.el-input__password) {
    font-size: 20px;
  }

  .el-input {
    height: 50px;
    width: 100%;
    font-size: 20px;
    input {
      height: 50px;
    }
  }

  .el-select {
    height: 50px;
    width: 100%;
    font-size: 20px;
  }
  :deep(.el-select--large .el-select__wrapper) {  
    min-height: 50px;
    font-size: 20px;
  }
}

.login-code {
  height: 60px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 60px;
  padding-left: 12px;
}

.login-btn {
  margin-top: 30px;
  width: 100%;
  height: 50px;
  font-size: 20px;
}

.sign-btn {
  width: 100%;
  height: 50px;
  font-size: 20px;
}

:deep(.el-form-item__label) {
  white-space: nowrap;
}
</style>
