package com.ho.filecenter.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ho.business.vo.SingleValueColVo;
import com.ho.business.vo.resp.point.PointCurveHomeResp;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.vo.req.StationHomeRespVo;
import com.ho.filecenter.service.PdfService;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import lombok.extern.slf4j.Slf4j;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author fancl
 * @desc: PDF文件处理
 * @date 2023/11/28
 */
@Service
@Slf4j
public class PdfServiceImpl implements PdfService {

    @Value("${path.chartPath}")
    String charPath;

    @Override
    public List<PdfPTable> getPdfTableList(List<PointCurveHomeResp> pointCurveList, Font titleFont) throws Exception {
        List<PdfPTable> pdfTableList = new ArrayList<>();
        // 创建两列的面板数据table
        PdfPTable panelImageTable = null;
        PdfPCell title= null;
        for (PointCurveHomeResp planPoint : pointCurveList) {
            panelImageTable = new PdfPTable(1);
            PdfPCell cellWithImage = null;
            //图片单独创建表格
            //设置表格宽度百分比
            panelImageTable.setWidthPercentage(100);
            float[] columnPanelImageWidths = {1.0f};
            panelImageTable.setWidths(columnPanelImageWidths);
            //第一列
            String lineStr = null;
            lineStr = planPoint.getColName() ;
            title = new PdfPCell(new Paragraph(lineStr, titleFont));
            title.setHorizontalAlignment(Element.ALIGN_LEFT);
            Image instance = null;
            //生成图片的路径
            //charPath
            Date now = new Date();
            String timeContent = DateUtil.format(now, CommonConstant.DATEYMDHSS);
            //判断文件夹是否存在,不存在就创建
            File fileFolder = new File(charPath);
            if (!fileFolder.exists()) {
                fileFolder.mkdirs();
            }
            String path = charPath + timeContent + ".jpg";
            List<StationHomeRespVo> staticCurveList = planPoint.getStaticCurveList();
            if(staticCurveList ==null || staticCurveList.isEmpty()){
                continue;
            }
            instance = getImage(staticCurveList, path, planPoint.getColName());
            try (FileInputStream fis = new FileInputStream(path)) {
                byte[] buffer = new byte[(int) path.length()];
                fis.read(buffer);
                // 现在，buffer数组中保存了文件的二进制数据
                fis.close();
                instance = Image.getInstance(buffer);
            } catch (IOException e) {
                log.error("解析图片错误");
            }
            // 创建包含图片的单元格
            if (instance != null) {
                cellWithImage = new PdfPCell(instance, false);
                cellWithImage.setFixedHeight(50f);
                cellWithImage.setHorizontalAlignment(Element.ALIGN_CENTER);
                cellWithImage.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                panelImageTable.addCell(instance);
                pdfTableList.add(panelImageTable);
            }
        }
        return pdfTableList;
    }

    @Override
    public List<PdfPTable> getOneTableList(List<SingleValueColVo> pointSingleValueList, Font titleFont) throws Exception {
        List<PdfPTable> pdfPTableList = new ArrayList<>();
        if(pointSingleValueList!=null && !pointSingleValueList.isEmpty()){
            for (SingleValueColVo singleValueColVo : pointSingleValueList) {
                // 创建两列的面板数据table
                PdfPTable panelTable = new PdfPTable(1);
                // 设置表格宽度百分比
                panelTable.setWidthPercentage(100);
                float[] columnPanelWidths = {1.0f};
                panelTable.setWidths(columnPanelWidths);
                //第一列
                String lineStr = singleValueColVo.getColName() +"-" +singleValueColVo.getCol()+" 值:" + singleValueColVo.getValue();
                PdfPCell title = new PdfPCell(new Paragraph(lineStr, titleFont));
                title.setHorizontalAlignment(Element.ALIGN_LEFT);
                panelTable.addCell(title);
                pdfPTableList.add(panelTable);
            }
        }
        return pdfPTableList;

    }

    //根据
    Image getImage(List<StationHomeRespVo> staticCurveList, String path, String curveName) throws Exception {
        BaseFont bfCN = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font titleFont = new Font(bfCN, 12f);
        DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
        //
        for (StationHomeRespVo stationHomeRespVo : staticCurveList) {
            dataSet.addValue(stationHomeRespVo.getDigital(), curveName, stationHomeRespVo.getDate());
        }

        //dataSet.addValue(30, "家储", "第二季度");
        //dataSet.addValue(40, "家储", "第三季度");
        //dataSet.addValue(50, "家储", "第四季度");

        JFreeChart lineChart = ChartFactory.createLineChart(curveName, "", "", dataSet, PlotOrientation.VERTICAL, true, true, true);
        lineChart.getLegend().setItemFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
        //获取title
        lineChart.getTitle().setFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 16));

        //获取绘图区对象
        CategoryPlot linePlot = lineChart.getCategoryPlot();
        //设置绘图区域背景的 alpha 透明度 ,在 0.0f 到 1.0f 的范围内
        linePlot.setBackgroundAlpha(0.5f);

        //区域背景色
        linePlot.setBackgroundPaint(Color.white);

        //背景底部横虚线
        linePlot.setRangeGridlinePaint(Color.gray);
        //linePlot.setRangeGridlinePaint(Color.white);
        //linePlot.setOutlinePaint(Color.RED);//边界线

        // 设置水平方向背景线颜色
        // 设置是否显示水平方向背景线,默认值为true
        linePlot.setRangeGridlinesVisible(true);
        // 设置垂直方向背景线颜色
        linePlot.setDomainGridlinePaint(Color.gray);
        //linePlot.setDomainGridlinePaint(Color.gray);
        // 设置是否显示垂直方向背景线,默认值为false
        linePlot.setDomainGridlinesVisible(true);


        //获取坐标轴对象
        CategoryAxis lineAxis = linePlot.getDomainAxis();
        //设置坐标轴字体
        lineAxis.setLabelFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
        //设置坐标轴标尺值字体（x轴）
        lineAxis.setTickLabelFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
        //获取数据轴对象（y轴）
        ValueAxis rangeAxis = linePlot.getRangeAxis();
        rangeAxis.setLabelFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));


        //图片存放位置
        //String templatePath = "e:/1.jpg";

        FileOutputStream fos = new FileOutputStream(path);
        ChartUtils.writeChartAsJPEG(fos, 0.7f, lineChart, 400, 300);
        fos.close();
        Paragraph lineParagraph = new Paragraph(curveName, titleFont);
        lineParagraph.setAlignment(Paragraph.ALIGN_LEFT);
        //document.add(lineParagraph);
        com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(path);
        image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);
        image.scaleAbsolute(400, 300);
        return image;
    }

}
