import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, getRepository, In, Like, Repository } from 'typeorm';
import { CourseStudyCoursewareDto } from '../dto/course-my/course-study-courseware.dto';
import { CourseStudyDiscussion } from '../entities/course-my/course-study-discussion.entity';
import { CourseStudyEvaluate } from '../entities/course-my/course-study-evaluate.entity';
import { CourseStudyExercise } from '../entities/course-my/course-study-exercise.entity';
import {
  CourseStudyDiscussionDto,
  updateStudyDiscussionkudoDto,
} from '../dto/course-my/course-study-discussion.dto';
import { CourseStudyRecord } from '../entities/course-my/course-study-record.entity';
import { CourseStudyCourseware } from '../entities/course-my/course-study-courseware.entity';
import { updateExercise } from '../dto/course-my/course-study-exercise.dto';
import {
  findMyCourse_All,
  findMyCourse_Type,
} from '../dto/course-my/course-study-record.dto';
import { User } from 'src/system/entities/user.entity';
import { CourseList } from '../entities/course-manage/course-list.entity';
import { updateEvaluate } from '../dto/course-my/course-study-evaluate.dto';
import { CourseClassify } from '../entities/course-manage/course-classify.entity';
import { OnlineCourseService } from './online-course.service';
import { Resource } from 'src/resource/entities/resource.entity';
import { QuestionsForCourse } from '../entities/course-manage/course-questions.entity';
import { Question } from 'src/assessment-evaluation/entities/entities-question-manager/question.entity';
import { QuestionType } from 'src/assessment-evaluation/entities/entities-question-manager/question-type.entity';
import { checkAnswer } from 'src/assessment-evaluation/controller/sim-test/mistake-again.controller';
import { CourseStudyDisKudos } from '../entities/course-my/course-study-discussion-kudos.entity';
export class myCourseService {
  constructor(
    // 课程学习记录
    @InjectRepository(CourseStudyRecord)
    private study_record_Sql: Repository<CourseStudyRecord>,
    // 课程学习讨论
    @InjectRepository(CourseStudyDiscussion)
    private study_discussion_Sql: Repository<CourseStudyDiscussion>,
    // 课程学习评价
    @InjectRepository(CourseStudyEvaluate)
    private study_evaluate_Sql: Repository<CourseStudyEvaluate>,
    // 课件
    @InjectRepository(CourseStudyCourseware)
    private study_coursewar_Sql: Repository<CourseStudyCourseware>,
    // 练习题
    @InjectRepository(CourseStudyExercise)
    private study_Exercise_Sql: Repository<CourseStudyExercise>,
    // // 用户
    // @InjectRepository(User)
    // private userRepository: Repository<User>,
    // 课程表
    @InjectRepository(CourseList)
    private Course_List_sql: Repository<CourseList>,
    private readonly onlineCourseService: OnlineCourseService,

    // // 试题表
    // @InjectRepository(QuestionsForCourse)
    // private QuestionsForCourse_sql: Repository<QuestionsForCourse>,

    // 试题表
    @InjectRepository(Question)
    private Questions_sql: Repository<Question>,

    // 讨论点赞表
    @InjectRepository(CourseStudyDisKudos)
    private CourseStudyDisKudos_sql: Repository<CourseStudyDisKudos>,
  ) {}
  // 查询【某个状态】课程列表
  async findMycourseList(findInfo: findMyCourse_Type, tokenInfo) {
    // 获取分页数据
    const page = findInfo.page;
    const pageSize = findInfo.pageSize;
    const findString = [
      `record.course_id = course.id`,
      `course.study_org_id = ${tokenInfo.orgId}`,
      'course.del_flag = 0',
    ];
    const res: any = await this.study_record_Sql
      .createQueryBuilder('record')
      .innerJoinAndMapOne(
        'record.courseInfo',
        CourseList,
        'course',
        findString.join(' AND '),
      )
      .leftJoinAndMapMany(
        'record.exercise',
        CourseStudyExercise,
        'exercise',
        'exercise.recordId = record.id and exercise.del_flag = 0',
      )
      .leftJoinAndMapOne(
        'record.lecturer',
        User,
        'user',
        'user.id = course.creator',
      )
      .leftJoinAndMapOne(
        'record.classify',
        CourseClassify,
        'classify',
        'classify.id = course.classify',
      )
      .andWhere({
        delFlag: 0,
        studyProgress: findInfo.type,
        studentId: tokenInfo.userId,
      })
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return {
      data: res[0],
      total: res[1],
    };
  }
  // 我的课程列表统计
  async getListCount(tokenInfo, searchVlue) {
    const orgId = tokenInfo.orgId;
    const userId = tokenInfo.userId;
    const sqlString = `
    SELECT (
      SELECT
        COUNT( course_study_record.id ) AS countList
      FROM
        course_study_record
        INNER JOIN course_list ON course_study_record.course_id = course_list.id 
      WHERE
        course_list.study_org_id = ${orgId}
        AND course_list.del_flag = 0 
        AND course_study_record.del_flag = 0 
        AND course_study_record.student_id = '${userId}' 
        AND course_study_record.study_progress = 1 ) as 'no',(
      
      SELECT
        COUNT( course_study_record.id ) AS aaa 
      FROM
        course_study_record
        INNER JOIN course_list ON course_study_record.course_id = course_list.id 
      WHERE
        course_list.study_org_id = ${orgId}
        AND course_list.del_flag = 0 
        AND course_study_record.del_flag = 0 
        AND course_study_record.student_id = '${userId}' 
        AND course_study_record.study_progress = 2 ) as 'start',
      
      
      (
      SELECT
        COUNT( course_study_record.id ) AS aaa 
      FROM
        course_study_record
        INNER JOIN course_list ON course_study_record.course_id = course_list.id 
      WHERE
        course_list.study_org_id = ${orgId}
        AND course_list.del_flag = 0 
        AND course_study_record.del_flag = 0 
        AND course_study_record.student_id = '${userId}' 
        AND course_study_record.study_progress = 3) as 'over',
      
      (
      SELECT
        COUNT(course_list.id)
      FROM
        course_list
      WHERE
        course_list.study_org_id = ${orgId} AND
        course_list.del_flag = 0
        ) as 'all'
    `;
    return (await this.Course_List_sql.query(sqlString, []))[0];
  }
  // 查找我的所有课程列表
  async findAllMyCourseList(findInfo: findMyCourse_All, tokenInfo) {
    console.log(findInfo);
    const a: any = { delFlag: 0, studyOrgId: +tokenInfo.orgId };

    const page = findInfo.page;
    const pageSize = findInfo.pageSize;
    const searchVlue = findInfo.search;
    if (searchVlue) {
      a.name = Like(`%${searchVlue}%`);
    }
    const res: any = await this.Course_List_sql.createQueryBuilder('course')
      .leftJoinAndMapOne(
        'course.record',
        CourseStudyRecord,
        'record',
        `record.del_flag = 0 AND record.courseId = course.id AND record.student_id = '${tokenInfo.userId}'`,
      )
      .leftJoinAndMapMany(
        'record.exercise',
        CourseStudyExercise,
        'exercise',
        'exercise.recordId = record.id and exercise.del_flag = 0',
      )
      .leftJoinAndMapOne(
        'record.lecturer',
        User,
        'user',
        'user.id = course.creator',
      )
      .leftJoinAndMapOne(
        'record.classify',
        CourseClassify,
        'classify',
        'course.classify = classify.id',
      )

      .andWhere(a)
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const needAdd = [];
    res[0].forEach((course) => {
      console.log(course);
      if (!course.record) {
        const newRecord: any = {
          studentId: tokenInfo.userId,
          courseId: course.id,
          studyTime: 0,
          studyProgress: 1,
          exerciseGrade: 0,
          selfEvael: '',
          courseEveal: '',
          score: 0,
          createTime: course.createTime,
          creator: course.creator,
          delFlag: 0,
          updater: course.updater,
          remarks: null,
          version: 1,
          id: undefined,
        };
        course.record = newRecord;
        needAdd.push(newRecord);
      }
    });
    needAdd.length && (await this.study_record_Sql.save(needAdd));
    return {
      data: res[0],
      count: await this.getListCount(tokenInfo, searchVlue),
    };
  }
  async findComment(courseId) {
    const discussion = await this.study_discussion_Sql
      .createQueryBuilder('sds')
      .leftJoinAndMapMany(
        'sds.kudos',
        CourseStudyDisKudos,
        'csdk',
        `csdk.record_id = ${courseId} and csdk.dis_id = sds.id and csdk.del_flag = 0`,
      )
      .leftJoinAndMapOne(`sds.userInfo`, User, 'du', 'du.id = sds.creator')
      .where({ delFlag: 0, recordId: courseId })
      .getMany();
    const courseInfo = await this.onlineCourseService.findOne(courseId);
    return { discussion, courseInfo };
  }
  // 查找某个记录的详细信息
  async fingOneRecord(id, tokenInfo) {
    const findString = [
      `course.id = record.course_id`,
      `course.del_flag = 0`,
      `course.study_org_id = ${tokenInfo.orgId}`,
      `course.status = 1`,
    ];
    const res: any = await this.study_record_Sql
      .createQueryBuilder('record')
      .leftJoinAndMapMany(
        'record.exercise',
        CourseStudyExercise,
        'exercise',
        'exercise.recordId = record.id and exercise.del_flag = 0',
      )
      .leftJoinAndMapOne(
        'exercise.answer',
        CourseStudyExercise,
        'cse',
        `exercise.question_id = exercise.question_id and cse.del_flag = 0 and cse.recordId = ${id}`,
      )
      .leftJoinAndMapMany(
        'record.eveal',
        CourseStudyEvaluate,
        'eveal',
        'eveal.recordId = record.id',
      )
      .leftJoinAndMapMany(
        'record.discussion',
        CourseStudyDiscussion,
        'discussion',
        'discussion.recordId = record.courseId and discussion.del_flag = 0',
      )
      .leftJoinAndMapMany(
        'record.courseware',
        CourseStudyCourseware,
        'courseware',
        'courseware.record_id = record.id and courseware.del_flag = 0',
      )
      .leftJoinAndMapOne(
        `discussion.userInfo`,
        User,
        'du',
        'du.id = discussion.creator',
      )
      .leftJoinAndMapOne(
        `discussion.replyUserInfo`,
        User,
        'ru',
        'ru.id = discussion.reply_user_id',
      )
      .leftJoinAndMapOne(
        'record.courseInfo',
        CourseList,
        'course',
        findString.join(' AND '),
      )
      .leftJoinAndMapMany(
        'discussion.kudos',
        CourseStudyDisKudos,
        'csdk',
        `csdk.record_id = record.courseId and csdk.dis_id = discussion.id and csdk.del_flag = 0`,
      )
      .leftJoinAndMapOne(
        'record.lecturer',
        User,
        'user',
        'user.id = course.creator',
      )
      .leftJoinAndMapOne(
        'record.classifyInfo',
        CourseClassify,
        'classify',
        'classify.id = course.classify',
      )
      .andWhere({ delFlag: 0, id })
      .getOne();
    if (res.courseInfo) {
      res.courseInfo = await this.onlineCourseService.findOne(
        res.courseInfo.id,
      );
      console.log(res.courseInfo);
    }
    this.fingOneRecordThen(res);
    return res;
  }
  // 课程查看后的处理
  async fingOneRecordThen(record) {
    if (record.isFirst && record.courseInfo) {
      // 设置课程观看人数+1
      this.Course_List_sql.query(
        `update course_list set view_number=view_number+1 where  id= ${record.courseInfo.id};`,
      );
      // 修改
      this.study_record_Sql.update({ id: record.id }, { isFirst: 0 });
    }
  }
  // 查找试题的详细信息
  async findOneRecordExercise(id, tokenInfo) {
    const res = await this.study_record_Sql
      .createQueryBuilder('srs')
      .leftJoin(CourseList, 'cl', 'srs.course_id = cl.id')
      .leftJoinAndMapMany(
        'srs.exercise',
        QuestionsForCourse,
        'qfc',
        'qfc.course_id = cl.id AND qfc.del_flag = 0',
      )
      .leftJoinAndMapOne('qfc.info', Question, 'q', 'q.id = qfc.question_id')
      .leftJoinAndMapOne('q.typeInfo', QuestionType, 'qt', 'qt.id = q.type')
      .leftJoinAndMapOne(
        'qfc.answer',
        CourseStudyExercise,
        'cse',
        `qfc.question_id = cse.question_id and cse.del_flag = 0 and cse.recordId = ${id}`,
      )
      .where({ id, studentId: tokenInfo.userId })
      .getOne();
    return res;
  }

