package com.qingyun.web.controller.api.contract;

import com.qingyun.service.domain.ContractCompareTask;
import com.qingyun.service.domain.ContractReviewTask;
import com.qingyun.service.service.IContractCompareTaskService;
import com.qingyun.service.service.IContractReviewTaskService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;

/**
 * pdf通用接口
 */
@RestController
@RequestMapping("/api/pdf")
@SuppressWarnings("all")
@AllArgsConstructor
public class ContractPDFCommonController {

    private final IContractReviewTaskService contractReviewTaskService;

    private final IContractCompareTaskService contractCompareTaskService;

    /**
     * 根据任务id和任务类型获取pdf 文件流
     *
     * @param taskId 任务id
     * @param taskType 任务类型 1审查任务 2 比对任务-主版文件 3 比对任务-副版文件
     */
    @GetMapping("/load/{taskId}")
    public void loadPDF(@PathVariable Long taskId, @RequestParam("taskType") Integer taskType,
                        HttpServletResponse response) {
        // Return the PDF stream directly without returning a string
        String contractUrl = null;
        if (taskType == 1) {
            ContractReviewTask contractReviewTask = contractReviewTaskService.getBaseMapper().selectById(taskId);
            if (contractReviewTask == null) {
                throw new RuntimeException("任务不存在");
            }
            contractUrl = contractReviewTask.getContractUrl();
        } else if (taskType == 2) {
            // 主版pdf
            ContractCompareTask contractCompareTask = contractCompareTaskService.getBaseMapper().selectById(taskId);
            if (contractCompareTask == null) {
                throw new RuntimeException("任务不存在");
            }
            contractUrl = contractCompareTask.getFirstContractUrl();
        } else if (taskType == 3) {
            // 副版pdf
            ContractCompareTask contractCompareTask = contractCompareTaskService.getBaseMapper().selectById(taskId);
            if (contractCompareTask == null) {
                throw new RuntimeException("任务不存在");
            }
            contractUrl = contractCompareTask.getSecondContractUrl();
        } else {
            throw new RuntimeException("任务类型错误");
        }
        if (contractUrl == null) {
            throw new RuntimeException("任务不存在");
        }
        try (InputStream inputStream = new URL(contractUrl).openStream()) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline; filename=\"contract.pdf\"");
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
