/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.feesapi.dzht.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.feesapi.common.dzht.CommOfficeService;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.config.FilePathBean;
import com.tofly.feesapi.dzht.entity.HtFiles;
import com.tofly.feesapi.dzht.entity.HtTemplate;
import com.tofly.feesapi.dzht.entity.dto.HtGhDto;
import com.tofly.feesapi.dzht.entity.dto.HtXhDto;
import com.tofly.feesapi.dzht.entity.dto.HtXzbgDto;
import com.tofly.feesapi.dzht.entity.vo.HtPreviewParameter;
import com.tofly.feesapi.dzht.entity.vo.HtReplaceParameter;
import com.tofly.feesapi.dzht.service.HtFilesService;
import com.tofly.feesapi.dzht.service.HtTemplateService;
import com.tofly.feesapi.file.fileconfiguration.FileStorageService;
import com.tofly.feesapi.file.service.IFileInfoService;
import com.tofly.feesapi.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.feesapi.dzht.mapper.HtFilesMapper;


import java.io.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 电子合同文件
 *
 * @author admin
 * @date Tue Nov 19 00:00:00 GMT+08:00 2024
 */
@Slf4j
@Service("htFilesService")
public class HtFilesServiceImpl extends ServiceImpl<HtFilesMapper, HtFiles> implements HtFilesService {

    @Autowired
    private FilePathBean filePathBean;
    @Autowired
    private HtTemplateService htTemplateService;
    @Autowired
    private CommOfficeService commOfficeService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IFileInfoService iFileInfoService;

    @Override
    public ResultRespone WordToPdf(HtPreviewParameter htPreviewParameter) {
        HtReplaceParameter htReplaceParameter = getHtReplaceParameter(htPreviewParameter);
        String pathStr = this.WordToPdf(htReplaceParameter);
        return ResultRespone.success(pathStr);
    }

