import { GenericCrudService } from '@/server/utils/generic-crud.service';
import { DataSource } from 'typeorm';
import { Template } from './template.entity';

export class TemplateService extends GenericCrudService<Template> {
  constructor(dataSource: DataSource) {
    super(dataSource, Template);
  }

  /**
   * 获取可用的模板列表（排除禁用和删除的）
   */
  async getAvailableTemplates(
    page: number = 1,
    pageSize: number = 10,
    category?: string,
    isFree?: boolean
  ): Promise<[Template[], number]> {
    const where: any = {
      isDisabled: 0,
      isDeleted: 0
    };

    if (category) {
      where.category = category;
    }

    if (isFree !== undefined) {
      where.isFree = isFree ? 1 : 0;
    }

    return this.getList(
      page,
      pageSize,
      undefined,
      ['title', 'description'],
      where,
      ['file']
    );
  }

  /**
   * 获取热门模板（按下载次数排序）
   */
  async getPopularTemplates(limit: number = 10): Promise<Template[]> {
    const [templates] = await this.getList(
      1,
      limit,
      undefined,
      undefined,
      { isDisabled: 0, isDeleted: 0 },
      ['file'],
      { downloadCount: 'DESC' }
    );
    return templates;
  }

  /**
   * 获取模板分类列表
   */
  async getCategories(): Promise<string[]> {
    const query = this.repository
      .createQueryBuilder('template')
      .select('DISTINCT template.category')
      .where('template.isDisabled = :isDisabled', { isDisabled: 0 })
      .andWhere('template.isDeleted = :isDeleted', { isDeleted: 0 })
      .orderBy('template.category', 'ASC');

    const result = await query.getRawMany();
    return result.map(item => item.category);
  }

  /**
   * 增加下载次数
   */
  async incrementDownloadCount(id: number): Promise<void> {
    await this.repository.increment({ id }, 'downloadCount', 1);
  }

  /**
   * 检查用户是否有下载权限
   */
  async checkDownloadPermission(id: number, userId: number): Promise<boolean> {
    const template = await this.getById(id, ['file']);
    if (!template) {
      throw new Error('模板不存在');
    }

    // 免费模板直接允许下载
    if (template.isFree) {
      return true;
    }

    // 检查用户会员状态
    const userRepository = this.dataSource.getRepository('UserEntity');
    const user = await userRepository.findOne({
      where: { id: userId },
      relations: ['membership']
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 检查用户是否激活的会员
    if (user.membership && user.membership.isActive) {
      const now = new Date();
      if (new Date(user.membership.expiresAt) > now) {
        return true;
      }
    }

    return false;
  }
}