<template>
  <div id="signin" v-loading="loading" element-loading-background="rgba(43, 48, 67, 0.65)">
    <div class="logo">
      <img width="65%" :src="logo" alt="logo" />
    </div>
    <div class="title">
      <p class="tit1">{{ t('newSignin.item1') }}</p>
      <p class="tit2">{{ t('newSignin.item2') }}</p>
    </div>
    <el-form ref="formRef" :model="params" :rules="rules" label-width="0" class="form">
      <el-form-item prop="loginName">
        <el-input
          v-model.trim="params.loginName"
          class="m-input"
          :placeholder="t('newSignin.item3')"
          @keyup.enter="login"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model.trim="params.password"
          class="m-input"
          type="password"
          show-password
          autocomplete="off"
          :placeholder="t('newSignin.item4')"
          @keyup.enter="login"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="forget">
          <div>
            <!-- <el-checkbox v-model="remember" class="Remember">
              <span>{{ $t('newSignin.item5') }}</span>
            </el-checkbox> -->
          </div>
          <router-link to="/forget">{{ t('newSignin.item6') }}</router-link>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="s-btn" :loading="loading" @click="login">
          {{ t('newSignin.item7') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <div class="words">
          <span>{{ t('newSignin.item8') }}</span>
          <router-link to="/signup">{{ t('newSignin.item9') }}</router-link>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="des">
          <span v-html="t('newSignin.item12')"></span><br />
          <span v-html="t('newSignin.item10')"></span><br />
          <span v-html="t('newSignin.item11')"></span><br />
          <span>{{ t('newSignin.item13') }}</span>
          <a
            :href="`https://www.${ho}.com/doc/Risk-Disclosures-and-Acknowledgements-2020-08.pdf`"
            target="_blank"
          >
            {{ t('newSignin.item13_1') }}
          </a>
          <span>{{ t('newSignin.item13_2') }}</span>
          <span>{{ t('newSignin.item13_3') }}</span>
          <span>{{ t('newSignin.item13_4') }}</span>
        </div>
      </el-form-item>
    </el-form>

    <!-- 验证码弹窗 -->
    <el-dialog
      v-model="dialogCheck"
      :title="t('getCode.item1')"
      center
      :close-on-click-modal="false"
      append-to-body
      custom-class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogFormRef"
          :model="dialogCheckForm"
          :rules="dialogRules"
          label-width="0"
          class="dialogCheck_form"
        >
          <el-form-item v-if="dialogCheckType === 0" prop="emailCode">
            <el-row>
              <el-col :span="14">
                <el-input
                  v-model.trim="dialogCheckForm.emailCode"
                  class="code"
                  :placeholder="t('getCode.item2')"
                  @blur="selectChange"
                >
                  <template #prefix>
                    <el-icon>
                      <Message />
                    </el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="9" :push="1" class="code-col">
                <span class="getCode" @click="getCode(1)" v-text="getCodeString"></span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="dialogCheckType === 1" prop="gaCode">
            <el-input
              v-model.trim="dialogCheckForm.gaCode"
              class="code"
              :placeholder="t('getCode.item3')"
              @blur="selectChange"
            >
              <template #prefix>
                <el-icon>
                  <Key />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="dialogCheck = false">
            {{ t('Btn.Cancel') }}
          </el-button>
          <el-button type="danger" @click="login">
            {{ t('Btn.Confirm') }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, inject, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Message, Key } from '@element-plus/icons-vue'
import axios from 'axios'
import logo from '@/assets/images/cwg-logo-01.svg'
import Service from '@/service/login'
import Config from '@/config/index'
import { useStore } from 'vuex'

// Composition API
const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()
const Session = inject('session')
const pigeon = inject('pigeon')

// 响应式数据
const loading = ref(false)
const dialogCheck = ref(false)
const dialogCheckType = ref(0)
const getCodeString = ref('')
const timer = ref(59)
const interval = ref(null)
const ho = ref('')
const flag = ref(false)
const remember = ref(false)
const more = ref(true)
const formRef = ref(null)
const dialogFormRef = ref(null)

const { Code, Pattern } = Config
const store = useStore()
// 表单数据
const params = reactive({
  loginName: '',
  password: '',
  country: '',
})

const dialogCheckForm = reactive({
  emailCode: '',
  gaCode: '',
})

// 验证规则
const rules = computed(()=>({
  loginName: [
    {
      validator: (rule, value, callback) => {
        if (Pattern.Email.test(value)) {
          callback()
        } else {
          callback(new Error(t('vaildate.email.format')))
        }
      },
      trigger: 'blur',
    },
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (Pattern.Password.test(value)) {
          callback()
        } else {
          callback(new Error(t('vaildate.password.format')))
        }
      },
      trigger: 'blur',
    },
  ],
}))

