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.excel.ScheduleExportExcel2;
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 java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

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

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

	@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);
	}

	@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);
	}


	@GetMapping("/schedule/preview")
	@Operation(summary = "预览赛程表", description = "预览导出数据")
	public R<List<?>> previewSchedule(@RequestParam Long competitionId,
		@RequestParam(defaultValue = "template1") String template,
		@RequestParam(required = false) Long venueId) {
		if ("template2".equals(template)) {
			return R.data(scheduleService.exportScheduleTemplate2(competitionId, venueId));
		}
		return R.data(scheduleService.exportSchedule(competitionId));
	}

	@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);
	}

	@GetMapping("/schedule2")
	@Operation(summary = "导出赛程表-模板2", description = "按场地导出比赛时间表格式的赛程安排")
	public void exportScheduleTemplate2(@RequestParam Long competitionId, @RequestParam(required = false) Long venueId,
		@RequestParam(required = false) String venueName, @RequestParam(required = false) String timeSlot, HttpServletResponse response) {
		List<ScheduleExportExcel2> list = scheduleService.exportScheduleTemplate2(competitionId, venueId);
		String fileName = "比赛时间_" + (venueName != null ? venueName : "全部场地") + "_" + DateUtil.today();
		String sheetName = (venueName != null ? venueName : "全部场地") + (timeSlot != null ? "_" + timeSlot : "");
		ExcelUtil.export(response, fileName, sheetName, list, ScheduleExportExcel2.class);
	}

	@GetMapping("/certificate/{resultId}")
	@Operation(summary = "生成证书", description = "生成获奖证书HTML页面")
	public void generateCertificate(@PathVariable Long resultId, HttpServletResponse response) throws IOException {
		CertificateVO certificate = resultService.generateCertificateData(resultId);
		Path templatePath = Path.of("src/main/resources/templates/certificate/certificate.html");
		String template = Files.readString(templatePath, StandardCharsets.UTF_8);
		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());
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(html);
	}

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

	@GetMapping("/certificate/data/{resultId}")
	@Operation(summary = "获取证书数据", description = "获取证书数据（JSON格式）")
	public R<CertificateVO> getCertificateData(@PathVariable Long resultId) {
		CertificateVO certificate = resultService.generateCertificateData(resultId);
		return R.data(certificate);
	}
}
