import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { CreateCourseclassifyDto } from '../dto/course-manage/course-classify.dto';
import { CreateOnlineCourseDto } from '../dto/course-manage/create-online-course.dto';
import { UpdateOnlineCourseDto } from '../dto/course-manage/update-online-course.dto';
import { CourseClassify } from '../entities/course-manage/course-classify.entity';
import { CourseList } from '../entities/course-manage/course-list.entity';
import { CourseSectionCourseware } from '../entities/course-manage/course-courseware.entity';
import { courseSectionContent } from '../entities/course-manage/course-section-content.entity';
import { courseEvaluate } from '../entities/course-manage/course-evaluate.entity';
import { DeleteDto } from '../common/delete-dto';
import { SearchLsitDto } from '../dto/course-manage/get-course-list-dto';
import { User } from 'src/system/entities/user.entity';
import { CourseStudyRecord } from '../entities/course-my/course-study-record.entity';
import { Question } from 'src/assessment-evaluation/entities/entities-question-manager/question.entity';
import { QuestionsForCourse } from '../entities/course-manage/course-questions.entity';
import { Resource } from 'src/resource/entities/resource.entity';
import { PaginationDTO } from '../common/pagination.dto';
@Injectable()
export class OnlineCourseService {
  constructor(
    // 课程列表
    @InjectRepository(CourseList)
    private CourseList_SQL: Repository<CourseList>,
    // 课程分类
    @InjectRepository(CourseClassify)
    private Course_classify_SQL: Repository<CourseClassify>,
    // 课件信息
    @InjectRepository(CourseSectionCourseware)
    private course_courseware_SQL: Repository<CourseSectionCourseware>,
    // 章节信息
    @InjectRepository(courseSectionContent)
    private course_section_content_SQL: Repository<courseSectionContent>,
    // 评价维度
    @InjectRepository(courseEvaluate)
    private course_evaluate_SQL: Repository<courseEvaluate>,
    // 用户表
    @InjectRepository(User)
    private User_SQL: Repository<User>,
    // 学习记录表
    @InjectRepository(CourseStudyRecord)
    private record_SQL: Repository<CourseStudyRecord>,
    // 试题表
    @InjectRepository(QuestionsForCourse)
    private QuestionsForCourse_SQL: Repository<QuestionsForCourse>,
  ) {}
  async getCourseEvaluate(courseId: number, paging: PaginationDTO) {
    const sql = `select
    concat('[', group_concat('{"k":"', ce.dimensionality, '","v":', cse.value, '}'), ']' ) value,
    csr.self_evael eval,
    csr.student_id sid,
    u.name uname
  from
    course_study_evaluate cse
  left join course_evaluate ce on
    ce.id = cse.dimension_id
  left join course_study_record csr on
    csr.id = cse.record_id
  left join user u on
    u.id = csr.student_id
  where
    ce.course_id = ${courseId}
  group by
    csr.student_id
    `;
    const datas = await this.record_SQL.query(
      sql + `limit ${(paging.page - 1) * paging.pageSize},${paging.pageSize}`,
    );
    const [{ count }] = await this.record_SQL.query(
      `select count(1) count from (${sql}) c`,
    );
    return {
      data: datas,
      total: count,
      page: paging.page,
      pageSize: paging.pageSize,
    };
  }
  // 新建课程
  async create(courseInfo: CreateOnlineCourseDto) {
    const saveInfo: any = courseInfo;
    const res = await this.CourseList_SQL.save(saveInfo);
    // 评价
    const evaluate: any = courseInfo.evalDimension;
    if (evaluate && evaluate.length > 0) {
      evaluate.forEach((item) => {
        item.courseId = res.id;
      });
      this.course_evaluate_SQL.insert(evaluate);
    }
    // 习题

    /* 章节
    先保存章节信息拿到ID
    根据ID保存课件信息
    */
    let courseHours = 0;
    const section: any = courseInfo.courseSectionContent;
    if (section && section.length > 0) {
      section.forEach((item) => {
        item.courseId = res.id;
      });
      const sectionRes = await this.course_section_content_SQL.save(section);
      // 课件
      const coursewareList = [];
      sectionRes.forEach((item) => {
        item.courseware.forEach((courseware) => {
          courseware.courseId = res.id;
          courseware.sectionId = item.id;
          courseHours += courseware.studyTime;
          coursewareList.push(courseware);
        });
      });

      this.course_courseware_SQL.insert(coursewareList);
    }
    saveInfo.courseHours = courseHours;
    this.CourseList_SQL.save(saveInfo);
    courseInfo.exercise.forEach((exer: any) => {
      exer.courseId = res.id;
    });
    await this.QuestionsForCourse_SQL.save(courseInfo.exercise);
    return res;
  }
  // 新建课程学习记录
  async createUserRecord(courseInfo: CourseList, createType) {
    // if (createType == 'create') {
    //   const recordUserList = await this.User_SQL.findBy({
    //     delFlag: 0,
    //     orgId: courseInfo.studyOrgId,
    //   });
    // }
    // let res;
    // if (courseInfo.id) {
    //   const findSqlString = `user.id = record.studentId AND record.courseId = ${courseInfo.id}`;
    //   res = await this.User_SQL.createQueryBuilder('user')
    //     .leftJoinAndMapOne(
    //       'user.recordInfo',
    //       CourseStudyRecord,
    //       'record',
    //       findSqlString,
    //     )
    //     .andWhere({ delFlag: 0, orgId: courseInfo.studyOrgId })
    //     .getMany();
    //   const needUpdate = [];
    //   const needAdd = [];
    //   res.forEach((user) => {
    //     if (user.recordInfo) {
    //       user.recordInfo.del_flag = 0;
    //       needUpdate.push(user.recordInfo.id);
    //     } else {
    //       needAdd.push(user);
    //     }
    //   });
    //   console.log(needUpdate, '需要更新的用户');
    //   if (needUpdate.length) {
    //     const look = await this.record_SQL.update(needUpdate, { delFlag: 0 });
    //     console.log(look);
    //   }
    //   res = needAdd;
    // } else {
    //   res = await this.User_SQL.findBy({ orgId: courseInfo.studyOrgId });
    // }
    // if (res && res.length > 0) {
    //   const addRecordList = [];
    //   res.forEach((userInfo) => {
    //     const record: any = {
    //       studentId: userInfo.id,
    //       courseId: courseInfo.id,
    //       studyTime: 0,
    //       studyProgress: 1,
    //       exerciseGrade: 0,
    //       selfEvael: '',
    //       courseEveal: '',
    //       score: 0,
    //       createTime: courseInfo.createTime,
    //       id: undefined,
    //       creator: userInfo.id,
    //       updater: userInfo.id,
    //       version: 0,
    //       delFlag: 0,
    //       remarks: null,
    //     };
    //     addRecordList.push(record);
    //   });
    //   this.record_SQL.save(addRecordList);
    // }
  }
  // 编辑课程时修改了课程的所属机构，则需用到此函数，创建新的学习记录
  async editorUserRecord(courseInfo, oldCourse) {
    const res = await this.User_SQL.findBy({ orgId: oldCourse[0].studyOrgId });
    const ids = courseInfo;
    const idList: string[] = res.map((user) => user.id);
    await this.record_SQL.query(
      `update course_study_record csr set del_flag=1 where csr.student_id in (${
        "'" + idList.join("','") + "'"
      }) and course_id=${oldCourse[0].id} and csr.del_flag=0`,
    );
    // this.createUserRecord(courseInfo);
  }
  //  编辑课程
  async update(id: number, courseInfo: UpdateOnlineCourseDto) {
    // const oldCourse = await this.CourseList_SQL.query(
    //   `SELECT cl.study_org_id=${courseInfo.studyOrgId} as isNotDiff,cl.* from huai_li.course_list cl where cl.id=${id} and del_flag = 0`,
    // );
    // const newCourseInfo: any = courseInfo;
    this.QuestionsForCourse_SQL.update({ id }, { delFlag: 1 });
    const saveInfo: any = courseInfo;
    const courseSectionContent = courseInfo.courseSectionContent;
    const courseEvaluate = courseInfo.evalDimension;
    const exercise = courseInfo.exercise;
    delete courseInfo.courseSectionContent;
    delete courseInfo.evalDimension;
    delete courseInfo.exercise;
    if (courseEvaluate && courseEvaluate.length > 0) {
      this.course_evaluate_SQL.save(courseEvaluate);
    }
    // 课件列表
    const coursewareLsit = [];
    // 课程学时
    let courseHours = 0;
    // 保存章节信息，并遍历获取课件信息
    if (courseSectionContent && courseSectionContent.length > 0) {
      const cc: any = await this.course_section_content_SQL.save(
        courseSectionContent,
      );
      cc.forEach((section) => {
        if (section.courseware && section.courseware.length > 0) {
          section.courseware.forEach((courseware) => {
            courseware.sectionId = section.id;
            courseware.courseId = id;
            courseHours += courseware.studyTime;
            coursewareLsit.push(courseware);
          });
        }
      });
      this.course_courseware_SQL.save(coursewareLsit);
    }
    saveInfo.courseHours = courseHours;
    const res = await this.CourseList_SQL.update(id, saveInfo);
    await this.QuestionsForCourse_SQL.update({ courseId: id }, { delFlag: 1 });
    this.QuestionsForCourse_SQL.insert(exercise);
    return res;
  }
  // 编辑课程状态信息等
  async updateStatus(id: number, data) {
    const res = await this.CourseList_SQL.update(id, data);
    return res;
  }
  // 查询课程列表
  async findAll(getInfo, tokenData) {
    const { page, pageSize } = getInfo;
    const res = await this.CourseList_SQL.createQueryBuilder('course')
      .leftJoinAndMapOne(
        'course.creator_info',
        User,
        'user',
        'course.creator = user.id',
      )
      .andWhere({ delFlag: 0, creator: tokenData.userId })
      .andWhere(getInfo.classify == 0 ? {} : { classify: getInfo.classify })
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    return {
      data: res[0],
      total: res[1],
    };
  }
  // 搜索查询课程列表
  async searchCourseList(searchInfo: SearchLsitDto, tokenData) {
    const page = searchInfo.page;
    const pageSize = searchInfo.pageSize;
    let res: any = await this.CourseList_SQL.createQueryBuilder('course')
      .leftJoinAndMapOne(
        'course.creator_info',
        User,
        'user',
        'course.creator = user.id',
      )
      .andWhere({ name: Like(`%${searchInfo.value}%`) })
      .andWhere({ delFlag: 0, creator: tokenData.userId })
      .andWhere(
        searchInfo.classify == 0 ? {} : { classify: searchInfo.classify },
      )
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    res = {
      total: res[1],
      data: res[0],
    };
    return res;
  }
  //  查找某个课程详细信息
  async findOne(id: number) {
    console.log(id);
    const res: any = await this.CourseList_SQL.createQueryBuilder('cl')
      .leftJoinAndMapMany(
        'cl.evalDimension',
        courseEvaluate,
        'ce',
        'ce.course_id = cl.id and ce.del_flag = 0',
      )
      .leftJoinAndMapMany(
        'cl.courseSectionContent',
        courseSectionContent,
        'cs',
        'cs.course_id = cl.id and cs.del_flag = 0',
      )
      .leftJoinAndMapMany(
        'cs.courseware',
        CourseSectionCourseware,
        'ccs',
        'ccs.course_id = cl.id and ccs.section_id = cs.id and ccs.del_flag = 0',
      )
      .leftJoinAndMapOne('ccs.info', Resource, 'res', 'ccs.fileId = res.id')
      .leftJoinAndMapMany(
        'cl.exercise',
        QuestionsForCourse,
        'qfc',
        `qfc.course_id =${id} and qfc.del_flag = 0`,
      )
      .leftJoinAndMapOne('qfc.info', Question, 'q', 'qfc.question_id = q.id')
      .where({
        id,
        delFlag: 0,
      })
      .getOne();
    return res;
  }
  // 批量删除课程信息
  async batchDeleteCourse(data: DeleteDto) {
    const res = await this.CourseList_SQL.update(data.id, { delFlag: 1 });
    if (typeof data.id == 'number') {
      this.record_SQL.update({ courseId: data.id }, { delFlag: 0 });
    } else {
      this.record_SQL.query(
        `update course_study_record csr set del_flag=1 where csr.course_id in (${
          "'" + data.id.join("','") + "'"
        })`,
      );
    }
    return res;
  }
  async remove(id: number) {
    const res: any = await this.CourseList_SQL.update(id, { delFlag: 1 });
    this.course_section_content_SQL.update({ courseId: id }, { delFlag: 1 });
    this.course_evaluate_SQL.update({ courseId: id }, { delFlag: 1 });
    this.course_courseware_SQL.update({ courseId: id }, { delFlag: 1 });
    this.record_SQL.update({ courseId: id }, { delFlag: 1 });
    return res;
  }
  // 查询所有分类
  async getclassifyList() {
    const res = await this.Course_classify_SQL.findBy({ delFlag: 0 });
    return res;
  }
  // 新建分类
  async createclassify(classify: CreateCourseclassifyDto) {
    const res = await this.Course_classify_SQL.save(classify);
    return res;
  }
  // 编辑分类
  async updateclassify(id, classify) {
    const res = await this.Course_classify_SQL.update(id, classify);
    return res;
  }
  // 删除分类
  async deleteclassify({ id }) {
    const res = await this.Course_classify_SQL.update(id, { delFlag: 1 });
    return res;
  }
}
