// CloudObject.ts
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"].indexOf(key) > -1) {
                return;
            }
            this.data[key] = json[key];
        });
    }

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

    async save() {
        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: {
                "content-type": "application/json;charset=UTF-8",
                "x-parse-application-id": "dev"
            },
            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;
    }

    async destroy() {
        if (!this.id) return;
        const response = await fetch(`http://dev.fmode.cn:1337/parse/classes/${this.className}/${this.id}`, {
            headers: {
                "x-parse-application-id": "dev"
            },
            body: null,
            method: "DELETE",
            mode: "cors",
            credentials: "omit"
        });

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

// CloudQuery.ts
export class CloudQuery {
    className: string;
    queryParams: Record<string, any> = {};

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

    // 作用是将查询参数转换为对象
    include(...fileds:string[]) {
        this.queryParams["include"] = fileds;
    }
    greaterThan(key: string, value: any) {
        if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
        this.queryParams["where"][key]["$gt"] = value;
    }

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

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

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

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

    async get(id: string) {
        const url = `http://dev.fmode.cn:1337/parse/classes/${this.className}/${id}?`;

        const response = await fetch(url, {
            headers: {
                "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
                "x-parse-application-id": "dev"
            },
            body: null,
            method: "GET",
            mode: "cors",
            credentials: "omit"
        });

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

    }

    async find() {
        let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;

        let queryStr = ``
        Object.keys(this.queryParams).forEach(key=>{
            let paramStr = JSON.stringify(this.queryParams[key]); // 作用是将对象转换为JSON字符串
            if(key=="include"){
                paramStr = this.queryParams[key]?.join(",")
            }
            if(key=="where"){
                paramStr = JSON.stringify(this.queryParams[key]);

            }
            if(queryStr) {
                url += `${key}=${paramStr}`;
            }else{
                url += `&${key}=${paramStr}`;
            }
        })

        const response = await fetch(url, {
            headers: {
                "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
                "x-parse-application-id": "dev"
            },
            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 || [];
    }


    async first() {
        let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;

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

        const response = await fetch(url, {
            headers: {
                "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
                "x-parse-application-id": "dev"
            },
            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
        //let list = json?.results || []
        //let objList = list.map((item:any)=>this.dataToObj(item))
        //return objList || [];
    }

    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;
    }
}