import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
  CourseNotesDto,
  updateNoteDto,
} from '../dto/course-notes/course-nots.dto';
import { CourseNotes } from '../entities/course-notes/course-notes.entity';
export class CourseNotesService {
  constructor(
    // 课程学习记录
    @InjectRepository(CourseNotes)
    private CourseNotes_Sql: Repository<CourseNotes>,
  ) {}
  // 查询笔记列表
  async findNotes(pageInfo, { userId }) {
    const page = pageInfo.page;
    const pageSize = pageInfo.pageSize;
    console.log(userId);

    const res = await this.CourseNotes_Sql.createQueryBuilder('note')
      .where({
        delFlag: 0,
        creator: userId,
      })
      .select(['note.updateTime', 'note.id', 'note.title', 'note.explain'])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return res;
  }
  // 某个笔记详情
  async findOneNote(id, tokenInfo) {
    const res = await this.CourseNotes_Sql.findOneBy({
      id: id,
      creator: tokenInfo.userId,
    });
    this.CourseNotes_Sql.query(
      `update course_notes set view_count = view_count + 1  where id = ?
    `,
      [id],
    );
    return res;
  }
  async createNote(noteData: CourseNotesDto, tokenData) {
    noteData.creator = tokenData.userId;
    noteData.updater = tokenData.userId;
    const res = await this.CourseNotes_Sql.save(noteData);
    return res;
  }
  async updateNote(id, noteInfo: updateNoteDto, tokenInfo) {
    let res: any = await this.CourseNotes_Sql.update(id, {
      ...noteInfo,
      updater: tokenInfo.userId,
    });
    res = this.CourseNotes_Sql.findOneBy({ id });
    return res;
  }
  async deleteNote(id, tokenInfo) {
    const res = await this.CourseNotes_Sql.update(id, {
      delFlag: 1,
      updater: tokenInfo.userId,
    });
    return res;
  }
}
