<template>
  <el-form
    v-show="getShow"
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    class="mobile-login-form"
    label-position="top"
    size="large"
  >
    <div class="mobile-login-form__title"><LoginFormTitle /></div>

    <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
      <el-input
        v-model="loginData.loginForm.tenantName"
        :placeholder="t('login.tenantNamePlaceholder')"
        :prefix-icon="iconHouse"
      />
    </el-form-item>

    <el-form-item prop="username">
      <el-input
        v-model="loginData.loginForm.username"
        :placeholder="t('login.usernamePlaceholder')"
        :prefix-icon="iconAvatar"
      />
    </el-form-item>

    <el-form-item prop="password">
      <el-input
        v-model="loginData.loginForm.password"
        :placeholder="t('login.passwordPlaceholder')"
        :prefix-icon="iconLock"
        show-password
        type="password"
        @keyup.enter="getCode()"
      />
    </el-form-item>

    <el-form-item prop="captcha">
      <div class="mobile-login-form__captcha">
        <el-input
          v-model="loginData.loginForm.captcha"
          placeholder="请输入验证码"
          maxlength="4"
          class="mobile-login-form__captcha-input"
        />
        <canvas
          ref="captchaCanvas"
          width="100"
          height="40"
          class="mobile-login-form__captcha-canvas"
          @click="drawCaptcha"
        ></canvas>
      </div>
    </el-form-item>

    <div class="mobile-login-form__options">
      <el-checkbox v-model="loginData.loginForm.rememberMe">
        {{ t('login.remember') }}
      </el-checkbox>
      <el-link
        type="primary"
        :underline="false"
        @click="setLoginState(LoginStateEnum.RESET_PASSWORD)"
      >
        {{ t('login.forgetPassword') }}
      </el-link>
    </div>

    <el-form-item>
      <el-button
        :loading="loginLoading"
        type="primary"
        class="mobile-login-form__btn"
        @click="getCode()"
      >
        {{ t('login.login') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
import { ref, onMounted, defineExpose } from 'vue'

defineOptions({ name: 'LoginForm' })

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { setLoginState, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const captchaCode = ref('')
const captchaCanvas = ref<HTMLCanvasElement | null>(null)

function randomString(len = 4) {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
  let str = ''
  for (let i = 0; i < len; i++) {
    str += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return str.toUpperCase()
}

function drawCaptcha() {
  captchaCode.value = randomString()
  const canvas = captchaCanvas.value
  if (!canvas) return
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.font = '22px Arial'
  ctx.fillStyle = '#333'
  ctx.textBaseline = 'middle'
  ctx.fillText(captchaCode.value, 18, 18)
  // 干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = '#bbb'
    ctx.beginPath()
    ctx.moveTo(Math.random()*90, Math.random()*36)
    ctx.lineTo(Math.random()*90, Math.random()*36)
    ctx.stroke()
  }
}

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: 'YAVII',
    username: 'YAVII',
    password: 'yavii123',
    captcha: '', // 新增验证码字段
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

const socialList = [
  { icon: 'ant-design:wechat-filled', type: 30 },
  { icon: 'ant-design:dingtalk-circle-filled', type: 20 },
  { icon: 'ant-design:github-filled', type: 0 },
  { icon: 'ant-design:alipay-circle-filled', type: 0 }
]

// 获取验证码
const getCode = async () => {
  // 先校验表单
  const data = await validForm()
  if (!data) return
  // 再校验验证码
  if (loginData.loginForm.captcha.trim().toUpperCase() !== captchaCode.value) {
    message.error('验证码错误')
    drawCaptcha()
    return
  }
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}
// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    authUtil.setTenantId(res)
  }
}
// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}
// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  const website = location.host
  const res = await LoginApi.getTenantByWebsite(website)
  if (res) {
    loginData.loginForm.tenantName = res.name
    authUtil.setTenantId(res.id)
  }
}
const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params: any) => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }
    const loginDataLoginForm = { ...loginData.loginForm }
    loginDataLoginForm.captchaVerification = params.captchaVerification
    const res = await LoginApi.login(loginDataLoginForm)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginDataLoginForm.rememberMe) {
      authUtil.setLoginForm(loginDataLoginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      await push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
    loading.value.close()
  }
}

// 社交登录
const doSocialLogin = async (type: number) => {
  if (type === 0) {
    message.error('此方式未配置')
  } else {
    loginLoading.value = true
    if (loginData.tenantEnable === 'true') {
      // 尝试先通过 tenantName 获取租户
      await getTenantId()
      // 如果获取不到，则需要弹出提示，进行处理
      if (!authUtil.getTenantId()) {
        try {
          const data = await message.prompt('请输入租户名称', t('common.reminder'))
          if (data?.action !== 'confirm') throw 'cancel'
          const res = await LoginApi.getTenantIdByName(data.value)
          authUtil.setTenantId(res)
        } catch (error) {
          if (error === 'cancel') return
        } finally {
          loginLoading.value = false
        }
      }
    }
    // 计算 redirectUri
    // 注意: type、redirect 需要先 encode 一次，否则钉钉回调会丢失。
    // 配合 social-login.vue#getUrlValue() 使用
    const redirectUri =
      location.origin +
      '/social-login?' +
      encodeURIComponent(`type=${type}&redirect=${redirect.value || '/'}`)

    // 进行跳转
    window.location.href = await LoginApi.socialAuthRedirect(type, encodeURIComponent(redirectUri))
  }
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getLoginFormCache()
  getTenantByWebsite()
  drawCaptcha()
})
</script>

<style lang="scss" scoped>
.mobile-login-form {
  width: 100%;
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
  &__title {
    margin-bottom: 24px;
  }
  &__captcha {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
  }
  &__captcha-input {
    flex: 1;
  }
  &__captcha-canvas {
    flex-shrink: 0;
    border-radius: 6px;
    background: #f5f5f5;
    cursor: pointer;
  }
  &__options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;
    margin-top: -8px;
  }
  &__btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    border-radius: 8px;
  }
}
</style>
