import { Body, Controller, Get, Inject, Param, Post, Query } from '@midwayjs/core';
import { ApiQuery, ApiTags } from '@midwayjs/swagger';
import { ContactApplyService } from '../../service/users/contactApply.service';
import { get, omit, pick } from 'lodash';
import { Validate } from '@midwayjs/validate';
import { ServiceError, ErrorCode } from '../../error/service.error';
import { MessageService } from '../../service/system/message.service';

const namePrefix = '联系方式';
@ApiTags(['联系方式'])
@Controller('/contactApply', { tagName: namePrefix })
export class ContactApplyController {
  @Inject()
  service: ContactApplyService;
  @Inject()
  msgService: MessageService;

  @Get('/')
  @ApiTags('列表查询')
  @ApiQuery({ name: 'query' })
  async index(@Query() query: object) {
    const qobj = omit(query, ['skip', 'limit']);
    const others = pick(query, ['skip', 'limit']);
    const result = await this.service.query(qobj, others);
    return result;
  }

  @Post('/', { routerName: `申请${namePrefix}` })
  @ApiTags('创建数据')
  @Validate()
  async create(@Body() data: object) {
    /**
     * 数据应该只有:
     *  apply_user, source,source_id
     * 根据source和source_id获取到数据,再根据数据的user获取普通用户信息,先将普通用户信息中的
     * 用户id(user/user表的id),电话(phone)和邮箱(email)拿来给申请填充个数据
     */
    const otherData = await this.service.searchCompleteData(get(data, 'source'), get(data, 'source_id'));
    const userData = get(otherData, 'userData');
    if (!userData) throw new ServiceError(ErrorCode.CONTACTAPPLY_TARGET_USER_NOT_FOUND);
    const target_user = get(userData, 'id');
    data['target_user'] = target_user;
    const res = await this.service.checkHasApply(data);
    if (res) {
      const status = get(res, 'status');
      // 已有申请并通过审核,直接获取联系方式
      if (status === '1') return { data: get(res, 'content') };
    }
    const dbData = await this.service.create(data);
    const msgObj = await this.service.sendMqMsg(get(dbData, 'id'));
    // 发送mq消息
    await this.msgService.create(msgObj);
    const to = get(msgObj, 'to', []);
    for (const i of to) {
      await this.msgService.toSendMq(get(i, 'user'), get(i, 'user_type'), get(dbData, 'id'));
    }
    return dbData;
  }

  @Post('/status/:id', { routerName: `审核${namePrefix}申请` })
  @ApiTags('审核申请')
  @Validate()
  async update(@Param('id') id: number, @Body('status') status: string) {
    if (!id) throw new ServiceError(ErrorCode.ID_NOT_FOUND);
    const result = await this.service.update({ id }, { status });
    this.service.sendMqMsg(id);
    return result;
  }
}
