import { makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { apis, LoginApiParams } from '@/apis';
import LocalStorage from '@/LocalStorage';
import router from '@/router';
import { State, ReadonlyState, StateAction, LoginStore } from './types';

// 定义状态
const stateGenerator = (): ReadonlyState => ({
    buttonLoading: false,
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setButtonLoading: (loading) => {
            state.buttonLoading = loading;
        },
    };
};

// 使用仓库
const useLoginStore = (): LoginStore => {
    const state = makeAutoObservable(stateGenerator());
    const actions = stateActionsGenerator(state);

    const api = {
        // 登录
        login: async (data: LoginApiParams, remember: boolean) => {
            actions.setButtonLoading(true);
            try {
                const res = await apis.login(data);
                const info = res.data;
                if (remember) {// 记住密码
                    LocalStorage.setAccountPassword({
                        account: data.userName,
                        password: data.password,
                    });
                } else {// 不记住密码
                    LocalStorage.setAccountPassword(undefined);
                }
                // 首次登陆，重置菜单类型
                LocalStorage.setMenuType(1);
                LocalStorage.setToken(info.token);
                LocalStorage.setUserInfo({
                    id: info.userId,
                    name: info.nickName,
                });
                // 获取用户详细信息（permissions,role, user）
                const resUserInfo = await apis.fetchUserInfo(info.userId);
                if (resUserInfo.code === 200) {
                    LocalStorage.setPermissions(resUserInfo.permissions);
                    LocalStorage.setRoles(resUserInfo.roles);
                    if (!LocalStorage.getStatusFlag('deepseek:application:list') &&
                        !LocalStorage.getStatusFlag('deepseek:knowledge:list') &&
                        !LocalStorage.getStatusFlag('deepseek:dialog:list') &&
                        !LocalStorage.getStatusFlag('system:audit:list')) {
                        message.error('权限不足，请联系管理员');
                        LocalStorage.clear();
                        router.navigate({ pathname: '/login' }, { replace: true });
                        return;
                    }
                    if (LocalStorage.getStatusFlag('deepseek:application:list')) {
                        router.navigate({ pathname: '/deepseek/questionAnswer' }, { replace: true });
                    } else {
                        router.navigate({ pathname: '/404' }, { replace: true });
                    }
                    message.success('登录成功');
                }
            } catch (error: any) {
                LocalStorage.clear();
                message.error(error.msg);
            } finally {
                actions.setButtonLoading(false);
            }
        },
    }

    // 点击登录
    const onClickLogin: LoginStore['onClickLogin'] = async (data, remember) => {
        // 登录
        await api.login(data, remember);
    }

    // 初始渲染
    const init: LoginStore['init'] = (form) => {
        const accountPassword = LocalStorage.getAccountPassword();
        if (accountPassword) {
            form.setFieldsValue({
                account: accountPassword.account,
                password: accountPassword.password,
                remember: true,
            });
        }
    }

    // 状态重置
    const reset: LoginStore['reset'] = () => {
        const initialButtonLoading = stateGenerator().buttonLoading;

        actions.setButtonLoading(initialButtonLoading);
    }

    return {
        state,
        onClickLogin,
        init,
        reset
    };
};

export default useLoginStore();
