package com.yaoyicloud.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.yaoyicloud.config.CommonDataCache;
import com.yaoyicloud.config.RelationCounterRedisUtil;
import com.yaoyicloud.entity.ReportGenerationResult;
import com.yaoyicloud.service.CsoReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.yaoyicloud.dto.ReportDTO;


import java.io.ByteArrayOutputStream;

import static com.yaoyicloud.config.SessionInterceptor.SESSION_MAP;

/**
 * 报告控制器
 *
 * @author snows
 * @date 2024/10/14
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class CsoReportController {
    private final CsoReportService csoReportService;
    private final RelationCounterRedisUtil relationCounterRedisUtil;
    private final CommonDataCache commonDataCache;

    /**
     * 创建Plus版本审核报告
     *
     * @param resource 请求参数
     * @return {@link Boolean } 结果
     */
    @PostMapping("/report/create-word")
    public Map<String, Object>
        createPlusVersionCheckReport(@Validated @RequestBody ReportDTO.CsoReport resource,
            HttpServletRequest request) throws Exception {

        String relationId = request.getHeader("relationId");
        Boolean mergeflag = resource.getMergeflag();
        synchronized (this) {
            ReportGenerationResult plusVersionCheckReport = csoReportService.createCsoCheckReport(
                resource.getData(),
                Long.valueOf(relationId),
                resource.getModuleType(),
                mergeflag);
            String sessionId = SESSION_MAP.get(relationId);

            // 3. 构建响应
            Map<String, Object> response = new HashMap<>();
            // 根据是否是最后一个模块决定返回哪个路径
            if (mergeflag) {
                response.put("reportResult", plusVersionCheckReport.getMergedReportPath());
                commonDataCache.removeSessionData(relationId);
                relationCounterRedisUtil.delete(Long.valueOf(relationId));
            } else {
                response.put("reportResult", plusVersionCheckReport.getModulePath());

            }

            response.put("sessionId", sessionId);
            return response;
        }
    }

    /**
     * cso word转pdf
     * @param fileBytes
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/report/create-pdf", consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> handleReport(@RequestBody byte[] fileBytes)  {
        // 1. 直接获取PDF字节流
        ByteArrayOutputStream pdfStream = csoReportService.saveToTempFile(fileBytes);

        // 2. 转换为字节数组
        byte[] pdfBytes = pdfStream.toByteArray();

        // 3. 直接返回PDF字节流
        return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_PDF) // 关键：设置为PDF类型
            .header("Content-Disposition", "attachment; filename=report.pdf") // 设置下载文件名
            .body(pdfBytes);
    }
}
