import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { Exam } from 'src/assessment-evaluation/entities/entities-exam-manager/exam.entity';
import { UpdateExamDto } from 'src/assessment-evaluation/dto/dtos-exam-manager/exam/update-exam.dto';
import { PagingExamDto } from 'src/assessment-evaluation/dto/dtos-exam-manager/exam/paging-exam.dto';
import { CreateExamDto } from 'src/assessment-evaluation/dto/dtos-exam-manager/exam/create-exam.dto';
import { ExamPaper } from 'src/assessment-evaluation/entities/entities-exam-paper-manager/exam-paper.entity';
import { User } from 'src/system/entities/user.entity';
// import { ExamPaperClassify } from 'src/assessment-evaluation/entities/entities-exam-paper-manager/exam-paper-classify.entity';

@Injectable()
export class ExamService {
  constructor(
    @InjectRepository(Exam)
    private ExamRep: Repository<Exam>, // @InjectRepository(ExamPaperClassify) // private ExamPaperClassifyRep: Repository<ExamPaperClassify>,
    @InjectRepository(ExamPaper)
    private ExamPaperRep: Repository<ExamPaper>, // @InjectRepository(ExamPaperClassify) // private ExamPaperClassifyRep: Repository<ExamPaperClassify>,
  ) {}

  /* 
    创建试卷
  */
  async create(CreateExamPaperDto: CreateExamDto) {
    // const hasDifficultyLevel = await this.ExamPaperClassifyRep.findOneBy({
    //   delFlag: 0,
    //   id: createQuestionDto.difficultyLevel,
    // });
    // if (!hasDifficultyLevel) {
    //   throw '[classifyId]字段 - 类型不存在';
    // }

    return await this.ExamRep.save(CreateExamPaperDto);
  }

  /* 
    根据ID查找试卷
  */
  async findOne(id: number) {
    const examInfo = await this.ExamRep.createQueryBuilder('exam')
      .leftJoinAndMapOne(
        'exam.userinfo',
        User,
        'user',
        'user.id=exam.examinerId',
      )
      .andWhere({ id })
      .getOne();

    const paperInExam = await this.ExamPaperRep.findOneBy({
      id: examInfo.examPaperId,
    });
    return { examInfo, paperInExam };
  }
  /* 
    分页查询考试信息
  */
  async paging(pagingInfo: PagingExamDto, token: any) {
    const { currentPage, pageSize, classifyId, title } = pagingInfo;
    type PagingParamsMap = {
      delFlag: number;
      classifyId: number | null;
      title: any | null;
      type: number | null;
      difficultyLevel: number | null;
      creator: string | null;
    };

    // eslint-disable-next-line prefer-const
    let whereMap: PagingParamsMap = {
      delFlag: 0,
      classifyId: null,
      title: null,
      type: null,
      difficultyLevel: null,
      creator: null,
    };
    // console.log(pagingInfo, whereMap);
    try {
      let sql = `select
      e.id as id,
      e.title as title,
      e.classify_id as classifyId,
      e.exam_desc as examDesc,
      e.exam_duration as examDuration,
      e.exam_times as examTimes,
      e.pass_percent as passPercent,
      e.questions_is_random_sort as questionsIsRandomSort,
      e.options_is_random_sort as optionsIsRandomSort,
      e.success_tips as successTips,
      e.failed_tips as failedTips,
      e.waiting_tips as waitingTips,
      e.exam_paper_id as examPaperId,
      e.exam_mode as examMode,
      e.total_score as totalScore,
      e.grade_paper_mode as gradePaperMode,
      e.examiner_id as examinerId,
      e.join_mode as joinMode,
      e.join_password as joinPassword,
      ec.name as classify,
      ep.title as examPaperTitle,
      date_format(e.exam_start_time,'%Y-%m-%d %H:%i:%S') as examStartTime , 
      date_format(e.exam_end_time ,'%Y-%m-%d %H:%i:%S') as examEndTime , 
      (case 
         when now()>=e.exam_start_time and now()<=e.exam_end_time 
        then 1 when now()<e.exam_start_time then 0 
        when now()>e.exam_end_time then 2
      end) as status,
      u.name as creator 
    from
      exam e
    left join exam_classify ec on
      ec.id = e.classify_id
    left join exam_paper ep on ep.id=e.exam_paper_id left join user u on u.id=e.creator
    where
      e.del_flag = 0 `;
      if (classifyId) {
        sql += ` AND e.classify_id = ${classifyId}`;
        whereMap.classifyId = classifyId;
      }
      if (title) {
        sql += ` AND e.title LIKE '%${title}%'`;
        whereMap.title = Like(`%${title}%`);
      }
      if (token?.userId && token?.roleId !== 1) {
        sql += ` AND e.creator ='${token.userId}'`;
        whereMap.creator = token.userId;
      }
      sql += `
    order by
    e.id desc limit ?,?`;
      const getPagingQuestions = await this.ExamRep.query(sql, [
        +(currentPage - 1) * pageSize,
        +pageSize,
      ]);
      // console.log(sql);
      const total = await this.ExamRep.countBy(whereMap);
      return { total, currentPage, pageSize, data: getPagingQuestions };
    } catch (err) {
      throw '分页查询失败，错误详情：' + err;
    }
  }

  /* 
    更新某个考试
  */
  async update(id: number, UpdateExamPaperDto: UpdateExamDto) {
    return this.ExamRep.update(id, UpdateExamPaperDto);
  }

  /* 
    更新是否匿名
  */
  async updateIsAnonymous(id: number, isAnonymous: number) {
    return this.ExamRep.update(id, { isAnonymous: isAnonymous });
  }

  /* 
    删除某个考试
  */
  async remove(id: number) {
    await this.ExamRep.update(id, { delFlag: 1 });
    return true;
  }
}
