<script setup lang="tsx">
import { reactive, ref, watch, onMounted, unref, useTemplateRef } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElCheckbox } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { isCaptchaImg, loginApi } from '@/api/login'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'
import Verify from '@/components/verifition/Verify.vue'
import { ElLoading } from 'element-plus'
import { loginRoluData } from '@/utils/analysis'

const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { t } = useI18n()

const rules = {
  username: [required()],
  password: [required()]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold text-center w-[100%]">{t('login.login')}</h2>
        }
      }
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    // value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入账号'
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    // value: 'admin',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入密码'
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox v-model={remember.value} label={t('login.remember')} size="small" />
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  {t('login.login')}
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  }
])
const remember = ref(userStore.getRememberMe)

const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo
  // console.log(loginInfo, 'loginInfo')
  if (loginInfo) {
    const { username, password } = loginInfo
    setValues({ username, password })
  }
}
onMounted(() => {
  initLoginInfo()
})

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const loading = ref(false)

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
const verify = useTemplateRef('verifys')

// 登录
const signIn = async () => {
  //获取表单对象
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserType>()

      try {
        const captcha = await isCaptchaImg({ account: formData.username })
        // console.log(captcha, 'isCaptchaImg')
        // console.log(verify, 'verify')
        // 判断是否需要验证码
        if (captcha.data.is_captcha) {
          verify?.value?.show()
        } else {
          loginForm()
        }
      } finally {
        loading.value = false
      }
    }
  })
}

const loginForm = async (captcha?: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '登陆中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  //获取表单数据
  const formData = await getFormData<UserType>()
  const redata = {
    account: formData.username,
    pwd: formData.password,
    captchaType: '',
    captchaVerification: ''
  }
  if (captcha) {
    redata.captchaType = 'blockPuzzle'
    redata.captchaVerification = captcha.captchaVerification
  }
  //登录
  try {
    const res = await loginApi(redata)

    if (res) {
      // 是否记住我
      if (unref(remember)) {
        userStore.setLoginInfo({
          username: formData.username,
          password: formData.password
        })
      } else {
        userStore.setLoginInfo(undefined)
      }
      userStore.setRoleName(res.data.unique_auth)
      userStore.setRememberMe(unref(remember))
      userStore.setUserInfo(res.data)
      userStore.setToken(res.data.token)
      // 是否使用动态路由
      if (appStore.getDynamicRouter) {
        getRole(res.data.menus)
      } else {
        await permissionStore.generateRoutes('static').catch(() => {})
        permissionStore.getAddRouters.forEach((route) => {
          addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
        })
        permissionStore.setIsAddRouters(true)
        // console.log(permissionStore)
        push({ path: redirect.value || permissionStore.addRouters[0].path })
      }
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.close()
  }
}

// 获取角色信息
const getRole = async (menus: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '获取路由...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    const list = loginRoluData(menus)
    console.log(list, 'list')
    const routers = list || []
    userStore.setRoleRouters(routers)
    appStore.getDynamicRouter && appStore.getServerDynamicRouter
      ? await permissionStore.generateRoutes('server', routers).catch(() => {})
      : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {})
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    // console.log(permissionStore)
    await push({ path: redirect.value || permissionStore.addRouters[0].path })
    loading.close()
  } catch (error) {
    console.log(error)
    loading.close()
  }
}

const success = (params) => {
  loginForm(params)
}
</script>

<template>
  <div>
    <Verify
      @success="success"
      captchaType="blockPuzzle"
      :imgSize="{ width: '330px', height: '155px' }"
      ref="verifys"
    />
    <Form
      :schema="schema"
      :rules="rules"
      label-position="top"
      hide-required-asterisk
      size="large"
      class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
      @register="formRegister"
    />
  </div>
</template>
