package com.yaoyicloud.controller;


import com.yaoyicloud.annotation.EasierLog;
import com.yaoyicloud.dto.ReportDTO;
import com.yaoyicloud.service.ReportService;
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 javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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


/**
 * 报告控制器
 *
 * @author snows
 * @date 2024/10/14
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class ReportController {
    private final ReportService reportService;
    /**
     * 创建Plus版本审核报告
     *
     * @param resource 请求参数
     * @return {@link Boolean } 结果
     */
    @EasierLog("创建Plus版本审核报告")
    @PostMapping("/report/create-report")
    public Map<String, Object> createPlusVersionCheckReport(
            @Validated @RequestBody ReportDTO.OnCreatePlusVersionReport resource,
            HttpServletRequest request
    ) throws Exception {
        // 1. 解码文件并生成报告
        byte[] fileBytes = Base64.getDecoder().decode(resource.getReportTempFile());
        String relationId = request.getHeader("relationId");
        String reportPath = reportService.createPlusVersionCheckReport(
                resource.getReportType(),
                resource.getData(),
                fileBytes,
                resource.getReportBastPath(),
                Long.valueOf(relationId),
                request,
                resource.getModuleType()
        );

        HttpSession session = SESSION_MAP.get(relationId);
        // 2. 线程安全地更新 Session 中的报告路径列表
        synchronized (session) {
            List<String> reportPaths = Optional.ofNullable(
                    (List<String>) session.getAttribute(relationId)
            ).orElseGet(ArrayList::new);

            reportPaths.add(reportPath);
            session.setAttribute(relationId, reportPaths);
        }

        // 3. 返回响应
        Map<String, Object> response = new HashMap<>();
        response.put("reportResult", reportPath);
        response.put("sessionId", session.getId());
        response.put("reportResult", reportPath);
        return response;
    }
}
