import { defineStore } from 'pinia';
import { ref } from 'vue';
import storage from '@/utils/storage';
import { useClientRequest } from '@/utils/request';
import upload from '@/utils/upload';

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

export interface UserProfile extends UserInfo {
    createTime?: string;
    updateTime?: string;
    lastLoginTime?: string;
    status?: number;
    dept?: {
        id: string;
        name: string;
    };
}

interface ApiResponse<T = any> {
    code: number;
    msg: string;
    data: T;
}

const USER_INFO_KEY = 'userInfo';

export const useUserStore = defineStore('user', () => {
    const userInfo = ref<UserInfo | null>(storage.get(USER_INFO_KEY));
    const profile = ref<UserProfile | null>(null);

    /**
     * 设置用户信息
     */
    const setUserInfo = (info: UserInfo): void => {
        userInfo.value = info;
        storage.set(USER_INFO_KEY, info);
    };

    /**
     * 更新用户信息
     */
    const updateUserInfo = (updates: Partial<UserInfo>): void => {
        if (userInfo.value) {
            userInfo.value = { ...userInfo.value, ...updates };
            storage.set(USER_INFO_KEY, userInfo.value);
        }
    };

    /**
     * 清除用户信息
     */
    const clearUserInfo = (): void => {
        userInfo.value = null;
        profile.value = null;
        storage.remove(USER_INFO_KEY);
    };

    /**
     * 获取用户详细资料
     */
    const getUserProfile = async (): Promise<UserProfile | null> => {
        try {
            const response = await useClientRequest.get('/user/profile') as ApiResponse<UserProfile>;
            
            if (response.code === 200) {
                profile.value = response.data;
                return response.data;
            }
            return null;
        } catch (error) {
            console.error('Get user profile error:', error);
            return null;
        }
    };

    /**
     * 更新用户资料
     */
    const updateUserProfile = async (updates: Partial<UserProfile>): Promise<boolean> => {
        try {
            const response = await useClientRequest.put('/user/profile', updates) as ApiResponse;
            
            if (response.code === 200) {
                if (profile.value) {
                    profile.value = { ...profile.value, ...updates };
                }
                // 如果更新的字段包含在userInfo中，同步更新
                const userInfoFields = ['nickname', 'email', 'phone', 'avatar'];
                const userInfoUpdates: Partial<UserInfo> = {};
                
                userInfoFields.forEach(field => {
                    if (field in updates) {
                        (userInfoUpdates as any)[field] = (updates as any)[field];
                    }
                });
                
                if (Object.keys(userInfoUpdates).length > 0) {
                    updateUserInfo(userInfoUpdates);
                }
                
                return true;
            }
            return false;
        } catch (error) {
            console.error('Update user profile error:', error);
            return false;
        }
    };

    /**
     * 修改密码
     */
    const changePassword = async (oldPassword: string, newPassword: string): Promise<boolean> => {
        try {
            const response = await useClientRequest.put('/user/password', {
                oldPassword,
                newPassword
            }) as ApiResponse;
            
            return response.code === 200;
        } catch (error) {
            console.error('Change password error:', error);
            return false;
        }
    };

    /**
     * 上传头像
     */
    const uploadAvatar = async (filePath: string): Promise<string | null> => {
        try {
            const result = await upload({
                url: '/user/avatar',
                filePath,
                name: 'avatar'
            });
            
            if (result.code === 200 && result.data?.url) {
                // 更新用户信息中的头像
                updateUserInfo({ avatar: result.data.url });
                return result.data.url;
            }
            return null;
        } catch (error) {
            console.error('Upload avatar error:', error);
            return null;
        }
    };

    /**
     * 检查权限
     */
    const hasPermission = (permission: string): boolean => {
        if (!userInfo.value || !userInfo.value.permissions) {
            return false;
        }
        return userInfo.value.permissions.includes(permission);
    };

    /**
     * 检查角色
     */
    const hasRole = (role: string): boolean => {
        if (!userInfo.value || !userInfo.value.roles) {
            return false;
        }
        return userInfo.value.roles.includes(role);
    };

    /**
     * 检查是否有任一权限
     */
    const hasAnyPermission = (permissions: string[]): boolean => {
        if (!userInfo.value || !userInfo.value.permissions) {
            return false;
        }
        return permissions.some(permission => userInfo.value!.permissions.includes(permission));
    };

    /**
     * 检查是否有任一角色
     */
    const hasAnyRole = (roles: string[]): boolean => {
        if (!userInfo.value || !userInfo.value.roles) {
            return false;
        }
        return roles.some(role => userInfo.value!.roles.includes(role));
    };

    return {
        // 状态
        userInfo,
        profile,
        
        // 方法
        setUserInfo,
        updateUserInfo,
        clearUserInfo,
        getUserProfile,
        updateUserProfile,
        changePassword,
        uploadAvatar,
        
        // 权限检查
        hasPermission,
        hasRole,
        hasAnyPermission,
        hasAnyRole
    };
});
