<!-- 登录页面 -->
<template>
  <div class="flex w-full h-screen">
    <LoginLeftView />

    <div class="relative flex-1">
      <AuthTopBar />

      <div class="auth-right-wrap">
        <div class="form">
          <h3 class="title">{{ $t('login.title') }}</h3>
          <p class="sub-title">{{ $t('login.subTitle') }}</p>
          <ElForm
            ref="formRef"
            :model="formData"
            :rules="rules"
            :key="formKey"
            @keyup.enter="handleSubmit"
            style="margin-top: 25px"
          >
            <ElFormItem prop="account">
              <ElInput
                class="custom-height"
                :placeholder="$t('login.placeholder.account')"
                v-model.trim="formData.account"
              />
            </ElFormItem>
            <ElFormItem prop="phone">
              <ElInput
                class="custom-height"
                :placeholder="$t('login.placeholder.phone')"
                v-model.trim="formData.phone"
              />
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput
                class="custom-height"
                :placeholder="$t('login.placeholder.password')"
                v-model.trim="formData.password"
                type="password"
                autocomplete="off"
                show-password
              />
            </ElFormItem>

            <!-- 推拽验证（暂时注释掉，如需启用还原此区块）
            <div class="relative pb-5 mt-6">
              <div
                class="relative z-[2] overflow-hidden select-none rounded-lg border border-transparent tad-300"
                :class="{ '!border-[#FF4E4F]': !isPassing && isClickPass }"
              >
                <ArtDragVerify
                  ref="dragVerify"
                  v-model:value="isPassing"
                  :text="$t('login.sliderText')"
                  textColor="var(--art-gray-700)"
                  :successText="$t('login.sliderSuccessText')"
                  progressBarBg="var(--main-color)"
                  :background="isDark ? '#26272F' : '#F1F1F4'"
                  handlerBg="var(--default-box-color)"
                />
              </div>
              <p
                class="absolute top-0 z-[1] px-px mt-2 text-xs text-[#f56c6c] tad-300"
                :class="{ 'translate-y-10': !isPassing && isClickPass }"
              >
                {{ $t('login.placeholder.slider') }}
              </p>
            </div>
            -->

            <div class="flex-cb mt-2 text-sm">
              <ElCheckbox v-model="formData.rememberPassword">{{
                $t('login.rememberPwd')
              }}</ElCheckbox>
              <RouterLink class="text-theme" :to="{ name: 'ForgetPassword' }">{{
                $t('login.forgetPwd')
              }}</RouterLink>
            </div>

            <div style="margin-top: 30px">
              <ElButton
                class="w-full custom-height"
                type="primary"
                @click="handleSubmit"
                :loading="loading"
                v-ripple
              >
                {{ $t('login.btnText') }}
              </ElButton>
            </div>

            <!-- 平台管理端不提供自助注册入口 -->
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import AppConfig from '@/config'
  import { useUserStore } from '@/store/modules/user'
  import { useI18n } from 'vue-i18n'
  import { HttpError } from '@/utils/http/error'
  import { fetchLogin } from '@/api/auth'
  import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
  import {
    clearRememberLogin,
    loadRememberLogin,
    saveRememberLogin
  } from '@/utils/storage/remember-login'

  defineOptions({ name: 'Login' })

  const { t, locale } = useI18n()
  const formKey = ref(0)

  // 监听语言切换，重置表单
  watch(locale, () => {
    formKey.value++
  })

  const dragVerify = ref()

  const userStore = useUserStore()
  const router = useRouter()
  const route = useRoute()
  const isPassing = ref(true)

  const systemName = AppConfig.systemInfo.name
  const formRef = ref<FormInstance>()

  const formData = reactive({
    account: '',
    phone: '',
    password: '',
    rememberPassword: true
  })
  const loginUserName = computed(
    () => userStore.getUserInfo.displayName || userStore.getUserInfo.account || systemName
  )

  const rules = computed<FormRules>(() => ({
    account: [{ required: true, message: t('login.placeholder.account'), trigger: 'blur' }],
    phone: [{ required: true, message: t('login.placeholder.phone'), trigger: 'blur' }],
    password: [{ required: true, message: t('login.placeholder.password'), trigger: 'blur' }]
  }))

  const loading = ref(false)

  onMounted(() => {
    // 1. 读取记住的账号、手机号与密码
    const rememberedLogin = loadRememberLogin()
    if (rememberedLogin) {
      formData.account = rememberedLogin.accountName
      formData.phone = rememberedLogin.phone
      formData.password = rememberedLogin.password
      formData.rememberPassword = true
    } else {
      formData.rememberPassword = false
    }
  })

  // 登录
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      // 1. 表单验证
      const valid = await formRef.value.validate()
      if (!valid) return

      // 2. 滑块验证（当前已禁用，直接通过）
      isPassing.value = true

      // 3. 读取表单数据
      const { account: accountName, phone, password, rememberPassword } = formData
      loading.value = true

      // 4. 处理本地记住信息
      if (rememberPassword && accountName && phone && password) {
        saveRememberLogin({ accountName, phone, password })
      } else {
        clearRememberLogin()
      }

      // 5. 登录请求
      const { accessToken, refreshToken, user } = await fetchLogin({
        accountName,
        phone,
        password
      })

      // 6. 验证token
      if (!accessToken) {
        throw new Error('Login failed - no token received')
      }

      // 7. 存储 token、用户信息和登录状态
      userStore.setToken(accessToken, refreshToken)
      if (user) {
        userStore.setUserInfo(user)
      }
      userStore.setLoginStatus(true)

      // 8. 登录成功处理
      showLoginSuccessNotice()

      // 9. 登录后跳转（平台管理端不处理租户入驻流程）
      const redirect = route.query.redirect as string | undefined
      router.push(redirect || '/')
    } catch (error) {
      // 处理 HttpError
      if (error instanceof HttpError) {
        // console.log(error.code)
      } else {
        // 处理非 HttpError
        // ElMessage.error('登录失败，请稍后重试')
        console.error('[Login] Unexpected error:', error)
      }
    } finally {
      loading.value = false
      resetDragVerify()
    }
  }

  // 重置拖拽验证
  const resetDragVerify = () => {
    if (dragVerify.value?.reset) {
      dragVerify.value.reset()
    }
  }

  // 登录成功提示
  const showLoginSuccessNotice = () => {
    setTimeout(() => {
      ElNotification({
        title: t('login.success.title'),
        type: 'success',
        duration: 2500,
        zIndex: 10000,
        message: `${t('login.success.message')}, ${loginUserName.value}!`
      })
    }, 1000)
  }
</script>

<style scoped>
  @import './style.css';
</style>

<style lang="scss" scoped>
  :deep(.el-select__wrapper) {
    height: 40px !important;
  }
</style>
