import { create } from 'zustand';
import { message } from 'antd';
import { apis, LoginApiParams } from '@/apis';
import LocalStorage from '@/LocalStorage';
import useRouteStore from '../../store/route';

export interface CaptchaData {
    uuid: string;
    img: string;
}

export interface TenantItem {
    value: string;
    label: string;
    domain: string;
}

interface LoginState {
    buttonLoading: boolean;
    tenantEnabled: boolean;
    tenantEnabledList: TenantItem[];
    captchaData: CaptchaData;
}

interface LoginActions {
    setButtonLoading: (loading: boolean) => void;
    setCaptchaData: (data: CaptchaData) => void;
    setTenantEnabled: (data: any) => void;
}

export type LoginStore = LoginState & LoginActions & {
    // Actions
    login: (data: LoginApiParams, remember: boolean, navigate: any, redirectUrl?: any) => Promise<void>;
    captchaImage: () => Promise<void>;
    onClickLogin: (data: LoginApiParams, remember: boolean, navigate: any, redirectUrl?: any) => Promise<void>;
    onCaptchaImage: () => Promise<void>;
    init: (form: any, navigate: any) => Promise<void>;
    reset: () => void;
};

const initialState: LoginState = {
    buttonLoading: false,
    tenantEnabled: true,
    tenantEnabledList: [],
    captchaData: {
        uuid: '',
        img: ''
    }
};

export const useLoginStore = create<LoginStore>((set, get) => ({
    ...initialState,
    
    setButtonLoading: (loading) => set({ buttonLoading: loading }),
    
    setCaptchaData: (data) => set({ captchaData: data }),
    
    setTenantEnabled: (data) => set({
        tenantEnabled: data.tenantEnabled,
        tenantEnabledList: data.voList?.map((item: any) => ({
            value: item.tenantId,
            label: item.companyName,
            domain: item.domain,
        })) || [],
    }),
    
    login: async (data, remember, navigate, redirectUrl) => {
        set({ buttonLoading: 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);
            
            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,
                });
                
                get().onFetchClientRouters(navigate, 1, redirectUrl);
                message.success('登录成功');
            }
        } catch (error: any) {
            LocalStorage.clear();
            message.error(error.msg);
            get().captchaImage();
        } finally {
            set({ buttonLoading: false });
        }
    },
    
    captchaImage: async () => {
        try {
            const res = await apis.captchaImage();
            set({ captchaData: res?.data || {} });
        } catch (error: any) {
            console.error('验证码获取失败:', error);
        }
    },
    
    onClickLogin: async (data, remember, navigate, redirectUrl) => {
        await get().login(data, remember, navigate, redirectUrl);
    },
    
    onCaptchaImage: async () => {
        await get().captchaImage();
    },
    
    init: async (form, navigate) => {
        await get().captchaImage();
        const res = await apis.getTenantList(false);
        if (res.data.tenantEnabled) {
            get().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,
            });
        }
    },
    
    reset: () => {
        set({ buttonLoading: initialState.buttonLoading });
    },
    
    onFetchClientRouters: async (navigate?: any, typelink?: number, redirectUrl?: any) => {
        const res: any = await apis.fetchClientRouters();
        if (res.code !== 200) return;
        
        const { onSetRoutes } = useRouteStore.getState();
        
        const convertToBusinessRoutes = (nodes: any[], Parent?: string): any[] => {
            if (!Array.isArray(nodes)) return [];
            return nodes.map((node: any) => {
                const handle: any = {};
                if (node.path !== '/list') {
                    handle.breadcrumbName = node.meta?.title || '';
                }
                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}`;
                }
                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;
        
        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 });
        }
    },
}));
