import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Menu } from './menu.entity';
import { Like, Repository } from 'typeorm';
import { CreateMenuDto, GetMenuDto, QueryMenuDto, UpdateMenuDto } from './dto';
import { MenuTranslation } from './menu.entity.translation';

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private menuRepo: Repository<Menu>,

    @InjectRepository(MenuTranslation)
    private menuTranslation: Repository<MenuTranslation>,
  ) {}

  async create(createMenuDto: CreateMenuDto) {
    const menu = this.menuRepo.create(createMenuDto);
    // console.log('menu', menu);
    return this.menuRepo.save(menu);
  }

  async findPagination(query: QueryMenuDto) {
    const pageSize = query.pageSize || 10;
    const pageNo = query.pageNo || 1;
    const [data, total] = await this.menuRepo.findAndCount({
      where: {
        title: Like(`%${query.title || ''}%`),
        parentId: query.parentId || undefined,
        enable: query.enable || undefined,
      },
      relations: { user: true, category: true, translations: true },
      order: {
        // title: 'ASC',
        createTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNo - 1) * pageSize,
    });
    const pageData = data.map((item) => {
      return { ...item };
    });
    return { pageData, total };
  }

  async remove(id: number) {
    await this.menuRepo.delete(id);
    return true;
  }
  async find(id: number) {
    return await this.menuRepo.findOne({ where: { id } });
  }
  async findWithChild(id: number) {
    return await this.menuRepo.findOne({
      where: { id },
      relations: { children: true, user: true, translations: true },
    });
  }

  async findAll(query: GetMenuDto) {
    return this.menuRepo.find({ where: query });
  }

  async findLevel(level: number) {
    return await this.menuRepo.find({
      where: { level },
      relations: { user: true, category: true, children: true },
    });
  }

  async update(id: number, updateMenuDto: UpdateMenuDto) {
    const menu = await this.menuRepo.findOne({ where: { id } });
    if (!menu) throw new BadRequestException('权限不存在或者已删除');
    const updateMenu = this.menuRepo.merge(menu, updateMenuDto);
    delete updateMenu.userId;
    delete updateMenu.user;
    await this.menuRepo.save(updateMenu);
    return true;
  }
}
