import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { genCode } from '../pubUtils/util';

@index({ id: 1, surveyId: 1 })
export default class SurveyRec extends BaseModel {

    @prop({ required: true, default: 1 })
    code: string;              // 编码

    @prop({ required: true, default: 1 })
    roleId: string;              // 玩家id

    @prop({ required: true })
    surveyId: string;           // 问卷id

    @prop({ required: true })
    index: string;         // 有没有发邮件

    @prop({ required: true })
    hasSentMail: boolean;         // 有没有发邮件

    @prop({ required: true })
    json: string;                 // 整个回调

    public static async findByRoleIdAndId(roleId: string, surveyId: string) {
        let rec: SurveyRecType = await SurveyRecModel.findOne({ roleId, surveyId }).lean();
        return rec;
    }

    public static async findByRole(roleId: string) {
        let rec: SurveyRecType[] = await SurveyRecModel.find({ roleId }).lean();
        return rec;
    }

    public static async findByCode(code: string) {
        let rec: SurveyRecType = await SurveyRecModel.findOne({ code }).lean();
        return rec;
    }

    public static async createSurveyRec(roleId: string, surveyId: string, index: string, json: string) {
        let code = genCode(8);
        let rec: SurveyRecType = await SurveyRecModel.findOneAndUpdate({ roleId, surveyId }, { $set: { hasSentMail: false, json, index, code } }, { upsert: true, new: true }).lean();
        return rec;
    }

    public static async send(code: string) {
        let rec: SurveyRecType = await SurveyRecModel.findOneAndUpdate({ code }, { $set: { hasSentMail: true } }).lean();
        return rec;
    }
}

export const SurveyRecModel = getModelForClass(SurveyRec);

export interface SurveyRecType extends Pick<DocumentType<SurveyRec>, keyof SurveyRec> {};
export type SurveyRecUpdate = Partial<SurveyRecType>; // 将所有字段变成可选项
