import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/core';
import { DeptService } from '../../service/system/dept.service';
import { BaseController } from '../../frame/BaseController';
import { ApiQuery, ApiResponse, ApiTags } from '@midwayjs/swagger';
import { Validate } from '@midwayjs/validate';
import { omit, pick } from 'lodash';
import { ErrorCode, ServiceError } from '../../error/service.error';
import { CVO_dept, FVO_dept, QVO_dept, UVAO_dept } from '../../interface/system/dept.interface';

const namePrefix = '部门';
@ApiTags([namePrefix])
@Controller('/dept', { tagName: namePrefix })
export class DeptController implements BaseController {
  controllerCode = 'system_dept';
  @Inject()
  service: DeptService;

  @ApiTags('列表查询')
  @ApiQuery({ name: 'query' })
  @ApiResponse({ type: QVO_dept })
  async index(@Query() query: object) {
    const qobj = omit(query, ['skip', 'limit']);
    const others = pick(query, ['skip', 'limit']);
    const qbr = this.service.queryBuilder(qobj);
    const result = await this.service.query(qbr, others);
    return result;
  }
  @Get('/')
  @ApiTags('树型列表查询')
  @ApiResponse({ type: FVO_dept })
  async query() {
    const data = await this.service.queryAll();
    return data;
  }
  @Get('/nextLevel/:id')
  @ApiTags('下一级部门列表查询')
  @ApiQuery({ name: 'nextLevel' })
  @ApiResponse({ type: QVO_dept })
  async nextLevel(@Param('id') id: number, @Query('skip') skip: number, @Query('limit') limit: number) {
    const result = await this.service.getNextLevel(id, { skip, limit });
    return result;
  }

  @Get('/:id')
  @ApiTags('单查询')
  @ApiResponse({ type: FVO_dept })
  async fetch(@Param('id') id: number) {
    const qbr = this.service.queryBuilder({ id });
    const data = await this.service.fetch(qbr);
    const result = new FVO_dept(data);
    return result;
  }

  @Post('/', { routerName: `创建${namePrefix}` })
  @ApiTags('创建数据')
  @Validate()
  @ApiResponse({ type: CVO_dept })
  async create(@Body() data: object) {
    const dbData = await this.service.create(data);
    const result = new CVO_dept(dbData);
    return result;
  }

  @Post('/:id', { routerName: `修改${namePrefix}` })
  @ApiTags('修改数据')
  @Validate()
  @ApiResponse({ type: UVAO_dept })
  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;
  }
}