    @Override
    public com.tofly.feesapi.file.entity.File XH_WordToPdf(HtXhDto dto) {
        //是否欠费
        int qfcount = this.baseMapper.getQfState(dto.getYhbh());
        if (qfcount > 0) {
            dto.setSfqf("欠费");
        } else {
            dto.setSfqf("不欠费");
        }
        dto.setQyrq(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
        return WordToPdfNew(dto, dto.getHtmbid());
    }

    @Override
    public com.tofly.feesapi.file.entity.File GH_WordToPdf(HtGhDto dto) {
        dto.setQyrq(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
        return WordToPdfNew(dto, dto.getHtmbid());
    }

    @Override
    public com.tofly.feesapi.file.entity.File XZBG_WordToPdf(HtXzbgDto dto) {
        dto.setCzryxm(SecurityUtils.getUser().getRealName());
        dto.setQyrq(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
        return WordToPdfNew(dto, dto.getHtmbid());
    }

    public com.tofly.feesapi.file.entity.File WordToPdfNew(Object dto, String mbid) {
        try {
            HtTemplate htTemplate = htTemplateService.getById(mbid);
            if (StringUtil.isNull(htTemplate)) {
                throw new FeesException("合同模板不存在！", FeesErrorCode.BUSINESS_ERROR);
            }
            String wordaddr = htTemplate.getMbdz();
            //替换占位符列表
            Map<String, Object> objectMap = commOfficeService.modelToMap(dto);
            //下载doc模板 下载到本地temp文件夹内
            File file = downloadWord(objectMap, wordaddr);
            // pdf文件路径
            String pdfFilePath = String.format("%s",
                    filePathBean.getTemporaryfile()
            );
            //pdf文件名
            String pdffilename = new SimpleDateFormat("HH_mm_ss_SSS").format(new Date());
            pdfFilePath = String.format("%s/%s.pdf", pdfFilePath, pdffilename);
            //转换doc到pdf  把pdf文件存入本地临时文件夹
            File pdf_temp_file = commOfficeService.docTurnPdf(file, pdfFilePath);

            //把pdf存入ftp服务器内
            //返回ftp服务器文件地址 给前端签字
            return iFileInfoService.saveFile(iFileInfoService.convertFileToMultipartFileFile(pdf_temp_file), filePathBean.getHtfile(), objectMap.get("yhbh").toString(), "ht_temp");
        } catch (Exception e) {
            log.error("WordToPdf error:{}", e.getMessage());
            throw new FeesException("Word转PDF失败！", FeesErrorCode.BUSINESS_ERROR);
        }
    }

    /**
     * 删除指定地址文件
     */
    public void DeleteFiles() {
        String pathStr = filePathBean.getTemporaryfile();
        File[] files = new File(pathStr).listFiles();
        Date thresholdDate = new Date();
        thresholdDate.setTime(thresholdDate.getTime() - 24 * 60 * 60 * 1000 * 3);
        for (File file : files) {
            Date fileDate = new Date(file.lastModified());
            if (fileDate.before(thresholdDate)) {
                file.delete();
            }
        }
    }

    private HtReplaceParameter getHtReplaceParameter(HtPreviewParameter htPreviewParameter) {
        HtReplaceParameter htReplaceParameter = this.baseMapper.getHtReplaceParameter(htPreviewParameter.getYhbh());
        if (StringUtil.isNull(htReplaceParameter)) {
            throw new FeesException("用户信息不存在！", FeesErrorCode.BUSINESS_ERROR);
        }
        BeanUtils.copyProperties(htPreviewParameter, htReplaceParameter);
        htReplaceParameter.setQyrq(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
        return htReplaceParameter;
    }

    /**
     * word转pdf
     *
     * @param htReplaceParameter 替换参数
     * @return
     */
    private String WordToPdf(HtReplaceParameter htReplaceParameter) {
        try {
            HtTemplate htTemplate = htTemplateService.getById(htReplaceParameter.getHtmbid());
            if (StringUtil.isNull(htTemplate)) {
                throw new FeesException("合同模板不存在！", FeesErrorCode.BUSINESS_ERROR);
            }
            String wordaddr = htTemplate.getMbdz();
            //读取word文档
            XWPFDocument xwpfDocument = commOfficeService.getHealthReport(wordaddr);
            // 替换文本数据map构建
            Map<String, String> map = commOfficeService.objectToMap(htReplaceParameter);
            // 替换文本与图片
            commOfficeService.paragraphTextAndImagesFilling(xwpfDocument, map);
            // word转pdf
            String pdfFilePath = String.format("%s",
                    filePathBean.getTemporaryfile()
            );
            foldersfcz(pdfFilePath);
            pdfFilePath = String.format("%s/%s.pdf", pdfFilePath, new SimpleDateFormat("HH_mm_ss_SSS").format(new Date()));


            commOfficeService.WordToPdf(xwpfDocument, pdfFilePath);
            return pdfFilePath;
        } catch (Exception e) {
            log.error("WordToPdf error:{}", e.getMessage());
            throw new FeesException("Word转PDF失败！", FeesErrorCode.BUSINESS_ERROR);
        }
    }

    private void foldersfcz(String pdfFilePath) {
        File folder = new File(pdfFilePath);
        // 检查文件夹是否存在
        if (!folder.exists()) {
            // 创建文件夹
            boolean created = folder.mkdirs();
            if (created) {
                log.info("文件夹创建成功！");
            } else {
                log.info("文件夹创建失败！");
            }
        }
    }

    public File downloadWord(Map<String, Object> paramMap, String wordurl) {
        Long time = new Date().getTime();
        String formatSuffix = ".docx";
        String fileName = time + formatSuffix;

        File tempFile = null;

        try {
            tempFile = File.createTempFile(fileName, ".docx");

//            ClassPathResource classPathResource = new ClassPathResource(path);
//            InputStream inputStream =classPathResource.getInputStream();
            InputStream inputStream = fileStorageService.getByteDataforFileInputStream(wordurl);

            // reportList和模板对应
            // 读取模板templatePath并将paramMap的内容填充进模板，即编辑模板(compile)+渲染数据(render)

            ConfigureBuilder configureBuilder = Configure.builder().useSpringEL();
            Configure config = configureBuilder.build();
            // 读取模板templatePath并将paramMap的内容填充进模板，即编辑模板(compile)+渲染数据(render)
            XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(paramMap);

            //输出路径(下载到指定路径)
            OutputStream out = new FileOutputStream(tempFile.getPath());

            template.write(out);//将template写到OutputStream中
            out.flush();
            out.close();
            template.close();
            inputStream.close();
        } catch (Exception e) {
            throw new FeesException(e.getMessage(), FeesErrorCode.BUSINESS_ERROR);
        }

        return tempFile;
    }
//    public File downloadWord(Map<String, Object> paramMap, String wordurl) {
//        File tempFile = null;
//        try {
//            // 生成唯一临时文件（系统自动处理后缀）
//            tempFile = File.createTempFile("template_", ".docx");
//
//            // 1. 获取模板输入流并校验
//            try (InputStream inputStream = fileStorageService.getByteDataforFileInputStream(wordurl)) {
//                if (inputStream == null) {
//                    throw new IllegalArgumentException("模板文件不存在或无法读取: " + wordurl);
//                }
//
//                // 2. 配置及模板编译
//                Configure config = Configure.builder().useSpringEL().build();
//                try (XWPFTemplate template = XWPFTemplate.compile(inputStream, config)) {
//                    // 3. 渲染数据
//                    template.render(paramMap);
//
//                    // 4. 写入临时文件
//                    try (OutputStream out = new FileOutputStream(tempFile)) {
//                        template.write(out);
//                    }
//                }
//            }
//            return tempFile;
//        } catch (Exception e) {
//            // 5. 异常处理：删除临时文件并抛出异常
//            if (tempFile != null && tempFile.exists()) {
//                if (!tempFile.delete()) {
//                    System.err.println("临时文件删除失败: " + tempFile.getAbsolutePath());
//                }
//            }
//            throw new FeesException("生成Word文件失败: " + e.getMessage(), FeesErrorCode.BUSINESS_ERROR);
//        }
//    }

    public boolean isFileReadOnly(String filePath) {
        return Files.isReadable(Paths.get(filePath));
    }
}