  // 更新课件信息
  async updateStudy_ware(wareInfo: CourseStudyCoursewareDto | any, tokenInfo) {
    await this.study_record_Sql.update(wareInfo.recordId, {
      score: wareInfo.score,
      studyProgress: wareInfo.courseStudyOver,
    });
    delete wareInfo.courseStudyOver;
    delete wareInfo.score;
    wareInfo.creator = tokenInfo.userId;
    wareInfo.updater = tokenInfo.userId;
    console.log(wareInfo);
    const newData: any = wareInfo;
    const res = await this.study_coursewar_Sql.save(newData);
    return res;
  }
  // 更新评价信息
  async updateStudy_eveal(evealData: updateEvaluate) {
    const res: any = {};
    if (evealData.textEvealInfo) {
      res.textEvealInfo = await this.study_record_Sql.update(
        evealData.textEvealInfo.id,
        { ...evealData.textEvealInfo },
      );
    }
    if (evealData.evealInfo) {
      res.evealaute = await this.study_evaluate_Sql.save(evealData.evealInfo);
    }
    return res;
  }
  /**
   * 更新课程讨论信息;
   * */
  async updateStudy_discussion(
    discussionInfo: CourseStudyDiscussionDto,
    tokenInfo,
  ) {
    const saveData = {
      ...discussionInfo,
      creator: tokenInfo.userId,
      updater: tokenInfo.userId,
    };
    const res = await this.study_discussion_Sql.save(saveData);
    return res;
  }
  /**
   * 更新课程讨论点赞;
   * */
  async updateStudyDiscussionKudos(
    data: updateStudyDiscussionkudoDto,
    tokenInfo,
  ) {
    data.updater = tokenInfo.userId;
    data.creator = tokenInfo.userId;
    const result = await this.CourseStudyDisKudos_sql.save(data);
    const res = this.CourseStudyDisKudos_sql.findBy({
      recordId: result.recordId,
      disId: result.disId,
      delFlag: 0,
    });
    return res;
  }
  /**
   * 更新课程练习题信息
   */
  async manageStudy_exercise(
    { coureseId, answer, recordId, createTime }: updateExercise,
    TokenData,
  ) {
    const ids = answer.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 questions_for_course qs ON q.id = qs.question_id and qs.course_id = ? AND qs.del_flag =0 AND qs.course_id = ?  WHERE q.id IN (?)`,
      [coureseId, coureseId, ids],
    );
    console.log(answer);
    const res = { quesInfo: [...questions], score: 0, errorNum: 0 };
    // console.log(questions, '================>');

    questions.forEach((quesItem) => {
      const answerItem = answer.find((an) => an.questionId === quesItem.id);
      if (answerItem) {
        const result = checkAnswer(quesItem, answerItem.answer);
        res.score += result.score;
        quesItem.isPass = result.pass;
        if (result.isPass) res.errorNum++;
        quesItem.createTime = createTime;
        quesItem.userAnswer = JSON.stringify(answerItem.answer);
        quesItem.comment = '';
        quesItem.questionScore = quesItem.score;
        quesItem.recordId = recordId;
        quesItem.questionId = quesItem.id;
        quesItem.score = result.score;
        quesItem.mistakeScor = 0;
        quesItem.creator = TokenData.userId;
        quesItem.updater = TokenData.userId;
        delete quesItem.id;
      }
    });
    this.study_record_Sql.update(recordId, {
      exerciseGrade: res.score,
      isAnswer: 1,
    });
    await this.study_Exercise_Sql.update(
      { recordId: recordId },
      { delFlag: 1 },
    );
    console.log(questions);
    await this.study_Exercise_Sql.insert(questions);
    return res;
  }
}
