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;

@RestController
@RequiredArgsConstructor
@Slf4j
public class ReportController {
    private final ReportService reportService;
    /**
     * 创建Plus版本审核报告
     *
     * @param resource 请求参数
     * @return {@link Boolean } 结果
     */
    @EasierLog("扬子江审核报告")
    @PostMapping("/report/create-report")
    public Map<String, Object>
    createPlusVersionCheckReport(@Validated @RequestBody ReportDTO.OnCreateVersionReport resource,
                                 HttpServletRequest request) throws Exception {
        byte[] fileBytes = Base64.getDecoder().decode(resource.getReportTempFile());


        synchronized (this) {
            String reportPath = reportService.createPlusVersionCheckReport(
                    resource.getReportType(),
                    resource.getData(),
                    fileBytes,
                    resource.getReportBastPath(),
                    resource.getRelationId()
            );
            HttpSession session = request.getSession();
            String relationId = String.valueOf(resource.getRelationId());
            @SuppressWarnings("unchecked")
            List<String> reportPaths = (List<String>) session.getAttribute(relationId);

            if (reportPaths == null) {
                reportPaths = new ArrayList<>();
                session.setAttribute(relationId, reportPaths);
            }
            Map<String, Object> response = new HashMap<>();
            response.put("reportResult", reportPath);
            response.put("sessionId", request.getSession().getId());
            return response;
        }
    }
}
