import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { useClientRequest } from '@/utils/request';
import { useUserStore } from '@/store/modules/user';

export interface LoginForm {
    username: string;
    password: string;
    code?: string;
    uuid?: string;
    rememberMe?: boolean;
}

export interface UserInfo {
    id: string;
    username: string;
    nickname: string;
    email?: string;
    phone?: string;
    avatar?: string;
    roles: string[];
    permissions: string[];
}

export interface LoginResponse {
    code: number;
    msg: string;
    token: string;
    user: UserInfo;
}

export const useAuthStore = defineStore('auth', () => {
    const token = ref<string>(getToken() || '');
    const isLoggedIn = ref<boolean>(!!getToken());
    const loading = ref<boolean>(false);
    const loginError = ref<string>('');

    /**
     * 用户登录
     */
    const login = async (loginForm: LoginForm): Promise<boolean> => {
        try {
            loading.value = true;
            loginError.value = '';

            const response = await useClientRequest.post('/auth/login', loginForm) as LoginResponse;
            
            if (response.code === 200) {
                token.value = response.token;
                isLoggedIn.value = true;
                setToken(response.token);
                
                // 存储用户信息到用户store
                const userStore = useUserStore();
                userStore.setUserInfo(response.user);
                
                return true;
            } else {
                loginError.value = response.msg || '登录失败';
                return false;
            }
        } catch (error: any) {
            console.error('Login error:', error);
            loginError.value = error.message || '网络错误，请稍后重试';
            return false;
        } finally {
            loading.value = false;
        }
    };

    /**
     * 用户登出
     */
    const logout = async (): Promise<void> => {
        try {
            console.log('>>>>>>>');
            
            // 调用登出接口
            await useClientRequest.post('/auth/logout');
        } catch (error) {
            console.error('Logout error:', error);
        } finally {
            // 清除本地数据
            token.value = '';
            isLoggedIn.value = false;
            removeToken();
            
            // 清除用户信息
            const userStore = useUserStore();
            userStore.clearUserInfo();
        }
    };

    /**
     * 检查token有效性
     */
    const checkToken = async (): Promise<boolean> => {
        if (!token.value) {
            isLoggedIn.value = false;
            return false;
        }

        try {
            const response = await useClientRequest.get('/auth/check') as any;
            if (response.code === 200) {
                isLoggedIn.value = true;
                return true;
            } else {
                logout();
                return false;
            }
        } catch (error) {
            console.error('Token check error:', error);
            logout();
            return false;
        }
    };

    /**
     * 刷新token
     */
    const refreshToken = async (): Promise<boolean> => {
        try {
            const response = await useClientRequest.post('/auth/refresh') as any;
            if (response.code === 200) {
                token.value = response.token;
                setToken(response.token);
                return true;
            }
            return false;
        } catch (error) {
            console.error('Refresh token error:', error);
            return false;
        }
    };

    return {
        // 状态
        token,
        isLoggedIn,
        loading,
        loginError,
        
        // 方法
        login,
        logout,
        checkToken,
        refreshToken
    };
});
