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';
import useRouteStore from '../../store/route'



// 定义状态
const stateGenerator = (): ReadonlyState => ({
    buttonLoading: false,
    tenantEnabled: true,
    tenantEnabledList: [],
    captchaData: {
        uuid: '',
        img: ''
    }
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setButtonLoading: (loading) => {
            state.buttonLoading = loading;
        },
        setCaptchaData: (data: any) => {
            state.captchaData = data
        },
        setTenantEnabled: (data: any) => {
            state.tenantEnabled = data.tenantEnabled
            state.tenantEnabledList = data.voList.map((item: any) => {
                return {
                    value: item.tenantId,
                    label: item.companyName,
                    domain: item.domain,
                }
            })
        }
    };
};

// 使用仓库
const useLoginStore = (): LoginStore => {
    const state = makeAutoObservable(stateGenerator());
    const actions = stateActionsGenerator(state);
    const {
        onSetRoutes
    } = useRouteStore;
    const api = {
        // 登录
        login: async (data: LoginApiParams, remember: boolean, navigate: any,redirectUrl?:any) => {
            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.access_token);
                // 获取用户详细信息（permissions,role, user）
                const resuser = await apis.fetchUserInfo();
                if (resuser.code === 200) {
                    const resUserInfo = resuser.data;
                    LocalStorage.setPermissions(resUserInfo.permissions);
                    LocalStorage.setUserInfo({
                        id: resUserInfo.user.userId,
                        name: resUserInfo.user.nickName,
                        tenantId: resUserInfo.user.tenantId,
                    });
                    // 这里要先去调用获取路由的接口，路由弄好以后再去进行跳转
                    onFetchClientRouters(navigate,1,redirectUrl)
                    message.success('登录成功');
                }
            } catch (error: any) {
                LocalStorage.clear();
                message.error(error.msg);
                api.captchaImage()
            } finally {
                actions.setButtonLoading(false);
            }
        },
        // 验证码
        captchaImage: async () => {
            try {
                const res = await apis.captchaImage();
                actions.setCaptchaData(res?.data || {});
                return res;
            } catch (error: any) {
                console.log('error', error)
                message.error(error);
            }
        }
    }
    // 获取客户端路由
    const onFetchClientRouters = async (navigate?: any,typelink?: number,redirectUrl?:any) => {
        const res: any = await apis.fetchClientRouters()
        if (res.code !== 200) {
            return
        }
        // 将后端返回的路由递归转换为 store/route.tsx 中 businessRoutes 的格式（只打印，不替换）
        const convertToBusinessRoutes = (nodes: any[], Parent?: string): any[] => {
            if (!Array.isArray(nodes)) return [];
            return nodes.map((node: any, idx: number) => {
                const handle: any = {};
                if (node.path !== '/list') {
                    handle.breadcrumbName = node.meta?.title || '';
                }
                // if (node.icon || node.meta?.icon) handle.icon = node.icon || node.meta.icon;
                if (node.meta?.hidden !== undefined) handle.hidden = node.meta.hidden;
                const route: any = {};
                if (node.path === '/list') route.index = true;
                if (node.path && node.path !== '/list') route.path = `${Parent}${node.path}`;
                if (node.component && node.component.includes('/pages')) {
                    route.element = `@${node.component}`
                }
                // 不尝试解析组件加载，这里只保留 handle/children 等元信息
                route.handle = handle;
                if (Array.isArray(node.children) && node.children.length > 0) {
                    route.children = convertToBusinessRoutes(node.children, route.path);
                }
                return route;
            });
        }

        const converted = convertToBusinessRoutes(res.data, '');
        onSetRoutes(converted)
        if(typelink!==1||!navigate){ 
            return 
        }
        console.log('redirectUrl',redirectUrl)
        if(redirectUrl){
            const userInfo = LocalStorage.getUserInfo();
            const getToken = LocalStorage.getToken();
            window.location.replace(`${redirectUrl}&userId=${userInfo?.id}&nickName=${userInfo?.name}&token=${getToken}`);
            return
        }
        if (converted[0]?.path === '/overview') {
                navigate({ pathname: converted[0].path }, { replace: true });
        } else {
                navigate({ pathname: '/' }, { replace: true });
        }
    }

    // 点击登录
    const onClickLogin: LoginStore['onClickLogin'] = async (data, remember, navigate,redirectUrl) => {
        // 登录
        await api.login(data, remember, navigate,redirectUrl);
    }
    // 切换验证码
    const onCaptchaImage = async () => {
        await api.captchaImage();
    }



    // 初始渲染
    const init: LoginStore['init'] = async (form, navigate: any) => {
        api.captchaImage();
        const res = await apis.getTenantList(false)
        if (res.data.tenantEnabled) {
            actions.setTenantEnabled(res.data)
            form.setFieldsValue({
                tenantId: res.data?.tenantEnabled ? res.data?.voList[0].tenantId : null,
            });
        }
        const accountPassword = LocalStorage.getAccountPassword();
        if (accountPassword) {
            form.setFieldsValue({
                account: accountPassword.account,
                password: accountPassword.password,
                remember: true,
                tenantId: res.data?.tenantEnabled ? res.data?.voList[0].tenantId : null,
            });
        }
    }

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

        actions.setButtonLoading(initialButtonLoading);
    }

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

export default useLoginStore();
