
import { Service } from 'egg';
import { GMMailModel, } from '@db/GMMail';
import { STATUS } from '@consts';
import { SearchMailParam } from '@domain/backEndField/search';
import { UpdateMailParams } from '@domain/backEndField/params';
import { RoleModel, RoleType } from '@db/Role';

export default class Mail extends Service {

    public async getGMMailList(page: number, pageSize: number, sortField: string, sortOrder: string, form: SearchMailParam) {
        const { ctx } = this;
        const list = await GMMailModel.findByCondition(page, pageSize, sortField, sortOrder, form);
        const total = await GMMailModel.countByCondition( form )
        return ctx.service.utils.resResult(STATUS.SUCCESS, {
            list, total
        });
    }

    public async findRoleByIdOrName(serverId: number, roleId: string, roleName: string) {
        let role: RoleType;
        if(roleId) {
            role = await RoleModel.findByRoleId(roleId);
        }
        if(roleName) {
            role = await RoleModel.findByRoleName(roleName);
        }
        if(!role || role.serverId != serverId) return this.ctx.service.utils.resResult(STATUS.WRONG_PARMS);
        return this.ctx.service.utils.resResult(STATUS.SUCCESS, { env: this.ctx.app.config.realEnv, serverId, roleId: role.roleId, roleName: role.roleName })

    }

    public async createGmMail(params: UpdateMailParams) {
        const { ctx } = this;
        await GMMailModel.addMail(params, ctx.user?.uid);

        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async updateGMMail(_id: string, params: UpdateMailParams) {
        const { ctx } = this;
        await GMMailModel.updateMailById(_id, params, ctx.user?.uid);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }
}