export interface Mail {
    id: string;
    sys: number;
    expire: string;
    read: string;//读取状态
    awards: any;//奖励附件
}

class Data {
    private _mails: { [id: string]: Mail } = {};
    private _mailMaxIdTab: { [sys: number]: number } = { 0: 0, 1: 0 };

    init(): void {
        this.reset();
    }

    reset(): void {
        this._mails = {};
        this._mailMaxIdTab = { 0: 0, 1: 0 };
    }

    purge(): void {
        this.reset();
    }

    setData(data: Mail[]): void {
        if (data) {
            for (const v of data) {
                this._mails[v.id] = v;
            }
            for (const v of data) {
                if (parseInt(v.id, 10) > this._mailMaxIdTab[v.sys]) {
                    this._mailMaxIdTab[v.sys] = parseInt(v.id, 10);
                }
            }
        }
    }

    getData(): { [id: string]: Mail } {
        return this._mails;
    }

    //设置最后获得邮件索引
    setMailMax(data: number[]): void {
        for (const v of data) {
            if (v > this._mailMaxIdTab[1]) {
                this._mailMaxIdTab[1] = v;
            }
        }
    }

    //设置最新获得邮件索引
    setNewMail(data: Mail[]): void {
        for (const v of data) {
            this._mails[v.id] = v;
        }
        for (const v of data) {
            if (parseInt(v.id, 10) > this._mailMaxIdTab[v.sys]) {
                this._mailMaxIdTab[v.sys] = parseInt(v.id, 10);
            }
        }
    }

    //获取最新获得邮件索引
    getMaxMailId(type: number): number {
        return this._mailMaxIdTab[type];
    }

    //根据id设置邮件已读状态
    setMailReadById(id: string): void {
        for (const key in this._mails) {
            const v = this._mails[key];
            if (parseInt(v.id, 10) === parseInt(id, 10)) {
                v.read = '1';
                break;
            }
        }
    }

    //批量设置邮件已读状态
    setMailRead(ids: string[]): void {
        for (const k1 of ids) {
            for (const key in this._mails) {
                const v = this._mails[key];
                if (parseInt(v.id, 10) === parseInt(k1, 10)) {
                    v.read = '1';
                }
            }
        }
    }

    //批量移除邮件
    removeMail(mailList): void {
        for (const k1 in mailList) {
            for (const key in this._mails) {
                const v = this._mails[key];
                if (parseInt(v.id, 10) === parseInt(k1, 10)) {
                    delete this._mails[key];
                }
            }
        }
    }

    //根据id移除邮件
    removeMailById(id: string): void {
        for (const key in this._mails) {
            const v = this._mails[key];
            if (parseInt(v.id, 10) === parseInt(id, 10)) {
                delete this._mails[key];
            }
        }
    }
}

export let MailData = new Data;
