package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reading.platform.entity.*;
import com.reading.platform.mapper.*;
import com.reading.platform.service.ExportService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 导出服务实现类
 */
@Service
@RequiredArgsConstructor
public class ExportServiceImpl implements ExportService {

    private final TeacherMapper teacherMapper;
    private final StudentMapper studentMapper;
    private final LessonMapper lessonMapper;
    private final GrowthRecordMapper growthRecordMapper;

    @Override
    public byte[] exportTeachers(String tenantId) throws IOException {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getTenantId, tenantId);
        List<Teacher> teachers = teacherMapper.selectList(wrapper);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Teachers");
            String[] headers = {"ID", "Name", "Username", "Phone", "Email", "Gender", "Status"};
            createHeaderRow(sheet, headers);

            int rowNum = 1;
            for (Teacher t : teachers) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(t.getId());
                row.createCell(1).setCellValue(t.getName() != null ? t.getName() : "");
                row.createCell(2).setCellValue(t.getUsername() != null ? t.getUsername() : "");
                row.createCell(3).setCellValue(t.getPhone() != null ? t.getPhone() : "");
                row.createCell(4).setCellValue(t.getEmail() != null ? t.getEmail() : "");
                row.createCell(5).setCellValue(t.getGender() != null ? t.getGender() : "");
                row.createCell(6).setCellValue(t.getStatus() != null ? t.getStatus() : "");
            }
            return toBytes(workbook);
        }
    }

    @Override
    public byte[] exportStudents(String tenantId) throws IOException {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getTenantId, tenantId);
        List<Student> students = studentMapper.selectList(wrapper);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Students");
            String[] headers = {"ID", "Name", "Gender", "Birth Date", "Grade", "Student No", "Status"};
            createHeaderRow(sheet, headers);

            int rowNum = 1;
            for (Student s : students) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(s.getId());
                row.createCell(1).setCellValue(s.getName() != null ? s.getName() : "");
                row.createCell(2).setCellValue(s.getGender() != null ? s.getGender() : "");
                row.createCell(3).setCellValue(s.getBirthDate() != null ? s.getBirthDate().toString() : "");
                row.createCell(4).setCellValue(s.getGrade() != null ? s.getGrade() : "");
                row.createCell(5).setCellValue(s.getStudentNo() != null ? s.getStudentNo() : "");
                row.createCell(6).setCellValue(s.getStatus() != null ? s.getStatus() : "");
            }
            return toBytes(workbook);
        }
    }

    @Override
    public byte[] exportLessons(String tenantId) throws IOException {
        LambdaQueryWrapper<Lesson> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Lesson::getTenantId, tenantId);
        List<Lesson> lessons = lessonMapper.selectList(wrapper);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Lessons");
            String[] headers = {"ID", "Title", "Lesson Date", "Start Time", "End Time", "Location", "Status"};
            createHeaderRow(sheet, headers);

            int rowNum = 1;
            for (Lesson l : lessons) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(l.getId());
                row.createCell(1).setCellValue(l.getTitle() != null ? l.getTitle() : "");
                row.createCell(2).setCellValue(l.getLessonDate() != null ? l.getLessonDate().toString() : "");
                row.createCell(3).setCellValue(l.getStartTime() != null ? l.getStartTime().toString() : "");
                row.createCell(4).setCellValue(l.getEndTime() != null ? l.getEndTime().toString() : "");
                row.createCell(5).setCellValue(l.getLocation() != null ? l.getLocation() : "");
                row.createCell(6).setCellValue(l.getStatus() != null ? l.getStatus() : "");
            }
            return toBytes(workbook);
        }
    }

    @Override
    public byte[] exportGrowthRecords(String tenantId) throws IOException {
        LambdaQueryWrapper<GrowthRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GrowthRecord::getTenantId, tenantId);
        List<GrowthRecord> records = growthRecordMapper.selectList(wrapper);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Growth Records");
            String[] headers = {"ID", "Student ID", "Type", "Title", "Content", "Record Date"};
            createHeaderRow(sheet, headers);

            int rowNum = 1;
            for (GrowthRecord g : records) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(g.getId());
                row.createCell(1).setCellValue(g.getStudentId());
                row.createCell(2).setCellValue(g.getType() != null ? g.getType() : "");
                row.createCell(3).setCellValue(g.getTitle() != null ? g.getTitle() : "");
                row.createCell(4).setCellValue(g.getContent() != null ? g.getContent() : "");
                row.createCell(5).setCellValue(g.getRecordDate() != null ? g.getRecordDate().toString() : "");
            }
            return toBytes(workbook);
        }
    }

    /**
     * 创建表头行
     */
    private void createHeaderRow(Sheet sheet, String[] headers) {
        Row headerRow = sheet.createRow(0);
        CellStyle style = sheet.getWorkbook().createCellStyle();
        Font font = sheet.getWorkbook().createFont();
        font.setBold(true);
        style.setFont(font);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(style);
        }
    }

    /**
     * 将 Workbook 转换为字节数组
     */
    private byte[] toBytes(Workbook workbook) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        return out.toByteArray();
    }
}
