import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/core';
import { ApiQuery, ApiTags } from '@midwayjs/swagger';
import { BaseController } from '../../frame/BaseController';
import { Validate } from '@midwayjs/validate';
import { get, omit, pick } from 'lodash';
import { ServiceError, ErrorCode } from '../../error/service.error';
import { MessageService } from '../../service/system/message.service';
import { Context } from '@midwayjs/koa';
import { MessageUserType } from '../../public/var';

const namePrefix = '消息';
@ApiTags(['消息'])
@Controller('/message', { tagName: namePrefix })
export class RegionController implements BaseController {
  controllerCode = 'system_message';
  @Inject()
  service: MessageService;

  @Inject()
  ctx: Context;

  @Get('/')
  @ApiTags('列表查询')
  @ApiQuery({ name: 'query' })
  async index(@Query() query: object) {
    const qobj = omit(query, ['skip', 'limit']);
    const others = pick(query, ['skip', 'limit']);
    let { data, total } = await this.service.query(qobj, others);
    // 如果query中有'to.user',那就把to中其他的人的数据都删掉
    if (qobj['to.user']) {
      data = await this.service.deleteOtherUserInfo(data, qobj['to.user']);
    }
    return { data, total };
  }

  @Get('/:id')
  @ApiTags('单查询')
  async fetch(@Param('id') id: number) {
    const data = await this.service.fetch({ id });
    return data;
  }

  @Post('/', { routerName: `创建${namePrefix}` })
  @ApiTags('创建数据')
  @Validate()
  async create(@Body() data: object) {
    let oto = get(data, 'to', []);
    oto = oto.map(i => {
      const user_type = get(i, 'user_type');
      if (!user_type) return i;
      else if (user_type === 'admin') i.user_type = MessageUserType.ADMIN;
      else if (user_type === 'user') i.user_type = MessageUserType.USER;
      return i;
    });
    data['to'] = oto;
    const dbData = await this.service.create(data);
    // 需要让mq发送消息,触发前端接收消息
    const to = get(dbData, 'to', []);
    for (const i of to) {
      await this.service.toSendMq(get(i, 'user'), MessageUserType.USER, get(dbData, 'id'));
    }
    return dbData;
  }

  @Post('/remind/:id', { routerName: `重提示${namePrefix}` })
  @ApiTags('重提示')
  async remind(@Param('id') id: number) {
    const message = await this.service.fetch({ id });
    if (!message) return;
    const to = get(message, 'to', []);
    for (const i of to) {
      await this.service.toSendMq(get(i, 'user'), MessageUserType.USER, id);
    }
    return;
  }

  @Post('/:id', { routerName: `修改${namePrefix}` })
  @ApiTags('修改数据')
  @Validate()
  async update(@Param('id') id: number, @Body() data: object) {
    if (!id) throw new ServiceError(ErrorCode.ID_NOT_FOUND);
    const result = await this.service.update({ id }, data);
    return result;
  }

  @Del('/:id', { routerName: `删除${namePrefix}` })
  @ApiTags('删除数据')
  @Validate()
  async delete(@Param('id') id: number) {
    if (!id) throw new ServiceError(ErrorCode.ID_NOT_FOUND);
    const result = await this.service.delete({ id });
    return result;
  }

  @Get('/checkNotRead')
  @ApiTags('未读查询')
  @ApiQuery({ name: 'query' })
  async checkNotRead() {
    const qobj = { 'to.is_read': '0', 'to.user_type': MessageUserType.USER };
    const user = get(this.ctx, 'user');
    if (!user) return 0;
    qobj['to.user'] = get(user, 'id');
    const result = await this.service.query(qobj);
    return get(result, 'total');
  }

  @Get('/adminCheckNotRead')
  @ApiTags('管理员未读查询')
  @ApiQuery({ name: 'query' })
  async adminCheckNotRead() {
    const qobj = { 'to.is_read': '0', 'to.user_type': MessageUserType.ADMIN };
    const user = get(this.ctx, 'user');
    if (!user) return 0;
    qobj['to.user'] = get(user, 'id');
    const result = await this.service.query(qobj);
    return get(result, 'total');
  }

  @Get('/read/:id')
  @ApiTags('全部已读')
  async read(@Param('id') id: number) {
    const data = await this.service.read({ id, user_type: MessageUserType.USER });
    return data;
  }
  @Get('/adminRead/:id')
  @ApiTags('管理员全部已读')
  async adminRead(@Param('id') id: number) {
    const data = await this.service.read({ id, user_type: MessageUserType.ADMIN });
    return data;
  }
}
