<script setup lang="ts">
import type { RouteRecordName, RouteRecordRaw } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { asyncRoutes } from '~/router/routes'
import { FilteredRoutesMap, asyncFilteredRoutes } from '~/router/index'

import bar from '~/assets/img/login/bar.webp'
import { user } from '~/store/index'
import type { User } from '~/store/user/index'
const router = useRouter()
const route = useRoute()
interface IForm {
  user_name: string
  user_password: string
}
const lastForm = localStorage.getItem('login-form')
const form: IForm = reactive(
  lastForm
    ? (JSON.parse(atob(lastForm)))
    : {
        user_name: '',
        user_password: '',
      },
)

const rules: FormRules = reactive({

})

const formRef = $ref<FormInstance>()

const isRemember = $ref(!!lastForm)

function handleLogin() {
  formRef?.validate((valid) => {
    if (valid) {
      localStorage.removeItem('login-form')
      isRemember && localStorage.setItem('login-form', btoa(JSON.stringify(form)))
      // console.log('md5() :>> ', md5(form.user_password))
      // console.log('btoa() :>> ', btoa(md5(form.user_password)))
      // TODO: request login api
      request({
        url: '/user/main/login',
        data: {
          user_main: {
            user_name: form.user_name,
            // user_password: btoa(md5(form.user_password)),
            user_password: form.user_password,
          },
        },
      }).then(async (res) => {
        if (res?.code === '1') {
          user.value = res.data as User
          // await setUserInfo(res.data)
          const _dept_id = user.value.my_org?.filter((item: { uom_default: string }) => item.uom_default === '1')?.[0]?.uo_id_1
          const setting = await request({
            url: '/user/org_menu/setting',
            data: {
              cpm_id: '10000',
              dept_id: _dept_id,
              user_id: user.value.user_id,
              keyname: 'cmu_name',
            },
          })
          const requestRoutes = Object.keys(setting.data.cmu_setting_user).length !== 0 ? setting.data.cmu_setting_user : setting.data.cmu_setting_dept
          const requestRoutesKeyMap: { [key: RouteRecordName]: boolean } = {}
          Object.keys(requestRoutes).forEach((k) => {
            const val = requestRoutes[k]
            if (val?.split(',')?.includes('show'))
              requestRoutesKeyMap[k] = true
          })
          const filteredRoutesMap: { [key: RouteRecordName]: boolean } = {}
          // 维护路由树结构
          const RoutesTreeRelationMap: { [key: RouteRecordName]: { parent: RouteRecordName[]; children?: void } } = {}
          // const leafRouteMap: any = {}
          function initRoutesTreeRelation(routes: RouteRecordRaw[], parent: RouteRecordName[]) {
            routes.forEach((route) => {
              if (!route.name)
                throw new Error(`route name is empty :  ${route?.path}`)

              RoutesTreeRelationMap[route.name] = {
                parent,
                children: route.children === undefined ? undefined : initRoutesTreeRelation(route.children, [...parent, route.name]),
              }
              if (route.children === undefined) {
                // leafRouteMap[route.name] = true
                if (requestRoutesKeyMap[route.name]) {
                  filteredRoutesMap[route.name] = true
                  RoutesTreeRelationMap[route.name].parent.forEach((k: RouteRecordName) => filteredRoutesMap[k] = true)
                }
              }
            })
          }
          initRoutesTreeRelation(asyncRoutes, [])
          FilteredRoutesMap.value = filteredRoutesMap
          // router.replace('/')
          router.push({ path: '/' })
        }
      })
    }
  })
}
</script>

<template>
  <div class="flex">
    <div class="flex-auto flex_center min-w-580px">
      <div class="w-470px flex flex-col">
        <h1 class="text-5xl mb-24">
          蒙阴县教育数字平台
        </h1>
        <el-form ref="formRef" label-position="top" :model="form" :rules="rules" size="large">
          <el-form-item label="账户">
            <el-input v-model="form.user_name" class="h-56px" clearable />
          </el-form-item>
          <el-form-item label="密码" class="mt-8">
            <el-input v-model="form.user_password" type="password" show-password class="h-56px" />
          </el-form-item>
        </el-form>

        <div class="flex justify-between my-6">
          <el-checkbox v-model="isRemember" label="记住密码" size="large" />
          <el-link type="primary" class="text-xs" :underline="false">
            忘记密码
          </el-link>
        </div>

        <div
          class="rounded bg-hex-409eff hover:bg-hex-40bbff h-50px flex_center text-white text-sm font-semibold box_shadow tracking-wider cursor-pointer"
          @click="handleLogin"
        >
          登录
        </div>
      </div>
    </div>
    <div class="h-full min-w-683px bg-hex-3F8CFF w-1/2 flex_center">
      <img :src="bar" alt="" class="h-full">
    </div>
  </div>
</template>

<style lang="scss" scoped>
._shadow {
  text-shadow: 0px 7px 14px 0px rgba(143, 149, 178, 0.15);
  box-shadow: 0px 7px 14px 0px rgba(143, 149, 178, 0.15), 0px 7px 14px 0px rgba(143, 149, 178, 0.15);
}
</style>
