package com.hotwj.platform.reportStatistics.controller;

import cn.dev33.satoken.spring.SpringMVCUtil;
import com.hotwj.platform.reportStatistics.domain.bo.ReportLedgerQueryBo;
import com.hotwj.platform.reportStatistics.domain.vo.*;
import com.hotwj.platform.reportStatistics.service.ILedgerReportService;
import com.hotwj.platform.reportStatistics.service.ISecurityManageFilePrintService;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.domain.bo.HotHiddenDangerPlanBo;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.domain.vo.HotHiddenDangerPlanVo;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.service.IHotHiddenDangerPlanService;
import com.hotwj.platform.securityManagement.safetyInvestment.domain.bo.HotSafetyInvestmentBo;
import com.hotwj.platform.securityManagement.safetyInvestment.domain.vo.HotSafetyInvestmentVo;
import com.hotwj.platform.securityManagement.safetyInvestment.service.IHotSafetyInvestmentService;
import com.hotwj.platform.securityManagement.serviceQualityComplaint.domain.bo.HotServiceQualityComplaintBo;
import com.hotwj.platform.securityManagement.serviceQualityComplaint.domain.vo.HotServiceQualityComplaintVo;
import com.hotwj.platform.securityManagement.serviceQualityComplaint.service.IHotServiceQualityComplaintService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.file.FileUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * 安全生产管理档案
 *
 * @author shihongwei
 * @date 2026-01-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/reportStatistics/securityManageFile")
@Tag(name = "安全生产管理档案", description = "安全生产管理档案")
public class SecurityManageFileController extends BaseController {

    private final ILedgerReportService ledgerReportService;
    private final ISecurityManageFilePrintService securityManageFilePrintService;
    private final IHotHiddenDangerPlanService hotHiddenDangerPlanService;
    private final IHotSafetyInvestmentService hotSafetyInvestmentService;
    private final IHotServiceQualityComplaintService hotServiceQualityComplaintService;

