import { InjectRepository } from '@nestjs/typeorm';
import { checkAnswer } from 'src/assessment-evaluation/controller/sim-test/mistake-again.controller';
import { QuestionType } from 'src/assessment-evaluation/entities/entities-question-manager/question-type.entity';
import { Question } from 'src/assessment-evaluation/entities/entities-question-manager/question.entity';
import { SearchNoClassLsitDto } 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 { DataSource, Repository } from 'typeorm';
import { LiveAnsweringDto } from '../dto/live-question-answer.dto';
import { LiveClassify } from '../entities/live-classify.entity';
import { LiveCourseware } from '../entities/live-courseware.entity';
import { LiveEvaluate } from '../entities/live-evaluate.entity';
import { LiveQuestionAnswer } from '../entities/live-question-answer.entity';
import { LiveQuestion } from '../entities/live-question.entity';
import { LiveStudent } from '../entities/live-student.entity';
import { LiveTeaching } from '../entities/live-teaching.entity';
export class LiveClassService {
  constructor(
    // 课程学习记录
    private dataSource: DataSource,
    @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>,
    @InjectRepository(LiveQuestionAnswer)
    private LiveQuesstionAnswer_Sql: Repository<LiveQuestionAnswer>,
    // 试题表
    @InjectRepository(Question)
    private Questions_sql: Repository<Question>,
  ) {}
  // 查询课程列表
  async findMyLiveList(pageInfo, tokenInfo) {
    const page = pageInfo.page - 1;
    const pageSize = pageInfo.pageSize;
    const sql = `
    SELECT
    huai_li.live_teaching.*, 
    huai_li.live_teaching.start_time AS startTime, 
    huai_li.live_teaching.create_time AS createTime, 
    huai_li.\`user\`.id AS userId, 
    huai_li.\`user\`.name AS userName
  FROM
    huai_li.live_student
    INNER JOIN
    huai_li.live_teaching
    ON 
      huai_li.live_student.live_id = huai_li.live_teaching.id
    LEFT JOIN
    huai_li.\`user\`
    ON 
      huai_li.live_teaching.lecturer = huai_li.\`user\`.id
  WHERE
    huai_li.live_student.student_id = ? AND
    huai_li.live_student.del_flag = 0 AND
    huai_li.live_teaching.del_flag = 0
  ORDER BY
    huai_li.live_teaching.update_time DESC
  LIMIT ?,? 
 `;
    let res = await this.LiveStudent_Sql.query(sql, [
      tokenInfo.userId,
      +page,
      +pageSize,
    ]);
    const total = await this.LiveStudent_Sql.query(
      `SELECT FOUND_ROWS() as total;`,
    );
    // console.log(total);
    // res.total = total[0];
    res = { data: res, total: +total[0].total };
    return res;
  }
  // 搜索直播
  async searchMyLiveList(searchInfo: SearchNoClassLsitDto, tokenInfo) {
    const page = searchInfo.page - 1;
    const pageSize = searchInfo.pageSize;
    const sql = `
    SELECT
    huai_li.live_teaching.*, 
    huai_li.live_teaching.start_time AS startTime, 
    huai_li.live_teaching.create_time AS createTime, 
    huai_li.\`user\`.id AS userId, 
    huai_li.\`user\`.name AS userName
  FROM
  huai_li.live_student
  INNER JOIN
  huai_li.live_teaching
  ON 
    huai_li.live_student.live_id = huai_li.live_teaching.id
  LEFT JOIN
  huai_li.\`user\`
  ON 
    huai_li.live_teaching.lecturer = huai_li.\`user\`.id
  WHERE
    huai_li.live_student.student_id = ? AND
    huai_li.live_teaching.title LIKE ? AND
    huai_li.live_teaching.del_flag = 0 AND
    huai_li.live_student.del_flag = 0
  ORDER BY
    huai_li.live_teaching.update_time DESC
  LIMIT ?, ?
 `;
    let res = await this.LiveStudent_Sql.query(sql, [
      tokenInfo.userId,
      `%${searchInfo.value}%`,
      +page,
      +pageSize,
    ]);
    const total = await this.LiveStudent_Sql.query(
      `SELECT FOUND_ROWS() as total;`,
    );
    // console.log(total);
    // res.total = total[0];
    res = { data: res, total: +total[0].total };
    return res;
  }
  // 查询直播详情
  async getLiveInfo(id, tokenInfo) {
    const judgeIsviewerSql = `ls.del_flag = 0 AND ls.liveId = l.id AND ls.studentId = '${tokenInfo.userId}'`;
    const res = this.Live_Sql.createQueryBuilder('l')
      .innerJoin(LiveStudent, 'ls', judgeIsviewerSql)
      .leftJoinAndMapMany(
        'l.courseware',
        LiveCourseware,
        'lc',
        'lc.delFlag = 0 AND lc.liveId = l.id',
      )
      .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',
      )
      .leftJoinAndMapOne('l.lecturerInfo', User, 'u', 'u.id = l.lecturer')
      .leftJoinAndMapOne('u.photo', Resource, 'photo', 'photo.id = u.photo')
      .where({ id })
      .getOne();
    return res;
  }
  // 获取直播学员列表
  async getStudentList(id, tokenInfo) {
    return await this.dataSource.query(
      `select u.id id,u.name name,rr.diskname photo,0 status from (select ls.student_id uid from live_student ls where ls.live_id = ?
        union all (select lt.lecturer uid from live_teaching lt where lt.id = ?)) tdd left join user u on u.id = tdd.uid left join resource rr on  rr.id = u.photo`,
      [id, id],
    );
  }
  /**
   * 获取当前直播下所有试题
   */
  async getLiveQuestionList(liveId) {
    const res = await this.LiveQuestion_Sql.createQueryBuilder('lqs')
      .leftJoinAndMapOne('lqs.info', Question, 'q', 'q.id = lqs.question_id')
      .leftJoinAndMapOne('q.typeInfo', QuestionType, 'qt', 'qt.id = q.type')
      .leftJoinAndMapOne(
        'lqs.answer',
        LiveQuestionAnswer,
        'lqa',
        'lqa.question_id = lqs.question_id AND lqa.del_flag = 0 AND lqa.liveId = ' +
          liveId,
      )
      .where({ liveId })
      .getMany();
    return res;
  }
  // 回答练习题
  async answeringQuestions(
    { answerInfo, liveId, createTime }: LiveAnsweringDto,
    TokenData,
  ) {
    const ids = answerInfo.map((_) => _.questionId);
    console.log(ids, '====================>');

    const questions = await this.Questions_sql.query(
      `
      SELECT
      q.id as id,
      q.type as typeId,
      q.difficulty_level as  difficultyLevelId,
      q.classify_id as  classifyId,
      q.knowledge_id as knowledgeId,
      q.title as title,
      q.answer as answer ,
      q.analysis as analysis,
      q.options  as options,
      qs.score as score
     FROM question q LEFT JOIN live_question qs  ON  q.id = qs.question_id 
		where	 qs.live_id = ? AND  qs.del_flag =0 AND
     q.id IN (?)`,
      [liveId, ids],
    );
    console.log(questions);

    const res = { quesInfo: [...questions], score: 0, errorNum: 0 };
    questions.forEach((quesItem) => {
      const answerItem = answerInfo.find((an) => an.questionId === quesItem.id);
      quesItem.questionScore = quesItem.score;
      if (answerItem) {
        const result = checkAnswer(quesItem, answerItem.answer);
        res.score += result.score;
        quesItem.isPass = result.pass;
        if (result.isPass) res.errorNum++;
        quesItem.userAnswer = JSON.stringify(answerItem.answer);
        quesItem.score = result.score;
        quesItem.createTime = createTime;
        quesItem.mistakeScor = 0;
      } else {
        quesItem.score = 0;
        quesItem.createTime = new Date();
        quesItem.userAnswer = '';
      }
      quesItem.comment = '';
      quesItem.liveId = liveId;
      quesItem.questionId = quesItem.id;
      quesItem.creator = TokenData.userId;
      quesItem.updater = TokenData.userId;
      delete quesItem.id;
    });
    await this.LiveQuesstionAnswer_Sql.update(
      { liveId, creator: TokenData.userId },
      { delFlag: 1 },
    );
    console.log(questions);

    await this.LiveQuesstionAnswer_Sql.insert(questions);
    return res;
  }
}
