package com.yunyan.business.document.templateEpStrategy;


import cn.hutool.json.JSONUtil;
import com.yunyan.business.constant.TemplateEpType;
import com.yunyan.business.document.Word2PdfUtils;
import com.yunyan.business.document.WordGeneratorUtils;
import com.yunyan.business.document.utils.FileDataUtil;
import com.yunyan.business.document.y22.pojo.finalExcelY22.FinalP1Vo;
import com.yunyan.business.document.y22.pojo.finalExcelY22.FinalP4T1TermVo;
import com.yunyan.business.document.y23.budget.pojo.budgetY23.BudgetDataVo;
import com.yunyan.business.domain.FinalData;
import com.yunyan.business.domain.ReportExplain;
import com.yunyan.business.domain.ReportFile;
import com.yunyan.business.pojo.admin.vo.FinalDataDownloadFileItemVo;
import com.yunyan.business.pojo.admin.vo.FinalDataDownloadFileVo;
import com.yunyan.business.service.*;
import com.yunyan.common.config.YunYanConfig;
import com.yunyan.common.core.domain.entity.SysDept;
import com.yunyan.common.exception.ServiceException;
import com.yunyan.common.utils.StringUtils;
import com.yunyan.common.utils.file.FileUploadUtils;
import com.yunyan.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TplStrategyY2024BT1Service {

    @Autowired
    private IReportTermService reportTermService;

    @Autowired
    private IReportDeptService reportDeptService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IReportFileService reportFileService;

    @Autowired
    private IReportExplainService reportExplainService;

    public void exportSave(IFinalDataService finalDataService, Long id, String templatePath) {
        FinalData finalData = finalDataService.getById(id);

        ReportExplain reportExplain = reportExplainService.getReportExplainByReportId(id);
        if(null == reportExplain) {
            throw new ServiceException("还未有读取的报告数据");
        }
        BudgetDataVo dataVo = JSONUtil.toBean(reportExplain.getJsonContent(), BudgetDataVo.class);

        SysDept sysDept = sysDeptService.getById(finalData.getDeptId());
        if(null != sysDept) {
            //设置 名词解释
            List<FinalP4T1TermVo> termVoList = reportTermService.getTermInfo(sysDept.getArea(), finalData.getYear(), finalData.getType());
            dataVo.setTermList(termVoList);
        }

        //设置部门的 由详情中的部门来保存
        FinalP1Vo finalP1Vo = reportDeptService.getDeptInfo(finalData.getDeptId(), finalData.getYear(), finalData.getType());
        dataVo.setP1Vo(finalP1Vo);



        // 上传文件路径
        String localOfficePath = YunYanConfig.getOfficePath();
        String localPath = YunYanConfig.getProfile();
        String targetWordFileName = "";
        String targetPdf = "";

        //文件名
        String deptName = dataVo.getDeptName();
        String deptCode = dataVo.getDeptCode();
        String year = dataVo.getYear();
        String fileName = String.format("%s_%s_%s", deptCode, deptName, id);

        String wordFileName = FileUploadUtils.extractFilename(fileName, "docx");
        String pdfFileName = FileUploadUtils.extractFilename(fileName, "pdf");

        //全路径
        try {
            targetWordFileName = FileUploadUtils.getAbsoluteFile(localOfficePath, wordFileName).getAbsolutePath();
            targetPdf = FileUploadUtils.getAbsoluteFile(localOfficePath, pdfFileName).getAbsolutePath();
        } catch (IOException e) {
            log.error("创建office目录文件异常, {}, {}", e.getMessage(), e);
        }

        //生成word预览
        WordGeneratorUtils.generatorWord(dataVo, targetWordFileName, templatePath);
        //word 转 pdf 预览
        Word2PdfUtils.word2pdf(targetWordFileName, targetPdf);

        String wordPathFileName = "";
        String pdfPathFileName = "";
        //直接取 导入的  excel文件 是否需要复制到其他地方保存
        String excelPathFileName = finalData.getExcelUrl();

        //线上的路径读取
        try {
            wordPathFileName = FileUploadUtils.getPathFileName(localOfficePath, wordFileName);
            pdfPathFileName = FileUploadUtils.getPathFileName(localOfficePath, pdfFileName);
        } catch (IOException e) {
            log.error("获取office目录文件异常, {}, {}", e.getMessage(), e);
        }

        //设置保存 文件的url
        FinalDataDownloadFileVo fileVo = new FinalDataDownloadFileVo();
        List<FinalDataDownloadFileItemVo> fileContentlist = new ArrayList<>();
        fileVo.setList(fileContentlist);

        //获取部门
        if(StringUtils.isNotBlank(dataVo.getDeptName())) {
            fileVo.setDeptName(dataVo.getDeptName());
        }
        if(StringUtils.isNotBlank(dataVo.getDeptCode())) {
            fileVo.setDeptCode(dataVo.getDeptCode());
        }
        fileVo.setGenerateTime(new Date());

        //1.word生成
        FinalDataDownloadFileItemVo item1Vo = new FinalDataDownloadFileItemVo();
        item1Vo.setName(fileName);
        item1Vo.setUrl(wordPathFileName);
        item1Vo.setFileExtension("docx");
        item1Vo.setType(1);
        fileContentlist.add(item1Vo);

        //2.报告的附件
        ReportFile reportFile = reportFileService.getByReportId(id);
        if(null != reportFile && StringUtils.isNotBlank(reportFile.getFileUrl()) ) {
            FinalDataDownloadFileItemVo item3Vo = new FinalDataDownloadFileItemVo();
            item3Vo.setName(reportFile.getFileName().substring(0, reportFile.getFileName().lastIndexOf(".")));
            item3Vo.setUrl(reportFile.getFileUrl());
            if(StringUtils.isNotBlank(reportFile.getFileName())) {
                item3Vo.setFileExtension(reportFile.getFileName().substring(reportFile.getFileName().lastIndexOf(".") + 1));
            }
            item3Vo.setType(4);
            fileContentlist.add(item3Vo);
        }

        String jsonFileContent = JSONUtil.toJsonStr(fileVo);

        //记录之前的旧文件路径, 判断是否存在, 存在就删除
        FileDataUtil.deleteUrlFile(localPath, finalData.getJsonFileContent(), finalData.getPdfUrl(), new ArrayList<>(Arrays.asList(1)));

        //更新 保存 pdf状态数据
        FinalData updateEntity = new FinalData();
        updateEntity.setId(finalData.getId());
        //预览的 TODO 待生成
        //updateEntity.setPdfUrl(pdfPathFileName);
        updateEntity.setPdfUrl(pdfPathFileName);
        updateEntity.setGenerateTime(new Date());
        //updateEntity.setGenerateBy(SecurityUtils.getUsername());
        updateEntity.setGenerateStatus(1);
        updateEntity.setJsonFileContent(jsonFileContent);
        finalDataService.updateById(updateEntity);

    }


}
