package org.springblade.modules.martial.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.martial.excel.AthleteExportExcel;
import org.springblade.modules.martial.excel.ResultExportExcel;
import org.springblade.modules.martial.excel.ScheduleExportExcel;
import org.springblade.modules.martial.pojo.vo.CertificateVO;
import org.springblade.modules.martial.service.IMartialAthleteService;
import org.springblade.modules.martial.service.IMartialResultService;
import org.springblade.modules.martial.service.IMartialScheduleService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 导出打印 控制器
 *
 * @author BladeX
 */
@RestController
@AllArgsConstructor
@RequestMapping("/martial/export")
@Tag(name = "导出打印管理", description = "成绩单、赛程表、证书等导出打印接口")
public class MartialExportController {

	private final IMartialResultService resultService;
	private final IMartialAthleteService athleteService;
	private final IMartialScheduleService scheduleService;

	/**
	 * Task 3.1: 导出成绩单
	 */
	@GetMapping("/results")
	@Operation(summary = "导出成绩单", description = "导出指定赛事或项目的成绩单Excel")
	public void exportResults(
		@RequestParam Long competitionId,
		@RequestParam(required = false) Long projectId,
		HttpServletResponse response
	) {
		List<ResultExportExcel> list = resultService.exportResults(competitionId, projectId);
		String fileName = "成绩单_" + DateUtil.today();
		String sheetName = projectId != null ? "项目成绩单" : "全部成绩";
		ExcelUtil.export(response, fileName, sheetName, list, ResultExportExcel.class);
	}

	/**
	 * Task 3.2: 导出运动员名单
	 */
	@GetMapping("/athletes")
	@Operation(summary = "导出运动员名单", description = "导出指定赛事的运动员名单Excel")
	public void exportAthletes(
		@RequestParam Long competitionId,
		HttpServletResponse response
	) {
		List<AthleteExportExcel> list = athleteService.exportAthletes(competitionId);
		String fileName = "运动员名单_" + DateUtil.today();
		ExcelUtil.export(response, fileName, "运动员名单", list, AthleteExportExcel.class);
	}

	/**
	 * Task 3.3: 导出赛程表
	 */
	@GetMapping("/schedule")
	@Operation(summary = "导出赛程表", description = "导出指定赛事的赛程安排Excel")
	public void exportSchedule(
		@RequestParam Long competitionId,
		HttpServletResponse response
	) {
		List<ScheduleExportExcel> list = scheduleService.exportSchedule(competitionId);
		String fileName = "赛程表_" + DateUtil.today();
		ExcelUtil.export(response, fileName, "赛程安排", list, ScheduleExportExcel.class);
	}

	/**
	 * Task 3.4: 生成单个证书（HTML格式）
	 */
	@GetMapping("/certificate/{resultId}")
	@Operation(summary = "生成证书", description = "生成获奖证书HTML页面，可打印为PDF")
	public void generateCertificate(
		@PathVariable Long resultId,
		HttpServletResponse response
	) throws IOException {
		// 1. 获取证书数据
		CertificateVO certificate = resultService.generateCertificateData(resultId);

		// 2. 读取HTML模板
		Path templatePath = Path.of("src/main/resources/templates/certificate/certificate.html");
		String template = Files.readString(templatePath, StandardCharsets.UTF_8);

		// 3. 替换模板变量
		String html = template
			.replace("${playerName}", certificate.getPlayerName())
			.replace("${competitionName}", certificate.getCompetitionName())
			.replace("${projectName}", certificate.getProjectName())
			.replace("${medalName}", certificate.getMedalName())
			.replace("${medalClass}", certificate.getMedalClass())
			.replace("${organization}", certificate.getOrganization())
			.replace("${issueDate}", certificate.getIssueDate());

		// 4. 返回HTML
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(html);
	}

	/**
	 * Task 3.4: 批量生成证书数据
	 */
	@GetMapping("/certificates/batch")
	@Operation(summary = "批量生成证书数据", description = "批量获取项目获奖选手的证书数据")
	public R<List<CertificateVO>> batchGenerateCertificates(@RequestParam Long projectId) {
		List<CertificateVO> certificates = resultService.batchGenerateCertificates(projectId);
		return R.data(certificates);
	}

	/**
	 * Task 3.4: 获取单个证书数据（JSON格式）
	 */
	@GetMapping("/certificate/data/{resultId}")
	@Operation(summary = "获取证书数据", description = "获取证书数据（JSON格式），供前端渲染")
	public R<CertificateVO> getCertificateData(@PathVariable Long resultId) {
		CertificateVO certificate = resultService.generateCertificateData(resultId);
		return R.data(certificate);
	}

}
