import { InjectRepository } from '@nestjs/typeorm';
import { Question } from 'src/assessment-evaluation/entities/entities-question-manager/question.entity';
import { CreateCourseclassifyDto } from 'src/online-course/dto/course-manage/course-classify.dto';
import { SearchLsitDto } from 'src/online-course/dto/course-manage/get-course-list-dto';
import { Resource } from 'src/resource/entities/resource.entity';
import { User } from 'src/system/entities/user.entity';
import { Like, Repository } from 'typeorm';
import { UpdateLiveTeachingDto } from '../dto/live-update.dto';
import { LiveClassify } from '../entities/live-classify.entity';
import { LiveCourseware } from '../entities/live-courseware.entity';
import { LiveEvaluate } from '../entities/live-evaluate.entity';
import { LiveQuestion } from '../entities/live-question.entity';
import { LiveStudent } from '../entities/live-student.entity';
import { LiveTeaching } from '../entities/live-teaching.entity';
export class LiveTeachingService {
  constructor(
    // 课程学习记录
    @InjectRepository(LiveTeaching)
    private Live_Sql: Repository<LiveTeaching>,
    @InjectRepository(LiveCourseware)
    private LiveCourseware_Sql: Repository<LiveCourseware>,
    @InjectRepository(LiveEvaluate)
    private LiveEvaluate_Sql: Repository<LiveEvaluate>,
    @InjectRepository(LiveQuestion)
    private LiveQuestion_Sql: Repository<LiveQuestion>,
    @InjectRepository(LiveStudent)
    private LiveStudent_Sql: Repository<LiveStudent>,
    @InjectRepository(LiveClassify)
    private LiveClassify_Sql: Repository<LiveClassify>,
  ) {}
  // 查询直播列表
  async findLiveList(pageInfo, { userId }) {
    const page = pageInfo.page;
    const pageSize = pageInfo.pageSize;
    const res = await this.Live_Sql.createQueryBuilder('live')
      .leftJoinAndMapOne(
        'live.lecturerInfo',
        User,
        'user',
        'user.id = live.lecturer',
      )
      .where({
        delFlag: 0,
        lecturer: userId,
      })
      .orderBy('live.updateTime', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return {
      data: res[0],
      total: res[1],
    };
  }
  // 新建直播
  async createLive(liveData: any, tokenData) {
    liveData.creator = tokenData.userId;
    liveData.updater = tokenData.userId;

    const res = await this.Live_Sql.save(liveData);

    const liveId = res.id;
    const courseware = liveData.liveCourseware.map((ware) => {
      return { fileId: ware.fileId, liveId };
    });
    const evealuate = liveData.evalDimension.map((eveal) => {
      return {
        liveId,
        dimensionality: eveal.dimensionality,
        type: eveal.type,
      };
    });
    const question = liveData.liveQuestion.map((lq) => {
      delete lq.liveId;
      return {
        liveId,
        ...lq,
      };
    });
    const students = liveData.liveStudent.map((id) => {
      return {
        studentId: id,
        liveId,
      };
    });
    this.LiveCourseware_Sql.insert(courseware);
    this.LiveEvaluate_Sql.insert(evealuate);
    this.LiveQuestion_Sql.insert(question);
    this.LiveStudent_Sql.insert(students);
    return res;
  }
  // 搜索直播
  async searchSomeLive(searchInfo: SearchLsitDto) {
    const page = searchInfo.page - 1;
    const pageSize = searchInfo.pageSize;
    const res: any = await this.Live_Sql.createQueryBuilder('live')
      .leftJoinAndMapOne(
        'live.lecturerInfo',
        User,
        'user',
        'user.id = live.lecturer',
      )
      .where({
        delFlag: 0,
        title: Like(`%${searchInfo.value}%`),
      })
      .skip(page * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return {
      total: res[1],
      data: res[0],
    };
  }
  // 编辑直播时某个直播的详细信息
  async findOneInfo(id, tokenInfo) {
    const res = this.Live_Sql.createQueryBuilder('live')
      .leftJoinAndMapMany(
        'live.liveCourseware',
        LiveCourseware,
        'lcs',
        `lcs.liveId = live.id AND lcs.del_flag = 0`,
      )
      .leftJoinAndMapOne(
        'live.lecturerInfo',
        User,
        'user',
        'user.id = live.lecturer',
      )
      .leftJoinAndMapMany(
        'live.evalDimension',
        LiveEvaluate,
        'le',
        'le.liveId = live.id  AND le.del_flag = 0',
      )
      .leftJoinAndMapMany(
        'live.liveQuestion',
        LiveQuestion,
        'lq',
        'lq.liveId = live.id  AND lq.del_flag = 0',
      )
      .leftJoinAndMapMany(
        'live.liveStudent',
        LiveStudent,
        'ls',
        'ls.liveId = live.id  AND ls.del_flag = 0',
      )
      .leftJoinAndMapOne(
        'ls.info',
        User,
        'student',
        'student.id = ls.student_id ',
      )
      .leftJoinAndMapOne(
        'lcs.info',
        Resource,
        'lcsInfo',
        'lcs.file_id = lcsInfo.id',
      )
      .leftJoinAndMapOne(
        'lq.info',
        Question,
        'lqInfo',
        'lq.question_id = lqInfo.id',
      )
      .leftJoinAndMapOne('ls.info', User, 'lsInfo', 'ls.studentId = lsInfo.id')
      .where({ id })
      .getOne();
    return res;
  }
  // 编辑直播
  async updateLive(liveData: UpdateLiveTeachingDto, tokenInfo) {
    this.Live_Sql.update(liveData.id, { delFlag: 1 });
    delete liveData.id;
    return this.createLive(liveData, tokenInfo);
  }
  // 删除直播
  async deleteLive(id: [], tokenInfo) {
    const res = await this.Live_Sql.update(id, {
      delFlag: 1,
      updater: tokenInfo.userId,
    });
    return res;
  }
  // 开始直播时查询直播详情
  async getLiveInfo(id, tokenInfo) {
    const res = this.Live_Sql.createQueryBuilder('l')
      .leftJoinAndMapMany(
        'l.courseware',
        LiveCourseware,
        'lc',
        'lc.delFlag = 0 AND lc.liveId = l.id',
      )
      .leftJoinAndMapOne('l.lecturerInfo', User, 'user', 'user.id = l.lecturer')
      .leftJoinAndMapOne('user.photo', Resource, 'r', 'r.id = user.photo')
      .leftJoinAndMapMany(
        'l.evealuate',
        LiveEvaluate,
        'le',
        'le.delFlag = 0 AND le.liveId = l.id',
      )
      .leftJoinAndMapMany(
        'l.question',
        LiveQuestion,
        'lq',
        'lq.delFlag = 0 AND lq.liveId = l.id',
      )
      .where({ id })
      .getOne();
    return res;
  }
  /*
   * 更新直播某部分信息 如（开始直播时，直播状态调整）
   */
  async updateLiveInfo(data) {
    return await this.Live_Sql.update(data.id, data);
  }
  // -------------------分类模块------------------  //
  // 分类查询
  // 查询所有分类
  async getclassifyList() {
    const res = await this.LiveClassify_Sql.findBy({ delFlag: 0 });
    return res;
  }
  // 新建分类
  async createclassify(classify: CreateCourseclassifyDto) {
    const res = await this.LiveClassify_Sql.save(classify);
    return res;
  }
  // 编辑分类
  async updateclassify(id, classify) {
    const res = await this.LiveClassify_Sql.update(id, classify);
    return res;
  }
  // 删除分类
  async deleteclassify({ id }) {
    const res = await this.LiveClassify_Sql.update(id, { delFlag: 1 });
    return res;
  }
}
