package com.loan.system.utils;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.util.PoitlIOUtils;
import com.loan.system.config.FileUploadConfig;
import com.loan.system.domain.entity.Contract;
import com.loan.system.domain.pojo.ContractInformation;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;

/**
 * @author : EdwinXu
 * @date : Created in 2021/1/26 16:15
 */
public class PoiWordUtil {
    @Autowired
    private FileUploadConfig config;
    public  void writeApprove(HttpServletResponse response, String path, ContractInformation contract, String downloadName){
       // final String cacheFilePath = config.getUploadDir() + "file_store"+File.separator + downloadName + ".docx";

        File file = new File(path);
        System.out.println(file.getAbsolutePath());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        // 检查缓存文件若存在且仅查看
//        if ( new File(cacheFilePath).exists() ) {
//            try (FileInputStream fis = new FileInputStream(cacheFilePath);
//                 BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
//                byte[] buffer = new byte[1024];
//                int bytesRead;
//                while ((bytesRead = fis.read(buffer)) != -1) {
//                    bos.write(buffer, 0, bytesRead);
//                }
//                bos.flush();
//                return; // 如果找到缓存文件则直接返回
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

        // 假设签名图片路径是 contract.getSignatureImagePath()
        final String signaturePath = config.getUploadDir()+ "file_store"+File.separator +"sign.png";

        // 构造图片数据（支持本地路径、URL、byte[]）
        final PictureRenderData signaturePicture;
        if (signaturePath != null && !signaturePath.isEmpty()) {
            signaturePicture = new PictureRenderData(100, 50, signaturePath); // 宽200，高100
        }else
            signaturePicture = null;

        XWPFTemplate template = XWPFTemplate.compile(file).render(
                new HashMap<String, Object>(){{
                    put("contractNo",contract.getContractNo());
                    put("customerName",contract.getName());
                    put("customerIdNumber",contract.getIdNumber());
                    put("contractType",contract.getContractType());
                    put("contractUsage",contract.getContractUsage());
                    put("contractAmount",contract.getContractAmount());
                    put("contractPeriod",contract.getContractPeriod());

                    put("leastDay",contract.getLeastDay());
                    put("bankName",contract.getBankName());
                    put("bankAccount",contract.getBankAccount());
                    put("interestRate",contract.getInterestRate());
                    put("serviceCost",contract.getServiceCost());
                    put("collateralAddress",contract.getAddress());
                    put("numberAndArea",contract.getCollateralNumber()+" "+contract.getCollateralArea());
                    put("pages1",contract.getPages1());
                    put("pages2",contract.getPages2());

                    put("signature1",signaturePicture);
                    put("signature2",signaturePicture);
                    put("contactAddress1",contract.getContactAddress1());
                    put("contactAddress2",contract.getContactAddress2());
                    put("customerMobile",contract.getMobile());
                    put("userMobile",contract.getUserMobile());
                    put("signLocation1",contract.getSignLocation1());
                    put("signLocation2",contract.getSignLocation2());
                }});

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename=\""+downloadName+".docx"+"\"");
            OutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
//            // 设置响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
//            response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadName + ".docx\"");
//
//            // 将模板写入输出流
//            template.write(bos);
//            bos.flush();
//
//            // 同时将生成的文档保存到缓存路径
//            FileOutputStream fos = new FileOutputStream(cacheFilePath);
//            template.write(fos);
//            fos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            PoitlIOUtils.closeQuietlyMulti(template);
//        }

    }



}
