<template>
  <ld-login
    v-model="form"
    :layout="layout"
    :captcha-url="captchaUrl"
    @login="handleLogin"
    @loginSuccess="handleLoginSuccess"
  >
    <template #title>
      <l-space align="center">
        <img style="width:42px;height:42px;vertical-align: middle;" src="@/assets/logo.svg"/>
        <div style="line-height:1;">{{ title }}</div>
      </l-space>
    </template>
    <template #footer>
      Copyright © 1998 - 2023 Longrise. All Rights Reserved. 永兴元公司 版权所有
    </template>
    <template #background>
      <img src="@/assets/login/default/bg.jpg" alt="">
    </template>
    <template #banner>
      <img src="@/assets/login/default/banner.svg" alt="">
    </template>
  </ld-login>
</template>
<script setup lang="ts">
import type { AppConfig, LeapApi } from '@ldesign/business-next';
import { computed, inject, onBeforeMount, reactive, ref, type PropType } from 'vue';
import { useRouter } from '@ldesign/business-next';

const props = defineProps({
  appConfig: {
    type: Object as PropType<AppConfig>,
    default: {}
  }
})

const $api = inject<LeapApi>('$api', {} as any)

const layout = computed(() => props.appConfig.login_layout)

const title = computed(() => props.appConfig.system_title)

const $router = useRouter()

const form = reactive({
  password: {
    name: '',
    password: '',
    captcha: '',
    remember: false
  },
  phone: {
    name: '',
    password: '',
    captcha: '',
    code: ''
  }
})

const captchaUrl = ref<string | null>(null)

const handleLogin = (res: any, type: string) => {
  return new Promise(async (resolve) => {
    let cb: any = null
    if (type === 'password') {
      cb = await $api.loginApi.loginByPassword(
        res.name,
        res.password,
        res.captcha
      )
    }
    resolve(cb)
  })
}

const rememberPassword = () => {
  const {name, password, remember} = form.password
  if (!remember) {
    localStorage.removeItem(`${name}_pass`)
    localStorage.removeItem(`${name}_code`)
    localStorage.removeItem('LOGINUSER')
  } else {
    $api.loginApi.saveUserPasswordLocal(name, password)
  }
}

const getLocalPassword = () => {
  const username = localStorage.getItem('LOGINUSER') as string
  const password = $api.loginApi.getSavedPasswordByUser(username) as string
  form.password.name = username
  form.password.password = password
  if (username && password) {
    form.password.remember = true
  }
}

const handleLoginSuccess = async () => {
  rememberPassword()
  console.log('登录成功')
  $router.replace('/home')

}

onBeforeMount(async () => {
  await $api.loginApi.getSid()
  await getLocalPassword()
  captchaUrl.value = $api.loginApi.getValiCode()
})

</script>