export class CloudObject {
    id: string | null = null;
    className: string;
    createdAt: any;
    updatedAt: any;
    data: Record<string, any> = {};

    constructor(className: string) {
        this.className = className;
    }

    toPointer() {
        return { "__type": "Pointer", "className": this.className, "objectId": this.id };
    }

    set(json: Record<string, any>) {
        Object.keys(json).forEach(key => {
            if (["objectId", "id", "createdAt", "updatedAt", "ACL"].includes(key)) {
                return;
            }
            this.data[key] = json[key];
        });
    }

    get(key: string) {
        return this.data[key] || null;
    }

    // 修改 save 方法：根据新的接口 URL
    async save(): Promise<this> {
        let method = "POST";
        let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}`;
        
        // 更新
        if (this.id) {
            url += `/${this.id}`;
            method = "PUT";
        }
        
        const body = JSON.stringify(this.data);
        const response = await fetch(url, {
            headers: {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "content-type": "text/plain;charset=UTF-8",
                "x-parse-application-id": "dev",
                "Referer": "http://127.0.0.1:4040/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: body,
            method: method,
            mode: "cors",
            credentials: "omit"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result.error);
        }
        if (result?.objectId) {
            this.id = result.objectId;
        }
        return this;
    }

    // 修改 destroy 方法：根据新的接口 URL
    async destroy(): Promise<boolean> {
        if (!this.id) return false;
        
        const response = await fetch(`http://dev.fmode.cn:1337/parse/classes/${this.className}/${this.id}`, {
            headers: {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "x-parse-application-id": "dev",
                "Referer": "http://127.0.0.1:4040/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: null,
            method: "DELETE",
            mode: "cors",
            credentials: "omit"
        });

        const result = await response?.json();
        if (result) {
            this.id = null;
        }
        return true;
    }
}


export class CloudQuery {
    className: string;
    whereOptions: Record<string, any> = {};

    constructor(className: string) {
        this.className = className;
    }

    greaterThan(key: string, value: any) {
        if (!this.whereOptions[key]) this.whereOptions[key] = {};
        this.whereOptions[key]["$gt"] = value;
    }

    greaterThanAndEqualTo(key: string, value: any) {
        if (!this.whereOptions[key]) this.whereOptions[key] = {};
        this.whereOptions[key]["$gte"] = value;
    }

    lessThan(key: string, value: any) {
        if (!this.whereOptions[key]) this.whereOptions[key] = {};
        this.whereOptions[key]["$lt"] = value;
    }

    lessThanAndEqualTo(key: string, value: any) {
        if (!this.whereOptions[key]) this.whereOptions[key] = {};
        this.whereOptions[key]["$lte"] = value;
    }

    equalTo(key: string, value: any) {
        this.whereOptions[key] = value;
    }

