import { CloudObject, CloudUser } from './ncloud';

// CloudEvaluate.ts
export class CloudEvaluate extends CloudObject {
    userData: Record<string, any>;
    currentUser: CloudUser; // 添加当前用户的引用
    modalCtrl: any; // 假设 modalCtrl 是通过构造函数传入的

    constructor(userData: Record<string, any>, currentUser: CloudUser,modalCtrl: any) {
        super("_ChatEvaluate"); 
        this.userData = userData; // 保存用户评价数据
        this.currentUser = currentUser; // 保存当前用户
        this.modalCtrl = modalCtrl; // 保存模态控制器
    }

    /** 保存评价 */
    override async save() {
        // 确保 rating 是数字类型
        if (this.userData['rating']) {
            this.userData['rating'] = Number(this.userData['rating']);
        }
        console.log('保存评价被调用'); // 调试日志

        // 调用后端 API 保存评价
        const response = await fetch(`http://dev.fmode.cn:1337/parse/classes/ChatEvaluate`, {
            headers: {
                "x-parse-application-id": "dev",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                content: this.userData['content'],
                rating: this.userData['rating'],
                avatar: this.currentUser.data?.['avatar'], // 假设用户头像存储在 data.avatar 中
                user: { __type: "Pointer", className: "_User", objectId: this.currentUser.id } // 添加用户指针
            }),
            method: "POST"
        });

        const result = await response.json();
        console.log('保存结果:', result); // 输出保存结果

        if (result?.error) {
            console.error(result?.error);
            console.error('评价保存失败');
            return null;
        }

        console.log('评价保存成功:', result);
        this.modalCtrl.dismiss(result, "confirm"); // 关闭模态框并传递结果
        return result; // 返回保存的结果
    }
}