<template>
  <div id="signin" v-loading="loading">
    <div class="title">
      <i class="el-icon-unlock"></i>
      <span v-t="'signin.title'"></span>
    </div>
    <el-form ref="paramsRef" :model="params" :rules="rules" label-width="0" class="form">
      <el-form-item prop="loginName">
        <el-input
          :prefix-icon="Message"
          v-model.trim="params.loginName"
          class="m-input"
          :placeholder="$t('signin.form.email')"
          @keyup.enter="login"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model.trim="params.password"
          style="width: 100% !important"
          class="m-input"
          type="password"
          :prefix-icon="Key"
          autocomplete="off"
          show-password
          :placeholder="$t('signin.form.password')"
          @keyup.enter="login"
        ></el-input>
      </el-form-item>
      <el-form-item class="forget">
        <a style="width: 100%" href="#/forget">{{ $t('signin.forget') }}</a>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" class="s-btn" @click="loginValid">
          {{ $t('signin.login') }}
        </el-button>
      </el-form-item>
    </el-form>

    <!--验证码-->
    <el-dialog
      :title="$t('getCode.item1')"
      center
      :close-on-click-modal="false"
      v-model="dialogCheck"
      class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckFormRef"
          :model="dialogCheck_form"
          :rules="rules"
          label-width="0"
          class="dialogCheck_form"
        >
          <el-form-item v-if="dialogCheck_type == 0" prop="emailCode">
            <el-row>
              <el-col :span="14">
                <el-input
                  v-model.trim="dialogCheck_form.emailCode"
                  class="code"
                  :placeholder="$t('getCode.item2')"
                  @blur="selectChange"
                >
                  <template #prefix>
                    <i
                      style="font-weight: bold; font-size: 20px"
                      class="iconfont iconyanzhengma"
                    ></i>
                  </template>
                </el-input>
              </el-col>
              <el-col
                :span="9"
                :push="1"
                style="display: flex; justify-content: center; align-items: center"
              >
                <span class="getCode" @click="getCode(1)" v-text="getCodeString"></span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="dialogCheck_type == 1" prop="gaCode">
            <el-input
              v-model.trim="dialogCheck_form.gaCode"
              class="code"
              :placeholder="$t('getCode.item3')"
              @blur="selectChange"
            >
              <template #prefix>
                <i style="font-weight: bold; font-size: 20px" class="iconfont iconyanzhengma"></i>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-t="'Btn.Cancel'" @click="dialogCheck = false"></el-button>
          <el-button v-t="'Btn.Confirm'" type="danger" @click="login()"></el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import {
    ref,
    reactive,
    onMounted,
    computed,
    getCurrentInstance,
    onDeactivated,
    inject,
  } from 'vue'
  import { useRouter } from 'vue-router'
  import { useStore } from 'vuex'
  import Service from '@/service/login'
  import Config from '@/config/index'
  import axios from 'axios'
  import type { FormInstance, FormRules } from 'element-plus'
  import { Message, Key } from '@element-plus/icons-vue'
  import { useI18n } from 'vue-i18n'

  const { Code } = Config
  const router = useRouter()
  const store = useStore()
  const v3This = getCurrentInstance()
  // 引入弹窗方法
  const pigeon = inject('pigeon')
  // 引入session
  const session = inject('session')

  const { t } = useI18n()
  // 类型定义
  interface LoginParams {
    loginName: string
    password: string
    emailCode: string
  }

  interface DialogCheckForm {
    emailCode: string
    gaCode: string
  }

  // 响应式数据
  const loading = ref(false)
  const params = reactive<LoginParams>({
    loginName: '',
    password: '',
    emailCode: '',
  })

  const timer = ref(59)
  const interval = ref<NodeJS.Timeout | null>(null)
  const getCodeString = ref('')

  const dialogCheck = ref(false)
  const dialogCheck_form = reactive<DialogCheckForm>({
    emailCode: '',
    gaCode: '',
  })
  const dialogCheck_type = ref(0)

  // 表单引用
  const paramsRef = ref<FormInstance>()
  const dialogCheckFormRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive<FormRules>({
    loginName: [
      {
        required: true,
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
    code: [
      {
        validator: (rule, value, callback) => {
          if (params.emailCode != '' && params.emailCode != null) {
            callback()
          } else {
            callback(new Error(t('vaildate.code.empty')))
          }
        },
        trigger: 'blur',
      },
    ],
    emailCode: [
      {
        validator: (rule, value, callback) => {
          if (dialogCheck_form.emailCode != '' && dialogCheck_form.emailCode != null) {
            callback()
          } else {
            callback(new Error(t('vaildate.code.empty')))
          }
        },
        trigger: 'blur',
      },
    ],
    gaCode: [
      {
        validator: (rule, value, callback) => {
          if (dialogCheck_form.gaCode != '' && dialogCheck_form.gaCode != null) {
            callback()
          } else {
            callback(new Error(t('vaildate.code.empty')))
          }
        },
        trigger: 'blur',
      },
    ],
  })

  // 方法
  const selectChange = () => {
    // 如果需要强制更新
  }

  // 登录验证方式
  const loginValid = async () => {
    if (!paramsRef.value) return

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

    loading.value = true
    try {
      const data = {
        loginName: params.loginName,
        password: params.password,
      }
      dialogCheck.value = true
      const res = await Service.loginValid(data)
      console.log(res, 'res')
      //
      if (res.code === Code.StatusOK) {
        const validFlag = res.data
        dialogCheck.value = true
        dialogCheck_type.value = validFlag === 1 ? 1 : 0

        if (validFlag !== 1) {
          await getCode(1)
        }
      } else {
        // 使用你的消息提示组件
        console.error(res.msg)
      }
    } catch (error) {
      console.error('登录验证失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 登录
  const login = async () => {
    if (!dialogCheckFormRef.value) return
    console.log('asd')

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

    loading.value = true
    try {
      const data =
        dialogCheck_type.value === 1
          ? {
              loginName: params.loginName,
              password: params.password,
              gaCode: dialogCheck_form.gaCode,
            }
          : {
              loginName: params.loginName,
              password: params.password,
              emailCode: dialogCheck_form.emailCode,
            }

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

  // 获取登录信息
  const getLoginInfo = async () => {
    try {
      const res = await Service.CustomLoginInfo()
      if (res.code === Code.StatusOK) {
        store.commit('InitInfo', res.data)
        store.commit('InfoExpire', false)
        sessionStorage.setItem('info', JSON.stringify(res.data))
        pigeon.MessageOK(t('Msg.LoginSuccess'))
        setTimeout(() => {
          // 目前可能没有首页先跳有页面的
          router.push({ path: '/card/order' }).catch((err) => console.log(err))
        }, 1000)
      } else {
        store.commit('InfoExpire', false)
        console.error('系统错误')
      }
    } catch (error) {
      console.error('获取登录信息失败:', error)
      loading.value = false
    }
  }

  // 修改语言
  const switchLanguage = async () => {
    const la = 'cn' // 这里应该从 i18n 获取当前语言
    // await Service.switchLanguage({ lang: la })
  }

  // 获取验证码
  const getCode = async (val: number) => {
    if (val && !params.loginName) {
      console.warn('请输入邮箱')
      return
    }

    if (interval.value) return // 防止重复点击
    getCodeString.value = `
    ${t('signup.form.waitCode1')}${timer.value}${t('signup.form.waitCode2')}`

    await getCode1(val)

    interval.value = setInterval(() => {
      timer.value--
      sessionStorage.setItem('timer', timer.value.toString())

      if (timer.value > 0) {
        getCodeString.value = `
    ${t('signup.form.waitCode1')}${timer.value}${t('signup.form.waitCode2')}`
      } else {
        getCodeString.value = t('signup.form.getCode')
        clearInterval(interval.value!)
        interval.value = null
        timer.value = 59
        sessionStorage.setItem('timer', timer.value.toString())
      }
    }, 1000)
  }

  // 发送验证码请求
  const getCode1 = async (val: number) => {
    if (!val) return

    try {
      const res = await Service.sendCode({
        loginName: params.loginName,
        lang: session.Get('lang') || 'en',
      })

      if (res.code === Code.StatusOK) {
        console.log('验证码发送成功')
      } else {
        console.error(res.msg)
      }
    } catch (error) {
      console.error('发送验证码失败:', error)
    }
  }

  // 初始化定时器
  const initTimer = () => {
    const storedTimer = session.Get('timer') || timer.value
    const st = storedTimer ? parseInt(storedTimer) : 59

    if (st === 59) {
      getCodeString.value = t('signup.form.getCode')
    } else {
      timer.value = session.Get('timer')
      getCode(0)
    }
  }

  onMounted(() => {
    initTimer()
  })
  onDeactivated(() => {
    clearInterval(interval.value)
  })
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>
<style lang="scss">
  #signin {
    .el-input__inner {
      border: none !important;
    }
    .el-input__wrapper {
      width: 100%;
      border: none;
      border-bottom: 1px solid;
      border-radius: 0;
      box-shadow: none;
      @include border_gray_1();
    }
    .el-form-item {
      margin-bottom: 40px;
    }
    .el-form-item__content {
      line-height: initial !important;
    }
    .el-input__prefix,
    .el-input__suffix {
      @include font_gray_content_1();
    }
    .s-btn.el-button--danger {
      @include bg_red_1();
    }
  }
</style>