    // 修改 get 方法：根据新的接口 URL
    async get(id: string): Promise<Record<string, any>> {
        const url = `http://dev.fmode.cn:1337/parse/classes/${this.className}/${id}?`;
        const response = await fetch(url, {
            headers: {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "x-parse-application-id": "dev",
                "Referer": "http://127.0.0.1:4040/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: null,
            method: "GET",
            mode: "cors",
            credentials: "omit"
        });
        const json = await response?.json();
        return json || {};
    }

    // 修改 find 方法：根据新的接口 URL
    async find(): Promise<CloudObject[]> {
        let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;

        if (Object.keys(this.whereOptions).length) {
            const whereStr = JSON.stringify(this.whereOptions);
            url += `where=${whereStr}`;
        }

        const response = await fetch(url, {
            headers: {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "x-parse-application-id": "dev",
                "Referer": "http://127.0.0.1:4040/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: null,
            method: "GET",
            mode: "cors",
            credentials: "omit"
        });

        const json = await response?.json();
        let list = json?.results || [];
        let objList = list.map((item: any) => this.dataToObj(item));
        return objList || [];
    }

    // 修改 first 方法：根据新的接口 URL
    async first(): Promise<CloudObject | null> {
        let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;

        if (Object.keys(this.whereOptions).length) {
            const whereStr = JSON.stringify(this.whereOptions);
            url += `where=${whereStr}`;
        }

        const response = await fetch(url, {
            headers: {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "x-parse-application-id": "dev",
                "Referer": "http://127.0.0.1:4040/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: null,
            method: "GET",
            mode: "cors",
            credentials: "omit"
        });

        const json = await response?.json();
        const exists = json?.results?.[0] || null;
        if (exists) {
            let existsObject = this.dataToObj(exists);
            return existsObject;
        }
        return null;
    }

    dataToObj(exists: any): CloudObject {
        let existsObject = new CloudObject(this.className);
        existsObject.set(exists);
        existsObject.id = exists.objectId;
        existsObject.createdAt = exists.createdAt;
        existsObject.updatedAt = exists.updatedAt;
        return existsObject;
    }
}


export class CloudUser extends CloudObject {
    constructor() {
        super("_User"); // 假设用户类在Parse中是"_User"
        // 读取用户缓存信息
        let userCacheStr = localStorage.getItem("NCloud/dev/User")
        if(userCacheStr){
            let userData = JSON.parse(userCacheStr)
            // 设置用户信息
            this.id = userData?.objectId;
            this.sessionToken = userData?.sessionToken;
            this.data = userData; // 保存用户数据
        }
    }

    sessionToken:string|null = ""
    /** 获取当前用户信息 */
    async current() {
        if (!this.sessionToken) {
            console.error("用户未登录");
            return null;
        }
        
        const response = await fetch(`http://dev.fmode.cn:1337/parse/users/me`, {
            headers: {
                "x-parse-application-id": "dev",
                "x-parse-session-token": this.sessionToken // 使用sessionToken进行身份验证
            },
            method: "GET"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }
        return result;
    }

    

    // 登录
    async login(username: string, password: string): Promise<CloudUser | null> {
        const response = await fetch(`http://dev.fmode.cn:1337/parse/login`, {
            headers: {
                "x-parse-application-id": "dev",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ username, password }),
            method: "POST"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }
        // 设置用户信息
        this.id = result?.objectId;
        this.sessionToken = result?.sessionToken;
        this.data = result; // 保存用户数据
        // 缓存用户信息
        console.log(result)
        localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
        return this;

    }
    
        // 登出
        async logOut(){

            if (!this.sessionToken) {
                console.error("用户未登录");
                return;
            }
    
            const response = await fetch(`http://dev.fmode.cn:1337/parse/logout`, {
                headers: {
                    "x-parse-application-id": "dev",
                    "x-parse-session-token": this.sessionToken
                },
                method: "POST"
            });
            const result = await response?.json();
            if (result?.error) {
                console.error(result?.error);
                return false;

            }
            // 清除用户信息
        localStorage.removeItem("NCloud/dev/User")
        this.id = null;
        this.sessionToken = null;
        this.data = {};
        return true;
    }

    // 注册
    async signUp(username: string, password: string, email: string): Promise<CloudUser | null> {
        const userData = {
            username,
            password,
          
        };
        const response = await fetch(`http://dev.fmode.cn:1337/parse/users`, {
            headers: {
                "x-parse-application-id": "dev",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ username, password, email }),
            method: "POST"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }

        // 设置用户信息
        this.id = result?.objectId;
        this.sessionToken = result?.sessionToken;
        this.data = result; // 保存用户数据
        
        
        // 注册成功后自动登录
         return await this.login(username, password);



    }
}






           
//fearlessUser类封装
// src/lib/fearlessUser.ts




export class FearlessUser extends CloudObject {
    static getCurrentUser(): FearlessUser | undefined {
      throw new Error('Method not implemented.');
    }
    sessionToken: any;
    constructor() {
        super("FearlessUser"); // 假设 FearlessUser 类在 Parse 中是 "FearlessUser"
    }

    /** 获取单个用户信息 */
    async getUser(id: string) {
        const url = `http://dev.fmode.cn:1337/parse/classes/FearlessUser/${id}?`;

        const response = await fetch(url, {
            headers: {
                "x-parse-application-id": "dev"
            },
            method: "GET",
            mode: "cors",
            credentials: "omit"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }

        return this.dataToObj(result);
    }

    /** 获取当前登录用户的 `FearlessUser` 信息 */
    async getCurrentUserInfo() {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return null;
        }

        const currentUserId = currentUser.objectId;

        // 通过 _User 的 objectId 查询 FearlessUser 表中的记录
        const query = new CloudQuery("FearlessUser");
        query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": currentUserId });

        const fearlessUser = await query.first();
        return fearlessUser;
    }

    /** 创建或保存用户信息 */
    async saveUserInfo(userData: Record<string, any>) {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return null;
        }

        const userPointer = { "__type": "Pointer", "className": "_User", "objectId": currentUser.objectId };

        const newUserInfo = {
            ...userData,
            user: userPointer // 将当前用户作为外键关联到 FearlessUser 表
        };

        const url = `http://dev.fmode.cn:1337/parse/classes/FearlessUser`;

        const response = await fetch(url, {
            headers: {
                "Content-Type": "application/json",
                "x-parse-application-id": "dev"
            },
            method: "POST",
            body: JSON.stringify(newUserInfo),
            mode: "cors",
            credentials: "omit"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }

        return this.dataToObj(result);
    }

    /** 更新当前用户的信息 */
    async updateUserInfo(updatedData: Record<string, any>) {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return null;
        }

        const currentUserId = currentUser.objectId;

        // 查找当前用户的 FearlessUser 信息
        const query = new CloudQuery("FearlessUser");
        query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": currentUserId });

        const fearlessUser = await query.first();
        if (!fearlessUser) {
            console.error("未找到用户信息");
            return null;
        }

        // 更新信息
        fearlessUser.set(updatedData);
        await fearlessUser.save();

        return fearlessUser;
    }

    /** 删除当前用户的 FearlessUser 信息 */
    async deleteUserInfo() {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return false;
        }

        const currentUserId = currentUser.objectId;

        // 查找当前用户的 FearlessUser 信息
        const query = new CloudQuery("FearlessUser");
        query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": currentUserId });

        const fearlessUser = await query.first();
        if (!fearlessUser) {
            console.error("未找到用户信息");
            return false;
        }

        // 删除 FearlessUser 记录
        await fearlessUser.destroy();

        return true;
    }

    /** 将查询结果转换为 CloudObject */
    private dataToObj(result: any): CloudObject {
        let userObject = new CloudObject(this.className);
        userObject.set(result);
        userObject.id = result.objectId;
        userObject.createdAt = result.createdAt;
        userObject.updatedAt = result.updatedAt;
        return userObject;
    }


    async logOut() {
        if (!this.sessionToken) {
            console.error("用户未登录");
            return false;
        }

        const response = await fetch(`http://dev.fmode.cn:1337/parse/logout`, {
            headers: {
                "x-parse-application-id": "dev",
                "x-parse-session-token": this.sessionToken
            },
            method: "POST"
        });
        
        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return false;
        }


        return true;
    }
    
    async login(username: string, password: string): Promise<FearlessUser | null> {
        const response = await fetch(`http://dev.fmode.cn:1337/parse/login`, {
            headers: {
                "x-parse-application-id": "dev",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ username, password }),
            method: "POST"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }
        // 设置用户信息
        this.id = result?.objectId;
        this.sessionToken = result?.sessionToken;
        this.data = result; // 保存用户数据
        // 缓存用户信息
        console.log(result)
        localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
        return this;

    }

    

}