import { InjectRepository } from '@nestjs/typeorm';
import { ResourceDiscussion } from '../entities/resource-discussion.entity';
import { Repository } from 'typeorm';

import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
import { CreateDto } from 'src/common/dto/create.dto';
import { PaginationDTO } from 'src/assessment-evaluation/dto/pagination.dto';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
export class ResourceDiscussionService {
  constructor(
    // 课程学习讨论
    @InjectRepository(ResourceDiscussion)
    private ResourceDiscussionRep: Repository<ResourceDiscussion>,
  ) {}
  /**
   * 查询讨论信息;
   * */
  async updateStudy_discussion(
    ResourceDiscussion: ResourceDiscussionDto,
    tokenInfo,
  ) {
    const saveData = {
      ...ResourceDiscussion,
      creator: tokenInfo.userId,
      updater: tokenInfo.userId,
    };
    const res = await this.ResourceDiscussionRep.save(saveData);
    return res;
  }
  /**
   * 分页查询公共讨论
   */
  async paging(paging: PaginationDTO) {
    if (!paging.records) {
      paging.records = 'resource';
    }
    const countSql = `select
    rd.create_time createTime,
    rd.creator ,
    rd.update_time updateTime,
    rd.updater ,
    rd.del_flag delFlag,
    rd.remarks ,
    rd.version ,
    rd.id,
    rd.type,
    rd.reply_id replyId,
    rd.reply_user_id replyUserId ,
    rd.root_dis rootDis,
    rd.content,
    u.name as creatorName,
    u2.name as replyUserName,
    r.diskname as avatar
  
  from
    resource_discussion rd
    left join user u on u.id = rd.creator 
    left join user u2 on u2.id = rd.reply_user_id 
    left join resource r on u.photo  = r.id
  where rd.del_flag = 0 and rd.type = '${paging.records}'
  `;
    const dataSql =
      countSql +
      `order by rd.id desc
    limit ${+(paging.currentPage - 1) * paging.pageSize},${+paging.pageSize}`;
    const datas = await this.ResourceDiscussionRep.query(dataSql);
    const counts = await this.ResourceDiscussionRep.query(countSql);
    return {
      currentPage: paging.currentPage,
      pageSize: paging.pageSize,
      total: counts.length,
      data: datas,
    };
  }
  async delete(id: number, token: TokenDataEntity) {
    const discussionItem = await this.ResourceDiscussionRep.findOneBy({ id });
    if (discussionItem?.creator != token.userId) {
      throw '不是当前用户的评论，删除失败';
    }
    this.ResourceDiscussionRep.delete({ rootDis: id });
    return this.ResourceDiscussionRep.delete({ id });
  }
}

/**
 * 学员讨论信息
 */
export class ResourceDiscussionDto extends CreateDto {
  @ApiProperty({ description: '公共讨论类型' })
  @IsNotEmpty({ message: '公共讨论类型不能为空' })
  type: string;

  @ApiProperty({ description: '所回复的评论id' })
  replyId: number;

  @ApiProperty({ description: '所回复评论的用户id' })
  replyUserId: string;
  @ApiProperty({ description: '所回复评论内容' })
  @IsNotEmpty({ message: '所回复评论内容不能为空' })
  content: string;

  @ApiProperty({ description: '所回复评论的根ID' })
  rootDis: number;
}
