package org.jeecg.modules.database.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.database.entity.*;
import org.jeecg.modules.database.mapper.ExperimentDocMapper;
import org.jeecg.modules.database.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 试验文档
 * @Author: jeecg-boot
 * @Date: 2024-08-30
 * @Version: V1.0
 */
@Service
@Slf4j
public class ExperimentDocServiceImpl extends ServiceImpl<ExperimentDocMapper, ExperimentDoc> implements IExperimentDocService {

    @Value("${jeecg.template.path}")
    private String                   templatePath;
    @Autowired
    private IExperimentService       experimentService;
    @Autowired
    private IExperimentReportService experimentReportService;
    static  Map<String, String>      docTempalteMap = new HashMap<>();

    static {
        //辐照试验计划表
        docTempalteMap.put("辐照试验计划表", "fzsyjhb.docx");
        docTempalteMap.put("试验报告评审表", "sybgpsb.docx");
        docTempalteMap.put("设备使用记录表", "sbsyjlb.docx");
        docTempalteMap.put("试验报告", "sybg.docx");
        docTempalteMap.put("辐照试验总结单", "fzsyzjd.docx");
    }

    public static void main(String[] args) throws IOException {
        //The core API uses a minimalist design, only one line of code is required
        Map<String, Object> maps = new HashMap<>();
        maps.put("title", "辐照试验计划表");
        //generateExperimentDoc("20241028号实验", "辐照试验计划表", maps);
    }

    public String generateExperimentDoc(String experimentId, String fileName, String version) {
        String absolutePath = templatePath + File.separator + docTempalteMap.get(fileName);
        log.info("doc template path: " + absolutePath);
        if (!FileUtil.exist(absolutePath)) {
            throw new RuntimeException("模板文件不存在！");
        }
        try {
            Experiment experiment = experimentService.getById(experimentId);
            if (Objects.isNull(experiment)) {
                throw new RuntimeException("实验数据不存在！");
            }
            String tmpDirPath = FileUtil.getTmpDirPath();
            String outputFile = tmpDirPath + fileName + "-" + experimentId + "-" + version + ".docx";
            if (FileUtil.exist(outputFile)) {
                FileUtil.del(outputFile);
            }
            log.info("output file path: " + outputFile);
            Map<String, Object> params = assembleParams(experimentId, fileName);
            XWPFTemplate.compile(absolutePath).render(params).writeToFile(outputFile);
            String path = MinioUtil.upload(FileUtil.getInputStream(outputFile),
                    "experiment_doc/" + experimentId + "/" + version + "/" + experiment.getName() + "-" + fileName + ".docx");
            return path;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    private Map<String, Object> assembleParams(String experimentId, String type) {
        switch (type) {
            case "辐照试验计划表":
                return assembleFzsyjhb(experimentId);
            case "试验报告评审表":
                return assembleSybgpsb(experimentId);
            case "设备使用记录表":
                return assembleSbsyjlb(experimentId);
            case "试验报告":
                return assembleSybg(experimentId);
            case "辐照试验总结单":
                return assembleFzsyzjd(experimentId);
        }
        return new HashMap<>();
    }

    private Map<String, Object> assembleFzsyzjd(String experimentId) {
        return new HashMap<>();
    }

    private Map<String, Object> assembleSybg(String experimentId) {
        Experiment experiment = experimentService.getById(experimentId);
        ExperimentReport latestReport = experimentReportService.getLatestReport(experimentId);
        return new HashMap<>();
    }

    private Map<String, Object> assembleSbsyjlb(String experimentId) {
        return new HashMap<>();
    }

    private Map<String, Object> assembleSybgpsb(String experimentId) {
        return new HashMap<>();
    }

    private Map<String, Object> assembleFzsyjhb(String experimentId) {
        return new HashMap<>();
    }

    @Override
    public ExperimentDoc generate(String experimentId, String type) {
        String version = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
        String filePath = generateExperimentDoc(experimentId, type, version);
        if (StringUtils.isNotBlank(filePath)) {
            ExperimentDoc experimentDoc = new ExperimentDoc();
            experimentDoc.setDocType(type);
            experimentDoc.setExperimentId(experimentId);
            experimentDoc.setFilePath(filePath);
            experimentDoc.setVersion(version);
            this.save(experimentDoc);
            return experimentDoc;
        }
        return null;
    }

    @Override
    public List<ExperimentDoc> getHistoryByExperimentId(String experimentId, String type) {
        return list(new LambdaQueryWrapper<ExperimentDoc>().eq(ExperimentDoc::getExperimentId, experimentId)
                .eq(ExperimentDoc::getDocType, type).orderByDesc(ExperimentDoc::getVersion));
    }

    @Override
    public ExperimentDoc getByExperimentId(String experimentId, String type) {
        return getOne(new LambdaQueryWrapper<ExperimentDoc>().eq(ExperimentDoc::getExperimentId, experimentId)
                .eq(ExperimentDoc::getDocType, type).orderByDesc(ExperimentDoc::getVersion), false);
    }
}
