import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { OnlineIssues } from '../entities/online-issues/online-issues.entity';
import { OnlineIssuesAnswer } from '../entities/online-issues/online-answer.entity';
import { CourseNotes } from '../entities/course-notes/course-notes.entity';
import { PageInfoEntity } from 'src/common/entities/page-info.entity';
import { PaginationDTO } from '../common/pagination.dto';
import { AnswerDto } from '../dto/online-issues/online-answer.dto';
import {
  createIssuesDto,
  updateIssuesDto,
} from '../dto/online-issues/online-issues.dto';
import { User } from 'src/system/entities/user.entity';
import { TeacherStudent } from 'src/system/entities/teacher-student.entity';
export class OnlineIssuesService {
  constructor(
    // 问题列表
    @InjectRepository(OnlineIssues)
    private OnlineIssues_Sql: Repository<OnlineIssues>,
    // 回答列表
    @InjectRepository(OnlineIssuesAnswer)
    private OnlineIssuesAnswer_Sql: Repository<OnlineIssuesAnswer>,
    // 老师学员关系表
    @InjectRepository(TeacherStudent)
    private TeacherStudent_Sql: Repository<TeacherStudent>,
    // 用户表
    @InjectRepository(User)
    private user_Sql: Repository<User>,
  ) {}
  // 查询我的问题
  async findMyIssues(pageInfo: PaginationDTO, tokenInfo) {
    const page = pageInfo.page;
    const pageSize = pageInfo.pageSize;
    const res = await this.OnlineIssues_Sql.query(
      `select oi.id as id,
      oi.title as title,
      oi.content as content,
      oi.status as status,
      oi.explain as \`explain\`,
      DATE_FORMAT(oi.create_time,'%Y/%m/%d') as create_time, 
      uname.aname as answer_person_name from online_issues oi
      left join (
        select oia.issues_id as id,GROUP_CONCAT(u.name) as aname 
        from online_issues_answer oia 
        left join user u on u.id = oia.answer_person_id 
        WHERE oia.del_flag = 0
        group by oia.issues_id
      ) 
      uname on uname.id = oi.id
       where oi.del_flag=0 and oi.creator=? order by oi.id desc limit ?,?
      `,
      [tokenInfo.userId, +(page - 1) * pageSize, +pageSize],
    );
    return res;
    // return { data: res[0], total: res[1] };
  }
  // 查找某个问题
  async findMyIssuesOne(id, tokenInfo) {
    console.log(id);
    const res = await this.OnlineIssues_Sql.createQueryBuilder('issues')
      .leftJoinAndMapMany(
        'issues.answer',
        OnlineIssuesAnswer,
        'answer',
        [`answer.issues_id = issues.id`, `answer.del_flag = 0`].join(' AND '),
      )
      .leftJoinAndMapOne(
        'answer.answer_person',
        User,
        'user',
        'user.id = answer.answer_person_id',
      )
      .leftJoinAndMapOne(
        'issues.teacher',
        TeacherStudent,
        'teacher',
        'teacher.student = issues.creator',
      )
      .where({
        id,
        creator: tokenInfo.userId,
        delFlag: 0,
      })
      .getOne();
    return res;
  }
  // 查询我的回答
  async findMyAnswer(pageInfo: PaginationDTO, tokenInfo) {
    const page = pageInfo.page;
    const pageSize = pageInfo.pageSize;
    const res = await this.OnlineIssuesAnswer_Sql.query(
      `SELECT
    DATE_FORMAT(online_issues.create_time,'%Y/%m/%d') AS issuesCreateTime, 
    online_issues.creator, 
    ux.\`name\` AS creatorName, 
    online_issues.id AS issuesId, 
    online_issues.title, 
    online_issues.content, 
    online_issues.\`explain\`, 
    DATE_FORMAT(online_issues_answer.update_time,'%Y/%m/%d') AS answerTime, 
    online_issues_answer.status, 
    online_issues_answer.id,
    online_issues_answer.content AS answerContent, 
    online_issues_answer.id AS answerid, 
    online_issues_answer.answer_person_id, 
    \`user\`.\`name\` AS answerName
  FROM
    online_issues
    INNER JOIN
    online_issues_answer
    ON 
      online_issues.id = online_issues_answer.issues_id
    INNER JOIN
    \`user\`
    ON 
      \`user\`.id = online_issues_answer.answer_person_id
    LEFT JOIN
    \`user\` AS ux
    ON 
      ux.id = online_issues.creator
  WHERE
  online_issues_answer.answer_person_id = ? AND online_issues.del_flag = 0
  ORDER BY
    online_issues_answer.update_time DESC
  LIMIT ?, ?`,
      [tokenInfo.userId, +(page - 1) * pageSize, +pageSize],
    );
    return res;
  }
  // 新建问题
  async createIssues(data: createIssuesDto, tokenInfo) {
    data.creator = tokenInfo.userId;
    data.updater = tokenInfo.userId;
    const res: any = await this.OnlineIssues_Sql.save(data);
    const answerList = data.answerPersonIds.map((id) => {
      return {
        answerPersonId: id,
        issuesId: res.id,
        content: '',
        creator: tokenInfo.userId,
        updater: tokenInfo.userId,
      };
    });
    await this.OnlineIssuesAnswer_Sql.save(answerList);
    return res;
  }
  // 编辑问题
  async editorIssues(data: updateIssuesDto, tokenInfo) {
    data.updater = tokenInfo.userId;
    // 保存更改的问题标题和内容
    const res: any = await this.OnlineIssues_Sql.save(data);
    console.log(res);

    // 查找之前创建的答案
    const answers = await this.OnlineIssuesAnswer_Sql.find({
      where: { answerPersonId: In(data.answerPersonIds), issuesId: data.id },
    });
    const needAdd = [];
    // 遍历区分 需要delflag和取消delflag的数据
    data.answerPersonIds.forEach((id) => {
      const index = answers.findIndex((ans) => {
        if (ans.answerPersonId == id) {
          return true;
        }
        return false;
      });
      if (index == -1) {
        needAdd.push({
          creator: tokenInfo.userId,
          updater: tokenInfo.userId,
          answerPersonId: id,
          issuesId: data.id,
          content: '',
        });
      } else {
        answers[index].delFlag = 0;
        needAdd.push(answers[index]);
      }
    });
    await this.OnlineIssuesAnswer_Sql.save(needAdd);
    await this.OnlineIssuesAnswer_Sql.query(
      `update online_issues_answer oia set del_flag=1 where oia.answer_person_id in (${
        "'" + data.delAnswerPersonIds.join("','") + "'"
      }) and issues_id=${data.id} and oia.del_flag=0`,
    );
    return res;
  }
  // 回答问题
  async answer({ issuesId, ...data }: AnswerDto) {
    this.OnlineIssues_Sql.update({ id: issuesId }, { status: 1 });
    const res = await this.OnlineIssuesAnswer_Sql.update(
      {
        id: data.id,
      },
      {
        status: 1,
        content: data.content,
      },
    );
    return res;
  }
  // 查询我的老师下的所有学员接口
  async findMyteacherStudent(tokenInfo) {
    const info = await this.TeacherStudent_Sql.findOneBy({
      student: tokenInfo.userId,
    });
    let idList = [];
    console.log(info);

    if (info) {
      const infoList = await this.TeacherStudent_Sql.findBy({
        teacher: info.teacher,
      });
      idList = infoList.map((info) => info.student);
    }
    const res = await this.user_Sql.find({
      where: { id: In(idList) },
    });
    return res;
  }
}
