package com.om.utils;


import com.om.OperationApplication;
import com.om.entity.dto.ControlListMap;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HtmlGenerator {
    @Value("${baseStatic}")
    private  String baseStatic;


    public  File generateHtmlByMap(Integer id, List<ControlListMap> controlListMap
            , Map<String, String> baseMap, Map<String, String> companyMap){

        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
            cfg.setClassForTemplateLoading(OperationApplication.class, "../../template/static/");

            Template template = cfg.getTemplate("report.html");
            String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            StringWriter out = new StringWriter();
            Map<String, Object> data = new HashMap<>();
            data.put("reportTime",format);
            data.put("baseMap", baseMap);
            data.put("controlListMap", controlListMap);
            data.put("companyMap", companyMap);
            data.put("id", id);

            template.process(data, out);

            // 将HTML内容写入文件
            String htmlContent = out.toString();
            String yyyyMMdd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String outputPath = baseStatic+yyyyMMdd+"outputH5"+id+".html";
            FileWriter fileWriter = new FileWriter(outputPath);
            fileWriter.write(htmlContent);
            File file = new File(baseStatic+yyyyMMdd+"outputH5"+id+".html");
            fileWriter.close();
            System.out.println("HTML文件已生成：" + outputPath);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
