import {Application, BackendSession, ChannelService} from 'pinus';
import { MailModel, MailType } from '../../../db/Mail';
import { GroupMailModel, GroupMailType } from '../../../db/GroupMail';
import { resResult } from '../../../pubUtils/util';
import { STATUS } from '../../../consts/statusCode';
import { MAIL_STATUS, GM_MAIL_TYPE } from '../../../consts/constModules/mailConst';
import { addItems } from '../../../services/role/rewardService';
import { checkMailGoods, getMails } from '../../../services/mailService';
import { ServerMailModel, ServerMailType } from '../../../db/ServerMail';
import { MailParam } from '../../../domain/roleField/mail';
import { ItemInter, RewardInter } from '../../../pubUtils/interface';
import { RoleModel } from '../../../db/Role';
import { gameData } from '../../../pubUtils/data';
import { ITEM_CHANGE_REASON, ITID, RECEIVE_MAIL_TYPE } from '../../../consts';
import { BAG } from '../../../pubUtils/dicParam';
import { saveMailLog } from '../../../pubUtils/logUtil';

export default function(app: Application) {
    return new MailHandler(app);
}

export class MailHandler {
    constructor(private app: Application) {
    
    }

    public async getMails(msg:{}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const serverId: number = session.get('serverId');

        const list = await getMails(roleId, serverId);
        return resResult(STATUS.SUCCESS, { list });
    }

    public async refrshMails(msg:{}) {
        
    }

    public async readMail(msg: { id: string, mailType: number }, session: BackendSession) {
        let roleId: string = session.get('roleId');
        let { id, mailType } = msg;
        let mails = [];
        if (mailType == GM_MAIL_TYPE.SINGLE) {
            let mail = await MailModel.getMailById(id);
            if(mail && mail.status == MAIL_STATUS.CREATE) {
                mail = await MailModel.updateStatusWithCondition(id, MAIL_STATUS.READ);
                mails.push({ id, status: MAIL_STATUS.READ, mailType });
            }
                    
        } else if (mailType == GM_MAIL_TYPE.GROUP) {
            let mail = await GroupMailModel.getMailById(id);
            if(mail) {
                let myStatus = mail.roleStatus.find(cur => cur.roleId == roleId);
                if(myStatus && myStatus.status == MAIL_STATUS.CREATE) {
                    mail = await GroupMailModel.updateStatusWithCondition(id, roleId, MAIL_STATUS.READ);
                    mails.push({ id, status: MAIL_STATUS.READ, mailType });
                }
            }
        } else if (mailType == GM_MAIL_TYPE.SERVER) {
            let mail = await ServerMailModel.getMailById(id);
            if(mail) {
                let myStatus = mail.roleStatus.find(cur => cur.roleId == roleId);
                if(!myStatus || myStatus.status == MAIL_STATUS.CREATE) {
                    mail = await ServerMailModel.updateStatusWithCondition(id, roleId, MAIL_STATUS.READ);
                    mails.push({ id, status: MAIL_STATUS.READ, mailType });
                }
            }
        }
        // if (!mail)
        //     return resResult(STATUS.WRONG_PARMS);
        return resResult(STATUS.SUCCESS, { mails });
    }

    public async delMails(msg: { id: string, mailType: number, type: number }, session: BackendSession) {
        let roleId: string = session.get('roleId');
        let { id, type, mailType } = msg;
        if (type == 1) {//单个删除
            let mail: MailType|GroupMailType|ServerMailType;
            if (mailType == GM_MAIL_TYPE.SINGLE) {
                mail = await MailModel.delMailById(id);
            } else if (mailType == GM_MAIL_TYPE.GROUP) {
                mail = await GroupMailModel.delMailById(id, roleId);      
            } else if (mailType == GM_MAIL_TYPE.SERVER) {
                mail = await ServerMailModel.delMailById(id, roleId); 
            }
            if (!mail) return resResult(STATUS.WRONG_PARMS);

            return resResult(STATUS.SUCCESS, { mails: [{ id: mail._id, mailType, status: MAIL_STATUS.DELETE}] });
        } else {//一键删除
            let singlemails = await MailModel.delMailsByRoleId(roleId);
            let groupMails = await GroupMailModel.delMailsByRoleId(roleId);
            let servermails = await ServerMailModel.delMailsByRoleId(roleId);
            let mails: { id: string, mailType: GM_MAIL_TYPE, status: MAIL_STATUS }[] = [];
            for(let mail of singlemails) {
                mails.push({ id: mail._id, mailType: GM_MAIL_TYPE.SINGLE, status: MAIL_STATUS.DELETE });
            }
            for(let mail of groupMails) {
                mails.push({ id: mail._id, mailType: GM_MAIL_TYPE.GROUP, status: MAIL_STATUS.DELETE });
            }
            for(let mail of servermails) {
                mails.push({ id: mail._id, mailType: GM_MAIL_TYPE.SERVER, status: MAIL_STATUS.DELETE });
            }
            return resResult(STATUS.SUCCESS, { mails });
        }
    }

