<script setup lang="ts">
import { computed, reactive } from 'vue';
import { $t } from '@/locales';
import { useMessage } from 'naive-ui'
import { loginModuleRecord } from '@/constants/app';
import { useRouterPush } from '@/hooks/common/router';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { api_login, api_permission } from '@/api/index.ts'
import { useRouter } from 'vue-router';
import { localStg } from '@/utils/storage';
import { generatedRoutes } from "@/router/elegant/routes"

defineOptions({
  name: 'PwdLogin'
});

let routerList = reactive([]);


const routes = [
  {
    name: '403',
    path: '/403',
    component: 'layout.blank$view.403',
    meta: {
      title: '403',
      i18nKey: 'route.403',
      constant: true,
      hideInMenu: true
    }
  },
  {
    name: '404',
    path: '/404',
    component: 'layout.blank$view.404',
    meta: {
      title: '404',
      i18nKey: 'route.404',
      constant: true,
      hideInMenu: true
    }
  },
  {
    name: '500',
    path: '/500',
    component: 'layout.blank$view.500',
    meta: {
      title: '500',
      i18nKey: 'route.500',
      constant: true,
      hideInMenu: true
    }
  },
  {
    name: 'alarmcenter',
    path: '/alarmcenter',
    component: 'layout.base',
    meta: {
      title: 'alarmcenter',
      i18nKey: 'route.alarmcenter',
      order: 7,
      icon: 'ic:twotone-hearing'
    },
    children: [
      {
        name: 'alarmcenter_alarmlog',
        path: '/alarmcenter/alarmlog',
        component: 'view.alarmcenter_alarmlog',
        meta: {
          title: 'alarmcenter_alarmlog',
          i18nKey: 'route.alarmcenter_alarmlog',
          icon: 'ic:sharp-receipt-long'
        }
      },
      {
        name: 'alarmcenter_alarmpush',
        path: '/alarmcenter/alarmpush',
        component: 'view.alarmcenter_alarmpush',
        meta: {
          title: 'alarmcenter_alarmpush',
          i18nKey: 'route.alarmcenter_alarmpush',
          icon: 'ic:sharp-notifications-active'
        }
      },
      {
        name: 'alarmcenter_alarmreminder',
        path: '/alarmcenter/alarmreminder',
        component: 'view.alarmcenter_alarmreminder',
        meta: {
          title: 'alarmcenter_alarmreminder',
          i18nKey: 'route.alarmcenter_alarmreminder',
          icon: 'ic:baseline-legend-toggle'
        }
      }
    ]
  },
  {
    name: 'algorithmconfiguration',
    path: '/algorithmconfiguration',
    component: 'layout.base$view.algorithmconfiguration',
    meta: {
      title: 'algorithmconfiguration',
      i18nKey: 'route.algorithmconfiguration',
      order: 2,
      icon: 'ic:outline-storage'
    }
  },
  {
    name: 'home',
    path: '/home',
    component: 'layout.base$view.home',
    meta: {
      title: 'home',
      i18nKey: 'route.home',
      icon: 'mdi:monitor-dashboard',
      order: 0
    }
  },
  {
    name: 'iframe-page',
    path: '/iframe-page/:url',
    component: 'layout.base$view.iframe-page',
    props: true,
    meta: {
      title: 'iframe-page',
      i18nKey: 'route.iframe-page',
      constant: true,
      hideInMenu: true,
      keepAlive: true
    }
  },
  {
    name: 'login',
    path: '/login/:module(pwd-login|code-login|register|reset-pwd|bind-wechat)?',
    component: 'layout.blank$view.login',
    props: true,
    meta: {
      title: 'login',
      i18nKey: 'route.login',
      constant: true,
      hideInMenu: true
    }
  },
  {
    name: 'manage',
    path: '/manage',
    component: 'layout.base',
    meta: {
      title: 'manage',
      i18nKey: 'route.manage',
      icon: 'carbon:cloud-service-management',
      order: 9,
    },
    children: [
      {
        name: 'manage_role',
        path: '/manage/role',
        component: 'view.manage_role',
        meta: {
          title: 'manage_role',
          i18nKey: 'route.manage_role',
          icon: 'carbon:user-role',
          order: 2,
        }
      },
      {
        name: 'manage_user',
        path: '/manage/user',
        component: 'view.manage_user',
        meta: {
          title: 'manage_user',
          i18nKey: 'route.manage_user',
          icon: 'ic:round-manage-accounts',
          order: 1,
        }
      }
    ]
  },
  {
    name: 'user-center',
    path: '/user-center',
    component: 'layout.base$view.user-center',
    meta: {
      title: 'user-center',
      i18nKey: 'route.user-center',
      hideInMenu: true
    }
  },
  {
    name: 'videoanalysistask',
    path: '/videoanalysistask',
    component: 'layout.base$view.videoanalysistask',
    meta: {
      title: 'videoanalysistask',
      i18nKey: 'route.videoanalysistask',
      order: 3,
      icon: 'ic:outline-candlestick-chart'
    }
  },
  {
    name: 'webcamconfiguration',
    path: '/webcamconfiguration',
    component: 'layout.base$view.webcamconfiguration',
    meta: {
      title: 'webcamconfiguration',
      i18nKey: 'route.webcamconfiguration',
      order: 2,
      icon: 'ic:outline-video-camera-back'
    }
  }
];

