package com.yaoyicloud.controller;

import com.yaoyicloud.annotation.EasierLog;
import com.yaoyicloud.config.CommonDataCache;
import com.yaoyicloud.config.RelationCounterRedisUtil;
import com.yaoyicloud.dto.ReportDTO;
import com.yaoyicloud.entity.ReportGenerationResult;
import com.yaoyicloud.service.ReportUpdateService;
import com.yaoyicloud.tools.DocxUtil;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;

import java.util.Map;

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

/**
 * 报告控制器
 *
 * @author snows
 * @date 2024/10/14
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class ReportUpdateController {
    private final ReportUpdateService reportService;
    private final RelationCounterRedisUtil relationCounterRedisUtil;
    private final CommonDataCache commonDataCache;
    private final DocxUtil docxUtil;

    /**
     * 创建Plus版本审核报告
     *
     * @param resource 请求参数
     * @return {@link Boolean } 结果
     */
    @EasierLog("创建Plus版本审核报告")
    @PostMapping("/report/create-report-new")
    public Map<String, Object> createPlusVersionCheckReport(
        @Validated @RequestBody ReportDTO.OnCreatePlusVersionReport resource,
        HttpServletRequest request) throws Exception {
        // 1. 解码文件并生成报告
        String relationId = request.getHeader("relationId");

        ReportGenerationResult plusVersionCheckReport = reportService.createPlusVersionCheckReport(
            resource.getData(),
            Long.valueOf(relationId),
            resource.getModuleType());
        String sessionId = SESSION_MAP.get(relationId);
        // 3. 构建响应
        Map<String, Object> response = new HashMap<>();
        // 根据是否是最后一个模块决定返回哪个路径
        if (plusVersionCheckReport.isLastModule() && plusVersionCheckReport.getMergedReportPath() != null) {
            // word 转pdf
            commonDataCache.removeSessionData(relationId);
            relationCounterRedisUtil.delete(Long.valueOf(relationId));
            SESSION_MAP.remove(relationId.toString());
            String pdfDocumentPath = docxUtil.wordToPdf(plusVersionCheckReport.getMergedReportPath());
            response.put("reportResult", pdfDocumentPath);
            response.put("isFinalReport", true);

        } else {
            response.put("reportResult", plusVersionCheckReport.getModulePath());
            response.put("isFinalReport", false);
        }

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