const dialogRules = computed(() => (
  {
    emailCode: [
      {
        validator: (rule, value, callback) => {
          if (value && value.trim()) {
            callback()
          } else {
            callback(new Error(t('vaildate.code.empty')))
          }
        },
        trigger: 'blur',
      },
    ],
    gaCode: [
      {
        validator: (rule, value, callback) => {
          if (value && value.trim()) {
            callback()
          } else {
            callback(new Error(t('vaildate.code.empty')))
          }
        },
        trigger: 'blur',
      },
    ],
  }
) )


// 方法
const selectChange = () => {
  // 强制更新表单验证
  nextTick(() => {
    if (dialogFormRef.value) {
      dialogFormRef.value.validate(() => {
      })
    }
  })
}

const loginValid = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return false

  loading.value = true
  const data = {
    loginName: params.loginName,
    password: params.password,
  }

  try {
    const res = await Service.loginValid(data)
    if (res.code === Code.StatusOK) {
      const params = res.data
      loading.value = false

      if (params.roleCode === 'ROLE_SALE') {
        nextTick(() => {
          dialogCheck.value = true
          dialogCheckType.value = params.valid === 1 ? 1 : 0
          if (dialogCheckType.value === 0) {
            getCode(1)
          }
        })
      } else {
        login()
      }
    } else {
      ElMessage.error(res.msg)
      loading.value = false
    }
  } catch (error) {
    ElMessage.error(t('Msg.SystemError'))
    loading.value = false
  }
}

