import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
import { Repository } from 'typeorm';
import { EvaluationIndicator } from '../entities/evaluation-indicator.entity';
import { Evaluation } from '../entities/evaluation.entity';
import { StudentEvaluation } from '../entities/student-evaluation.entity';

@Injectable()
export class EvaluationService {
  constructor(
    @InjectRepository(Evaluation)
    private evaluationRepository: Repository<Evaluation>,

    @InjectRepository(StudentEvaluation)
    private studentEvealuation: Repository<StudentEvaluation>,
  ) {}

  async findAllTakeCharge(token) {
    const sql = `SELECT
    se.evaluation evaluation,
    se.update_time,
    u.id studentId,
    u.name,
    u.username account,
    org.name orgName,
    org.id orgId,
    se.id
  FROM
    teacher_student ts
    LEFT JOIN user u  ON ts.student = u.id
    LEFT JOIN student_evaluation se ON se.student_id = u.id 
    LEFT JOIN org on u.org_id = org.id
  WHERE
    ts.teacher = '${token.userId}' and
    (se.id in (select max(se.id) id from student_evaluation se group by se.student_id) or se.id is null)
    `;

    return await this.evaluationRepository.query(sql);
  }
  async create(data) {
    const res = await this.studentEvealuation.save(data);
    return res;
  }
  async findMyEavluation(token: TokenDataEntity) {
    return await this.studentEvealuation.findOneBy({
      studentId: token.userId,
      delFlag: 0,
    });
  }
}
