package org.example.mybatisplus.Controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.example.mybatisplus.model.auto.CmsEnterpriseRiskQxbInfoBO;
import org.example.mybatisplus.module.BasicInfo;
import org.example.mybatisplus.tools.WordPoiExporter;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

@ApiOperation("控制类")
@RestController
public class IndexController {

    //只要接口中，返回值存在实体类,就会被扫描到swagger中
    @GetMapping("/export")
    public ResponseEntity<Resource> export(@ApiParam("param")String param /* todo: 参数：服务商ID，报告类型*/){

        String wordFilePath = System.getProperty("user.dir")+File.separator+ "jijinhui.docx";
        String wordExportpath = System.getProperty("user.dir")+File.separator+ "jijinhui1.docx";
        String pdfFilePath =System.getProperty("user.dir")+File.separator+  "download.pdf";

        // todo:
        // 1. getWordTemplate for BasicInfo
        // 2. retrieve data
        //    2.1 get CmsEnterpriseRiskQxbInfoBO
        CmsEnterpriseRiskQxbInfoBO cmsEnterpriseRiskQxbInfoBO = org.example.mybatisplus.model.auto.CmsEnterpriseRiskQxbInfoBO.builder().build(); // mock
        // 3. fill BasicInfo
        BasicInfo basicInfo = new BasicInfo();
        cmsEnterpriseRiskQxbInfoBO.fillBasicInfoVO(basicInfo);
        // 4. render WordTemplate with BasicInfo

        // ...

        // 最后把所有片段合成一个完整报告


        try {
            JSONObject jsonObject = new JSONObject();
            // 生成Word文档
            WordPoiExporter.init(wordFilePath,wordExportpath,jsonObject);
            // 将Word文档转换为PDF
//            WordPoiExporter.convertWordToPdf(wordExportpath, pdfFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        File file = new File(wordExportpath);
        Resource resource = new FileSystemResource(file);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_PDF)
                .body(resource);
    }


}
