package com.keystar.plane.inspection.service.impl;

/**
 * @Author Lucien
 * @Date 2023-03-02 08:00:00
 * @Describe 报告接口实现类
 */

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.keystar.plane.inspection.bo.PlaneInspectionResultBo;
import com.keystar.plane.inspection.service.IReportService;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements IReportService {

    final MinioService minioService;

    @Autowired
    public ReportServiceImpl(MinioService minioService) {
        this.minioService = minioService;
    }

    //具体参数参照报告关键词
    @Override
    public void createReport(Map<String, String> mFlyCountMap, Map<String, String> mSummaryMap, List<PlaneInspectionResultBo> planeInspectionResultBoList) {

        FileOutputStream fileOutputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        File mFile = null;

        try {

            Calendar mCalendar = Calendar.getInstance();
            mCalendar.setTime(new Date());

            Map<String, Object> mValueMap = new HashMap<>();
            //报告标题(不用改)
            mValueMap.put("ReportTitle", "大唐安徽新能源唐阳光伏电站无人机智能巡检");
            mCalendar.add(Calendar.MONTH, -1);
            //报告福标题(已适配不用修改, 每个月生成一次, 可以每个月的第一天凌晨生成)
            mValueMap.put("ReportSubTitle", new SimpleDateFormat("yyyy年MM月").format(mCalendar.getTime()) + " 光伏区月度巡检报告");
            mCalendar.setTime(new Date());
            //生成报告日期(已适配不用修改)
            mValueMap.put("GenerateDate", new SimpleDateFormat("yyyy/MM/dd").format(mCalendar.getTime()));

            //电站名字(不需要修改)
            mValueMap.put("StationName", "大唐安徽新能源 唐阳光伏电站");
            //电站占地(问钰尧拿数据后填死即可)
            mValueMap.put("StationArea", "1000 亩");
            //电站装机容量(问钰尧拿数据后填死即可)
            mValueMap.put("StationInstalledCapacity", "50MW");
            //巡检设备(不需要修改)
            mValueMap.put("InspectionUAV", "DJI MK300 H20T");
            //巡检类型(不需要修改)
            mValueMap.put("InspectionType", "可见光、红外");

            mValueMap.putAll(mFlyCountMap);

            mValueMap.putAll(mSummaryMap);

            mValueMap.put("pirs", planeInspectionResultBoList);


            Configuration configuration = new Configuration(new Version("2.3.28"));
            configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());

            ClassTemplateLoader classTemplateLoader = new ClassTemplateLoader(this.getClass(), "/template/");
            configuration.setTemplateLoader(classTemplateLoader);

            Template template = configuration.getTemplate("report.ftl", StandardCharsets.UTF_8.toString());

            //todo: 记得修改路径和名字(这里后面确定路径后要挂载目录)
            mFile = new File("D:\\temp\\1.doc");

            fileOutputStream = new FileOutputStream(mFile);

            outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);

            template.process(mValueMap, outputStreamWriter);

            outputStreamWriter.flush();
        }catch (Exception e) {
            //生成失败删除垃圾文件
            if (mFile != null) {
                if (mFile.exists()) {
                    mFile.delete();
                }
            }
        }finally {
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                }catch (Exception e) {

                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                }catch (Exception e) {

                }
            }
        }

    }

    @Override
    public String pic2Base64FromMinio(String minioAddr) {

        String[] paths = StrUtil.splitToArray(minioAddr, "/");

        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            inputStream = minioService.getObject(paths[1], StrUtil.sub(minioAddr,
                    CharSequenceUtil.length(paths[1]) + 2, CharSequenceUtil.length(minioAddr)));

            byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] bytes = new byte[10240];
            int mReadLength = 0;

            while ((mReadLength = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, mReadLength);
            }

            return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
        }catch (Exception e) {

        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }catch (Exception e) {

                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                }catch (Exception e) {

                }
            }
        }

        return "";
    }

    @Override
    public String pic2Base64FromPath(String filePath) {

        FileInputStream fileInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {

            fileInputStream = new FileInputStream(filePath);

            byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] bytes = new byte[10240];
            int mReadLength = 0;

            while ((mReadLength = fileInputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, mReadLength);
            }

            return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
        }catch (Exception e) {

        }finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }catch (Exception e) {

                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                }catch (Exception e) {

                }
            }
        }

        return "";

    }
}
