package com.hotwj.platform.securityManagement.trainingParticipant.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.hotwj.platform.reportStatistics.integration.GotenbergClient;
import com.hotwj.platform.reportStatistics.template.VelocityTemplateRenderer;
import com.hotwj.platform.securityManagement.training.domain.vo.HotTrainingVo;
import com.hotwj.platform.securityManagement.training.service.IHotTrainingService;
import com.hotwj.platform.securityManagement.trainingParticipant.domain.bo.HotTrainingParticipantBo;
import com.hotwj.platform.securityManagement.trainingParticipant.domain.vo.HotTrainingParticipantVo;
import com.hotwj.platform.securityManagement.trainingParticipant.service.IHotTrainingParticipantPrintService;
import com.hotwj.platform.securityManagement.trainingParticipant.service.IHotTrainingParticipantService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 培训参与人员打印服务实现
 *
 * @author shihongwei
 * @date 2026-03-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class HotTrainingParticipantPrintServiceImpl implements IHotTrainingParticipantPrintService {

    private final IHotTrainingParticipantService trainingParticipantService;
    private final IHotTrainingService trainingService;
    private final OssService ossService;
    private final GotenbergClient gotenbergClient;
    private final VelocityTemplateRenderer velocityTemplateRenderer;

    @Value("${dromara.app.name:HOT交通安全管理清单平台}")
    private String appName;

    @Override
    public void exportPdf(HotTrainingParticipantBo bo, HttpServletResponse response) {
        // 1. Query Data
        List<HotTrainingParticipantVo> list = trainingParticipantService.queryList(bo);
        if (CollUtil.isEmpty(list)) {
            throw new ServiceException("数据不存在");
        }

        // 2. Query Training Info for isMakeUp
        Long isMakeUp = 0L;
        if (bo.getTrainingId() != null) {
            HotTrainingVo training = trainingService.queryById(bo.getTrainingId());
            if (training != null) {
                isMakeUp = training.getIsMakeUp();
            }
        }

        // 3. Process Data for Template
        List<Map<String, Object>> printList = new ArrayList<>();
        for (HotTrainingParticipantVo vo : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", vo.getUserName());
            map.put("phone", vo.getPhone());

            String personTypeStr = "未知";
            if (vo.getPersonType() != null) {
                if (vo.getPersonType() == 1L) personTypeStr = "驾驶员";
                else if (vo.getPersonType() == 2L) personTypeStr = "管理员";
            }
            map.put("personTypeStr", personTypeStr);

            map.put("completeTime", vo.getCompleteTime() != null ? DateUtil.formatDateTime(vo.getCompleteTime()) : "");

            // Signature Image
            String signatureUrl = "";
            if (vo.getSignatureOssId() != null) {
                signatureUrl = resolveMaybeOssUrl(String.valueOf(vo.getSignatureOssId()));
            }
            map.put("signatureUrl", signatureUrl);

            map.put("isMakeUpStr", isMakeUp != null && isMakeUp == 1L ? "是" : "否");
            map.put("isCompletedStr", (vo.getIsCompleted() != null && vo.getIsCompleted() == 1L) ? "已完成" : "未完成");

            printList.add(map);
        }

        // 4. Generate PDF
        VelocityContext context = new VelocityContext();
        context.put("list", printList);
        context.put("appName", appName);
        context.put("printTime", DateUtil.now());

        String bodyHtml = velocityTemplateRenderer.render("templates/securityManage/trainingAssessmentDetail.html.vm", context);

        // Merge into layout (Portrait A4) - Assuming printLayout.html.vm is for portrait
        // If table is wide, use printLayoutLandscape.html.vm
        // The columns are: Name, Phone, Type, Time, Sign, MakeUp, Completed. 7 columns. Portrait might be tight but ok.
        // Let's use Landscape to be safe if signatures are wide.
        // Actually, let's use Portrait first, similar to frontend manual implementation.
        // Wait, manual implementation used A4.

        VelocityContext layoutContext = new VelocityContext();
        layoutContext.put("title", "考核明细表");
        List<String> bodies = new ArrayList<>();
        bodies.add(bodyHtml);
        layoutContext.put("bodies", bodies);

        String finalHtml = velocityTemplateRenderer.render("templates/layout/printLayout.html.vm", layoutContext);

        try {
            byte[] pdfBytes = gotenbergClient.convertHtmlToPdf(finalHtml);

            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"training-assessment-detail.pdf\"");
            response.getOutputStream().write(pdfBytes);
        } catch (Exception e) {
            log.error("Export PDF failed", e);
            throw new ServiceException("导出PDF失败");
        }
    }

    private String resolveMaybeOssUrl(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        String first = value.split(",")[0].trim();
        if (StringUtils.isBlank(first)) {
            return null;
        }
        if (StringUtils.ishttp(first)) {
            return first;
        }
        if (first.matches("^\\d+$")) {
            String urls = ossService.selectUrlByIds(first);
            if (StringUtils.isBlank(urls)) {
                return null;
            }
            return urls.split(",")[0].trim();
        }
        return first;
    }
}