const authStore = useAuthStore();

const getPermission = async () => {
  await api_permission().then(res => {
    if (res.data && res.data.code === 200) {
      routerList = res.data.data.map(item => item.label);

      localStg.set("permission", routerList);
      console.log("=============== routerList", routerList)

      // authStore.login(model.userName, model.password);

      for (let key of routerList) {


        for (let router of routes) {

        }
      }
      // authStore.routes =
    }
  })
}



const router = useRouter();

const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useNaiveForm();

const message = useMessage();

interface FormModel {
  userName: string;
  password: string;
}

const model: FormModel = reactive({
  userName: '',
  password: ''
});


const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale reactive, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    userName: formRules.userName,
    password: formRules.pwd
  };
});


const toLogin = async () => {

  if (!model.userName) {
    return message.error("请输入用户名！")
  }

  if (!model.password) {
    return message.error("请输入账号密码！")
  }


  await api_login(model).then(async res => {
    if (res.data.code === 200) {
      localStg.set('token', res.data.data.token);
      localStg.set('id', res.data.data.id);
      localStg.set('refreshToken', res.data.data.token);
      localStg.set('userInfo', res.data.data.userName);
      await getPermission();
      // setTimeout(() => {
      //   router.push('/demo?reload')
      // }, 1000)
      router.push('/demo?reload=true#f')
      return message.success("登录成功！")
    }
    return message.error(res.data.msg);
  });
}


// ============================= 表单提交
async function handleSubmit() {
  // await validate();
  await toLogin();

  // await authStore.login(model.userName, model.password);
}

type AccountKey = 'super' | 'admin' | 'user';

interface Account {
  key: AccountKey;
  label: string;
  userName: string;
  password: string;
}

const accounts = computed<Account[]>(() => [
  {
    key: 'super',
    label: $t('page.login.pwdLogin.superAdmin'),
    userName: 'Super',
    password: '123456'
  },
  {
    key: 'admin',
    label: $t('page.login.pwdLogin.admin'),
    userName: 'Admin',
    password: '123456'
  },
  {
    key: 'user',
    label: $t('page.login.pwdLogin.user'),
    userName: 'User',
    password: '123456'
  }
]);

async function handleAccountLogin(account: Account) {
  await authStore.login(account.userName, account.password);
}
</script>

<template>
  <!-- :rules="rules" -->
  <NForm ref="formRef" :model="model" size="large" :show-label="false">
    <NFormItem path="userName">
      <NInput v-model:value="model.userName" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>

    <NFormItem path="password">
      <NInput v-model:value="model.password" type="password" show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')" />
    </NFormItem>
    <NSpace vertical :size="24">
      <div class="flex-y-center justify-between">
        <NCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</NCheckbox>
        <!-- <NButton quaternary @click="toggleLoginModule('reset-pwd')">
          {{ $t('page.login.pwdLogin.forgetPassword') }}
        </NButton> -->
      </div>
      <!-- :loading="authStore.loginLoading" -->
      <NButton type="primary" size="large" round block @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
      <!-- <div class="flex-y-center justify-between gap-12px">
        <NButton class="flex-1" block @click="toggleLoginModule('code-login')">
          {{ $t(loginModuleRecord['code-login']) }}
        </NButton>
        <NButton class="flex-1" block @click="toggleLoginModule('register')">
          {{ $t(loginModuleRecord.register) }}
        </NButton>
      </div> -->
      <!-- <NDivider class="text-14px text-#666 !m-0">{{ $t('page.login.pwdLogin.otherAccountLogin') }}</NDivider>
      <div class="flex-center gap-12px">
        <NButton v-for="item in accounts" :key="item.key" type="primary" @click="handleAccountLogin(item)">
          {{ item.label }}
        </NButton>
      </div> -->
    </NSpace>
  </NForm>
</template>

<style scoped></style>
