import { BadRequestException, Injectable } from '@nestjs/common';
import { Category } from './category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { CreateCategoryDto, GetAllCategoryDto, GetCategoryDto, UpdateCategoryDto } from './dto';
import { SharedService } from '@/shared/shared.service';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepo: Repository<Category>,
    private readonly sharedService: SharedService,
  ) { }

  async create(createCategoryDto: CreateCategoryDto) {
    const category = this.categoryRepo.create(createCategoryDto);
    // console.log('category', category);
    return this.categoryRepo.save(category);
  }

  async findAll(query: GetAllCategoryDto) {
    return this.categoryRepo.find({ where: query });
  }

  async findAllWithTree(query: GetAllCategoryDto) {
    const categories = await this.categoryRepo.find({ where: query });
    return this.sharedService.handleTree(categories);
  }

  async findPagination(query: GetCategoryDto) {
    const pageSize = query.pageSize || 10;
    const pageNo = query.pageNo || 1;
    const [data, total] = await this.categoryRepo.findAndCount({
      where: {
        title: Like(`%${query.title || ''}%`),
        enable: query.enable || undefined,
      },
      // children: true
      relations: { parent: true, user: 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.categoryRepo.delete(id);
    return true;
  }

  async update(id: number, updateCategoryDto: UpdateCategoryDto) {
    const category = await this.categoryRepo.findOne({ where: { id } });
    if (!category) throw new BadRequestException('权限不存在或者已删除');

    const updateCategory = this.categoryRepo.merge(category, updateCategoryDto);
    delete updateCategory.userId;
    delete updateCategory.user;
    console.log('updateCategory', updateCategory);
    await this.categoryRepo.save(updateCategory);
    return true;
  }
}
