import { BadRequestException, Injectable } from '@nestjs/common';
import { Article } from './article.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import {
  CreateArticleDto,
  CreateArticleTranslations,
  GetArticleDto,
  QueryArticleDto,
  UpdateArticleDto,
} from './dto';
import { ArticleTranslation } from './article.entity.translation';
@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private articleRepo: Repository<Article>,

    @InjectRepository(ArticleTranslation)
    private articleTranslationRepo: Repository<ArticleTranslation>,
  ) { }
  async create(createArticleDto: CreateArticleDto) {
    const article = this.articleRepo.create(createArticleDto);
    return this.articleRepo.save(article);
  }

  async findAll(query: GetArticleDto) {
    return this.articleRepo.find({ where: query });
  }
  async findPagination(query: QueryArticleDto) {
    const pageSize = query.pageSize || 10;
    const pageNo = query.pageNo || 1;

    const [data, total] = await this.articleRepo.findAndCount({
      where: {
        title: Like(`%${query.title || ''}%`),
        enable: query.enable || undefined,
      },
      relations: { user: true, category: true, translations: true },
      select: {
        user: {
          id: true,
          username: true,
        },
        category: {
          id: true,
          title: 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) {
    const article = await this.articleRepo.findOne({
      where: { id },
      relations: {
        translations: true,
      },
    });
    article.translations.forEach(async (trans) => {
      await this.articleTranslationRepo.delete(trans.id);
    });
    await this.articleRepo.remove(article);
    return true;
  }

  async find(id: number) {
    return await this.articleRepo.findOne({
      where: { id },
      relations: { user: true, translations: true },
      select: {
        user: {
          id: true,
          username: true,
        },
        category: {
          id: true,
          title: true,
        },
      },
    });
  }

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

    const updateArticle = this.articleRepo.merge(article, updateArticleDto);
    // console.log('updateArticle', updateArticle);
    await this.articleRepo.save(updateArticle);
    return true;
  }
}