const login = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return false

  if (flag.value) return
  flag.value = true
  loading.value = true

  const data = {
    loginName: params.loginName,
    password: params.password,
  }

  if (dialogCheckType.value === 1) {
    data.gaCode = dialogCheckForm.gaCode
  } else {
    data.emailCode = dialogCheckForm.emailCode
  }

  try {
    const res = await Service.Login(data)
    if (res.code === Code.StatusOK) {
      sessionStorage.setItem('access_token', res.data)
      axios.defaults.headers.common['Access-Token'] = res.data
      await getLoginInfo()
    } else {
      pigeon.error(res.msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
    flag.value = false
  }
}

const getLoginInfo = async () => {
  try {
    const res = await Service.CustomLoginInfo()
    if (res.code === Code.StatusOK) {
      // 这里假设有 store 可以使用
      store.commit('InitInfo', res.data)
      store.commit('InfoExpire', false)

      pigeon.success(t('Msg.LoginSuccess'))
      setTimeout(() => {
        router.push('/').catch((arr)=>arr)
        store.commit('isActiveTab', '0')
      }, 1000)
    } else {
      store.commit('InfoExpire', false)
      pigeon.error(t('Msg.SystemError'))
    }
  } catch (error) {
    console.log(error)
  }
}

const getCode = async (val) => {
  if (val && !params.loginName) {
    pigeon.warning(t('signin.form.email'))
    return
  }

  getCodeString.value = t('signup.form.waitCode1') + timer.value + t('signup.form.waitCode2')

  if (interval.value){
    await getCode1(val)
    interval.value = setInterval(() => {
      timer.value--
      Session.Set('timer', timer.value)
      getCodeString.value = t('signup.form.waitCode1') + timer.value + t('signup.form.waitCode2')

      if (timer.value === 0) {
        getCodeString.value = t('signup.form.getCode')
        clearInterval(interval.value)
        interval.value = null
        timer.value = 59
        Session.Set('timer', timer.value)
      }
    }, 1000)
  }
}

const getCode1 = async (val) => {
  if (!val) return

  try {
    const res = await Service.sendCode({
      loginName: params.loginName,
      lang: Session.Get('lang') || 'en', // 使用当前语言
    })
    if (res.code === Code.StatusOK) {
      pigeon.success(t('Msg.CodeSuccess'))
    } else {
      pigeon.error(res.msg)
    }
  } catch (error) {
    console.log(error)
  }
}

const initTimer = () => {
  const time = Session.Get('timer') || timer.value
  if (time == 59) {
    getCodeString.value = t('signup.form.getCode')
  } else {
    timer.value = Session.Get('timer')
    getCode(0)
  }
}

const sysLogin = async () => {
  if (!route.query.sysLoginToken) return

  const token = atob(route.query.sysLoginToken)
  loading.value = true
  sessionStorage.setItem('access_token', token)
  axios.defaults.headers.common['Access-Token'] = token
  await getLoginInfo()
}

// 生命周期
onMounted(() => {
  initTimer()
  const hostParts = window.location.host.split('.')
  ho.value = hostParts.length > 1 ? hostParts[1] : ''

  if (route.query.sysLoginToken) {
    sysLogin()
  }

  // 从 session 恢复记住的登录信息
  if (Session.Get('remember') == 1 && Session.Get('rememberList')) {
    remember.value = true
    const rememberList = JSON.parse(Session.Get('rememberList', true))
    Object.assign(params,{
      loginName: rememberList.loginName,
      password: rememberList.password,
    })
  }
})
</script>

<style lang="scss" scoped>
#signin {
  width: 100%;
  max-width: 530px;
  height: auto;
  padding-top: 35px;
  box-sizing: border-box;
  background-color: #fff;
  .m-input{
    height: 40px;
  }

  .title {
    margin: 32px 0;
    font-size: 24px;
    font-weight: bolder;
    color: #e4e4e4;

    i {
      margin-right: 10px;
    }

    .tit1 {
      font-size: 34px;
      line-height: 1.14;
      font-weight: bold;
      color: #000000;
    }

    .tit2 {
      font-size: 20px;
      line-height: 1.5;
      color: #000000;
      font-weight: 500;
    }
  }

  .form {
    padding: 20px 35px 35px;

    .forget {
      width: 100%;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      color: #000;

      a {
        color: #000;
      }

      .el-checkbox.Remember {
        color: #000;
      }

      .el-checkbox.Remember.is-checked .el-checkbox__label {
        color: #000;
      }
    }

    .words {
      text-align: start;
      line-height: 24px;
      color: #000;
      font-size: 16px;
      line-height: 1.6;

      a {
        margin-left: 1em;
        color: #e61f1e;
      }
    }

    .s-btn {
      width: 100%;
      height: 40px;
    }

    .des {
      text-align: start;
      line-height: 20px;
      color: #000;
      font-size: 12px;
      display: none;

      a {
        color: #e61f1e;
      }
    }

    .des.crm-one-font {
      height: 16px;
      overflow: hidden;
    }
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  #signin {
    height: auto;
    overflow: hidden;

    .title {
      margin: 32px 0;
      font-size: 20px;

      i {
        margin-right: 10px;
      }
    }

    .form {
      padding: 20px;

      .des {
        display: block;
      }
    }
  }
}

// 表单样式
#signin {
  .el-input__inner {
    border: none;
    border-bottom: 1px solid #979797;
    border-radius: 0;
    color: #000;
    height: 40px !important;
    background-color: rgba(0, 0, 0, 0);

    &::placeholder {
      color: #979797;
    }
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .el-form-item__content {
    //line-height: initial !important;
  }

  .el-input__prefix,
  .el-input__suffix {
    color: #e4e4e4;
  }

  .el-checkbox.Remember.is-checked .el-checkbox__label {
    color: #000;
  }
}

// 验证码相关样式
.getCode {
  margin-top: 15px;
  padding: 0px 20px;
  border: 1px solid;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  white-space: nowrap;

  &:hover {
    color: #9d9d9d;
  }
}

.code-col {
  display: flex;
  justify-content: center;
  align-items: center;
}

.dia-content {
  .dialogCheck_form {
    min-height: 100px;
  }

  .getCode {
    margin-top: 0;
  }

  .el-form-item {
    margin-top: 50px;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
  }
}

.w-100 {
  width: 100%;
}
</style>