    //@SaCheckPermission("reportStatistics:preJobTraining:list")
    @GetMapping("/preJobTraining/list")
    @Operation(summary = "从业人员岗前培训考核记录-分页")
    public TableDataInfo<PreJobTrainingLedgerVo> preJobTrainingList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        return ledgerReportService.queryPreJobTraining(bo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:preJobTraining:export")
    @PostMapping("/preJobTraining/exportPdf")
    @Operation(summary = "从业人员岗前培训考核记录-PDF导出")
    public void preJobTrainingExportPdf(@Valid ReportLedgerQueryBo bo) {
        byte[] bytes = securityManageFilePrintService.generatePreJobTrainingPdf(bo);
        try {
            HttpServletResponse response = SpringMVCUtil.getResponse();
            FileUtils.setAttachmentResponseHeader(response, "从业人员岗前培训考核记录.pdf");
            response.setContentType("application/pdf");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:safetyEducation:list")
    @GetMapping("/safetyEducation/list")
    @Operation(summary = "安全生产教育培训记录-分页")
    public TableDataInfo<GovSafetyEducationTrainingVo> safetyEducationList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        return ledgerReportService.queryGovSafetyEducationTraining(bo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:safetyEducation:export")
    @PostMapping("/safetyEducation/exportPdf")
    @Operation(summary = "安全生产教育培训记录-PDF导出")
    public void safetyEducationExportPdf(@Valid ReportLedgerQueryBo bo) {
        byte[] bytes = securityManageFilePrintService.generateSafetyEducationTrainingPdf(bo);
        try {
            HttpServletResponse resp = SpringMVCUtil.getResponse();
            FileUtils.setAttachmentResponseHeader(resp, "安全生产教育培训记录.pdf");
            resp.setContentType("application/pdf");
            resp.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:violationInvestigation:list")
    @GetMapping("/violationInvestigation/list")
    @Operation(summary = "违法违章隐患排查记录-分页")
    public TableDataInfo<GovViolationInfoLedgerVo> violationInvestigationList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        return ledgerReportService.queryGovViolationInfoLedger(bo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:violationInvestigation:export")
    @PostMapping("/violationInvestigation/exportPdf")
    @Operation(summary = "违法违章隐患排查记录-PDF导出")
    public void violationInvestigationExportPdf(@Valid ReportLedgerQueryBo bo) {
        byte[] bytes = securityManageFilePrintService.generateViolationInvestigationPdf(bo);
        try {
            HttpServletResponse resp = SpringMVCUtil.getResponse();
            FileUtils.setAttachmentResponseHeader(resp, "违法违章信息排查记录.pdf");
            resp.setContentType("application/pdf");
            resp.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:violationHandling:list")
    @GetMapping("/violationHandling/list")
    @Operation(summary = "违法违章处理记录-分页")
    public TableDataInfo<GovViolationHandlingLedgerVo> violationHandlingList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        if (bo.getCompanyId() == null) {
            throw new IllegalArgumentException("CompanyId不能为空");
        }
        return ledgerReportService.queryGovViolationHandlingLedger(null, bo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:violationHandling:export")
    @PostMapping("/violationHandling/exportPdf")
    @Operation(summary = "违法违章处理记录-PDF导出")
    public void violationHandlingExportPdf(@Valid ReportLedgerQueryBo bo) {
        byte[] bytes = securityManageFilePrintService.generateViolationHandlingPdf(bo);
        try {
            HttpServletResponse resp = SpringMVCUtil.getResponse();
            FileUtils.setAttachmentResponseHeader(resp, "违法违章处理记录.pdf");
            resp.setContentType("application/pdf");
            resp.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:dynamicMonitoringViolation:list")
    @GetMapping("/dynamicMonitoringViolation/list")
    @Operation(summary = "车辆动态监控违法行为处理记录-分页")
    public TableDataInfo<GovGpsViolationLedgerVo> dynamicMonitoringViolationList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        if (bo.getCompanyId() == null) {
            throw new IllegalArgumentException("CompanyId不能为空");
        }
        return ledgerReportService.queryGovGpsViolation(null, bo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:dynamicMonitoringViolation:export")
    @PostMapping("/dynamicMonitoringViolation/exportPdf")
    @Operation(summary = "车辆动态监控违法行为处理记录-PDF导出")
    public void dynamicMonitoringViolationExportPdf(@Valid ReportLedgerQueryBo bo, HttpServletResponse response) {
        byte[] bytes = securityManageFilePrintService.generateGpsViolationPdf(bo);
        try {
            FileUtils.setAttachmentResponseHeader(response, "车辆动态监控违法行为处理记录.pdf");
            response.setContentType("application/pdf");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:safetyMeeting:list")
    @GetMapping("/safetyMeeting/list")
    @Operation(summary = "安全生产会议记录-分页")
    public TableDataInfo<SafetyProductionMeetingLedgerVo> safetyMeetingList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        if (bo.getCompanyId() == null) {
            throw new IllegalArgumentException("CompanyId不能为空");
        }
        return ledgerReportService.querySafetyProductionMeeting(bo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:safetyMeeting:export")
    @PostMapping("/safetyMeeting/exportPdf")
    @Operation(summary = "安全生产会议记录-PDF导出")
    public void safetyMeetingExportPdf(@Valid ReportLedgerQueryBo bo, HttpServletResponse response) {
        byte[] bytes = securityManageFilePrintService.generateSafetyMeetingPdf(bo);
        try {
            FileUtils.setAttachmentResponseHeader(response, "安全生产会议记录.pdf");
            response.setContentType("application/pdf");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:safetyFireHazardRectification:list")
    @GetMapping("/safetyFireHazardRectification/list")
    @Operation(summary = "安全生产（消防）隐患排查整改记录-分页")
    public TableDataInfo<HotHiddenDangerPlanVo> safetyFireHazardRectificationList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        if (bo.getCompanyId() == null) {
            throw new IllegalArgumentException("CompanyId不能为空");
        }
        HotHiddenDangerPlanBo planBo = new HotHiddenDangerPlanBo();
        planBo.setCompanyId(bo.getCompanyId());
        planBo.setPlanName(bo.getPlanName());
        planBo.setStartDate(bo.getStartDate());
        planBo.setEndDate(bo.getEndDate());
        planBo.setIsDeleted(0L);
        return hotHiddenDangerPlanService.queryPageList(planBo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:safetyFireHazardRectification:export")
    @PostMapping("/safetyFireHazardRectification/exportPdf")
    @Operation(summary = "安全生产（消防）隐患排查项-PDF导出")
    public void safetyFireHazardRectificationExportPdf(@Valid ReportLedgerQueryBo bo, HttpServletResponse response) {
        byte[] bytes = securityManageFilePrintService.generateSafetyFireHazardInspectionPdf(bo);
        try {
            FileUtils.setAttachmentResponseHeader(response, "安全生产（消防）隐患排查整改记录.pdf");
            response.setContentType("application/pdf");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:safetyProductionInput:list")
    @GetMapping("/safetyProductionInput/list")
    @Operation(summary = "安全生产投入登记本-分页")
    public TableDataInfo<HotSafetyInvestmentVo> safetyProductionInputList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        HotSafetyInvestmentBo investmentBo = new HotSafetyInvestmentBo();
        investmentBo.setCompanyId(bo.getCompanyId());
        investmentBo.setIsDeleted(0L);
        String yearStr = bo.getKeyword();
        if (org.dromara.common.core.utils.StringUtils.isNotBlank(yearStr)) {
            try {
                int year = Integer.parseInt(yearStr);
                java.util.Calendar calendar = java.util.Calendar.getInstance();
                calendar.clear();
                calendar.set(java.util.Calendar.YEAR, year);
                java.util.Date begin = calendar.getTime();
                calendar.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
                calendar.set(java.util.Calendar.DAY_OF_MONTH, 31);
                calendar.set(java.util.Calendar.HOUR_OF_DAY, 23);
                calendar.set(java.util.Calendar.MINUTE, 59);
                calendar.set(java.util.Calendar.SECOND, 59);
                java.util.Date end = calendar.getTime();
                investmentBo.getParams().put("beginInvestmentTime", begin);
                investmentBo.getParams().put("endInvestmentTime", end);
            } catch (NumberFormatException ignored) {
                // 非法年度字符串则不按年度过滤
            }
        }
        return hotSafetyInvestmentService.queryPageList(investmentBo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:safetyProductionInput:export")
    @PostMapping("/safetyProductionInput/exportPdf")
    @Operation(summary = "安全生产投入登记本-PDF导出")
    public void safetyProductionInputExportPdf(@Valid ReportLedgerQueryBo bo, HttpServletResponse response) {
        byte[] bytes = securityManageFilePrintService.generateSafetyProductionInputPdf(bo);
        try {
            FileUtils.setAttachmentResponseHeader(response, "安全生产投入登记本.pdf");
            response.setContentType("application/pdf");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }

    //@SaCheckPermission("reportStatistics:serviceQuality:list")
    @GetMapping("/serviceQuality/list")
    @Operation(summary = "服务质量记录-分页")
    public TableDataInfo<HotServiceQualityComplaintVo> serviceQualityList(@Valid ReportLedgerQueryBo bo, PageQuery pageQuery) {
        if (bo.getCompanyId() == null) {
            throw new IllegalArgumentException("CompanyId不能为空");
        }
        HotServiceQualityComplaintBo complaintBo = new HotServiceQualityComplaintBo();
        complaintBo.setCompanyId(bo.getCompanyId());
        complaintBo.setIsDeleted(0L);
        if (bo.getKeyword() != null && !bo.getKeyword().isEmpty()) {
            complaintBo.setComplaintTarget(bo.getKeyword());
        }
        if (bo.getStartDate() != null) {
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            calendar.setTime(bo.getStartDate());
            calendar.set(java.util.Calendar.HOUR_OF_DAY, 0);
            calendar.set(java.util.Calendar.MINUTE, 0);
            calendar.set(java.util.Calendar.SECOND, 0);
            calendar.set(java.util.Calendar.MILLISECOND, 0);
            java.util.Date begin = calendar.getTime();
            calendar.set(java.util.Calendar.HOUR_OF_DAY, 23);
            calendar.set(java.util.Calendar.MINUTE, 59);
            calendar.set(java.util.Calendar.SECOND, 59);
            calendar.set(java.util.Calendar.MILLISECOND, 999);
            java.util.Date end = calendar.getTime();
            complaintBo.getParams().put("beginCaseTime", begin);
            complaintBo.getParams().put("endCaseTime", end);
        }
        return hotServiceQualityComplaintService.queryPageList(complaintBo, pageQuery);
    }

    //@SaCheckPermission("reportStatistics:serviceQuality:export")
    @PostMapping("/serviceQuality/exportPdf")
    @Operation(summary = "服务质量记录-PDF导出")
    public void serviceQualityExportPdf(@Valid ReportLedgerQueryBo bo, HttpServletResponse response) {
        byte[] bytes = securityManageFilePrintService.generateServiceQualityPdf(bo);
        try {
            FileUtils.setAttachmentResponseHeader(response, "安全生产服务质量记录.pdf");
            response.setContentType("application/pdf");
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException("导出PDF异常", e);
        }
    }
}