    public async getMailRewards(msg: { id: string, mailType: number, type: RECEIVE_MAIL_TYPE }, session: BackendSession) {
        let roleId: string = session.get('roleId');
        let roleName: string = session.get('roleName');
        let sid: string = session.get('sid');
        let serverId: number = session.get('serverId');
        let { id, type, mailType } = msg;
        let { jewelCount } = await RoleModel.findByRoleId(roleId, 'jewelCount');
        
        let originMails: {mailType: GM_MAIL_TYPE, mail: MailType|GroupMailType|ServerMailType}[] = []

        if (type == RECEIVE_MAIL_TYPE.SINGLE) {//单个领取
            let mail: MailType|GroupMailType|ServerMailType;
            if (mailType == GM_MAIL_TYPE.SINGLE) {
                mail = await MailModel.getMailById(id);
                if (!mail) return resResult(STATUS.WRONG_PARMS);
                if(mail.status != MAIL_STATUS.READ &&  mail.status != MAIL_STATUS.CREATE) return resResult(STATUS.WRONG_PARMS);
            } else if (mailType == GM_MAIL_TYPE.GROUP) {
                mail = await GroupMailModel.getMailById(id);
                if (!mail) return resResult(STATUS.WRONG_PARMS);
                let myStatus = mail.roleStatus.find(cur => cur.roleId == roleId);
                if(!myStatus) return resResult(STATUS.WRONG_PARMS);
                if(myStatus.status != MAIL_STATUS.READ &&  myStatus.status != MAIL_STATUS.CREATE) return resResult(STATUS.WRONG_PARMS);
            } else if (mailType == GM_MAIL_TYPE.SERVER) {
                mail = await ServerMailModel.getMailById(id);
                if (!mail) return resResult(STATUS.WRONG_PARMS);
                let myStatus = mail.roleStatus.find(cur => cur.roleId == roleId);
                if(myStatus && myStatus.status != MAIL_STATUS.READ &&  myStatus.status != MAIL_STATUS.CREATE) return resResult(STATUS.WRONG_PARMS);
            }
            originMails.push({ mailType, mail });
        } else {//一键领取
            let singlemails = await MailModel.findRewardsMails(roleId);
            for(let mail of singlemails) {
                if(mail.status != MAIL_STATUS.READ &&  mail.status != MAIL_STATUS.CREATE) continue;
                originMails.push({ mailType: GM_MAIL_TYPE.SINGLE, mail });
            }
            let groupMails = await GroupMailModel.findRewardsMails(roleId);
            for(let mail of groupMails) {
                let myStatus = mail.roleStatus.find(cur => cur.roleId == roleId);
                if(!myStatus) continue;
                if(myStatus.status != MAIL_STATUS.READ &&  myStatus.status != MAIL_STATUS.CREATE) continue;
                originMails.push({ mailType: GM_MAIL_TYPE.GROUP, mail })
            }
            let servermails = await ServerMailModel.findRewardsMails(serverId, roleId);
            for(let mail of servermails) {
                let myStatus = mail.roleStatus.find(cur => cur.roleId == roleId);
                if(myStatus && myStatus.status != MAIL_STATUS.READ &&  myStatus.status != MAIL_STATUS.CREATE) continue;
                originMails.push({ mailType: GM_MAIL_TYPE.SERVER, mail })
            }
        }

        let mailGoods: ItemInter[] = [], mails: MailParam[] = [];
        for(let { mail, mailType } of originMails) {
            let { isEquipOver, jewelCount: newEquipCount } = checkMailGoods(mail, jewelCount);
            if(isEquipOver) {
                if(type == RECEIVE_MAIL_TYPE.SINGLE) {
                    return resResult(STATUS.EQUIP_IS_OVER);
                } else {
                    continue;  // 如果有装备数量超过，那么一键领取这条邮件就不领了
                }
            }
            jewelCount = newEquipCount;

            if(mailType == GM_MAIL_TYPE.SINGLE) {
                mail = await MailModel.updateStatusWithCondition(mail._id, MAIL_STATUS.RECEIVED);
            } else if (mailType == GM_MAIL_TYPE.GROUP) {
                mail = await GroupMailModel.updateStatusWithCondition(mail._id, roleId, MAIL_STATUS.RECEIVED);
            } else if (mailType == GM_MAIL_TYPE.SERVER) {
                mail = await ServerMailModel.updateStatusWithCondition(mail._id, roleId, MAIL_STATUS.RECEIVED, <ServerMailType>mail);
            }
            if(!mail) return resResult(STATUS.MAIL_HAS_RECEIVE);

            let mailObj = new MailParam(mailType, mail, roleId);
            mailGoods.push(...mailObj.goods);
            mails.push(mailObj);
        }

        let resGoods = await addItems(roleId, roleName, sid, mailGoods, ITEM_CHANGE_REASON.MAIL);
        saveMailLog(session, mails);
        return resResult(STATUS.SUCCESS, { mails, goods: resGoods });
    }
}