package com.ruoyi.common.utils;
import org.apache.poi.hpsf.Section;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.HeaderFooter;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.Units;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.wp.usermodel.Paragraph;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;


/**
 * @Description: poi工具类
 * @Date: 2022/10/11
 * @Author shuaihua zang
 */
public class BarChart
{

    public static Double fun(Double value)
    {
        BigDecimal bg=new BigDecimal(value);
        return  bg.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    }



    private void setXWPFRunStyle(XWPFRun r1,String font,int fontSize) {
        r1.setFontSize(fontSize);
        CTRPr rpr = r1.getCTR().isSetRPr() ? r1.getCTR().getRPr() : r1.getCTR().addNewRPr();
        CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
        fonts.setAscii(font);
        fonts.setEastAsia(font);
        fonts.setHAnsi(font);
    }


    public  static void createHeader(XWPFDocument doc, String orgFullName){
       try {

           CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
           XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(doc,    sectPr);
           XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
           XWPFParagraph paragraph = header.createParagraph();
           paragraph.setAlignment(ParagraphAlignment.BOTH);   //设置段落左对齐
           paragraph.setBorderBottom(Borders.THICK);    //设置下划线
//           paragraph.setSpacingLineRule(LineSpacingRule.AUTO);
           paragraph.setSpacingBetween(40,LineSpacingRule.EXACT);
//           paragraph.setAlignment(ParagraphAlignment.CENTER);

           XWPFRun run = paragraph.createRun();
           run.setBold(false);
            run.setFontSize(9);
           /*
            * 取到图片的字节流
            * */
           String logoFilePath="shate.png";
           if (StringUtils.isNotEmpty(logoFilePath)) {
               File file=new File(logoFilePath);
               InputStream is = new FileInputStream(file);
               XWPFPicture picture = run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, logoFilePath, Units.toEMU(60), Units.toEMU(30));
               String blipID = "";
               for(XWPFPictureData picturedata : header.getAllPackagePictures()) {    //这段必须有，不然打开的logo图片不显示
                   blipID = header.getRelationId(picturedata);
               }
               picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID);
               run.addTab();
               is.close();
           }
           /*
            * 添加字体页眉
            * */
           if (StringUtils.isNotEmpty(orgFullName)) {
               run = paragraph.createRun();
               run.setText("      "+orgFullName);
           }


       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       } catch (InvalidFormatException e) {
           throw new RuntimeException(e);
       }

    }
    //绘制折线图
    public static void drawLine(XWPFDocument document, String[] xAxisData,Double[] yAxisData) throws Exception {
        XWPFChart xChart =  document.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);
//        xChart.setTitleText("海拔"); // 图表标题
        xChart.setTitleOverlay(false);

        // 5、X轴(分类轴)相关设置
        // 创建X轴,并且指定位置
        XDDFCategoryAxis xAxis = xChart.createCategoryAxis(AxisPosition.BOTTOM);
        XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData); // 设置X轴数据
//        xAxis.setTitle("海拔km²");
        // 6、Y轴(值轴)相关设置
        XDDFValueAxis yAxis = xChart.createValueAxis(AxisPosition.LEFT); // 创建Y轴,指定位置轴标题
        XDDFNumericalDataSource<Double> yAxisSource = XDDFDataSourcesFactory.fromArray(yAxisData); // 设置Y轴数据
        yAxis.setTitle("km²");
        // 7、创建折线图对象
        XDDFLineChartData lineChart = (XDDFLineChartData) xChart.createData(ChartTypes.LINE, xAxis, yAxis);

        // 8、加载折线图数据集
        XDDFLineChartData.Series lineSeries = (XDDFLineChartData.Series) lineChart.addSeries(xAxisSource, yAxisSource);
        lineSeries.setSmooth(false); // 线条样式:true平滑曲线,false折线
        lineSeries.setMarkerSize((short) 6); // 标记点大小
        lineSeries.setMarkerStyle(MarkerStyle.CIRCLE); // 标记点样式

        // 9、绘制折线图
        xChart.plot(lineChart);
    }

    public static void drawTable(XWPFDocument document, String[] xAxisData,Double[] yAxisData) throws Exception {
        // 创建chart图表对象,抛出异常
//        XWPFChart chart = document.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);
        XWPFChart chart=document.createChart(15 * Units.EMU_PER_CENTIMETER, 11 * Units.EMU_PER_CENTIMETER);
         chart.setTitleText("");
        chart.setTitleOverlay(false); // 图例是否覆盖标题
        chart.setChartBottomMargin(50);
        // X轴(分类轴)相关设置
        XDDFCategoryAxis xAxis =chart.createCategoryAxis(AxisPosition.BOTTOM); // 创建X轴,并且指定位置
        xAxis.setTitle(""); // x轴标题
        XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData); // 设置X轴数据
        // Y轴(值轴)相关设置
        //chart.createValueAxis(AxisPosition.LEFT);
        XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT); // 创建Y轴,指定位置
        yAxis.setTitle("Area(km²)"); // Y轴标题
        yAxis.setCrossBetween(AxisCrossBetween.BETWEEN); // 设置图柱的位置:BETWEEN居中
        XDDFNumericalDataSource<Double> yAxisSource = XDDFDataSourcesFactory.fromArray(yAxisData); // 设置Y轴数据
        ChartTypes chartTypes = ChartTypes.BAR;
        // 创建柱状图对象
        XDDFBarChartData barChart = (XDDFBarChartData) chart.createData(chartTypes, xAxis, yAxis);
        barChart.setBarDirection(BarDirection.COL); // 设置柱状图的方向:BAR横向,COL竖向,默认是BAR
        barChart.setVaryColors(false);
        // 加载柱状图数据集
        XDDFBarChartData.Series barSeries = (XDDFBarChartData.Series) barChart.addSeries(xAxisSource, yAxisSource);
        barSeries.setTitle("    ", null); // 图例标题
        // 绘制柱状图
        chart.plot(barChart);


    }

    //插入图片
    public static void insertPic(XWPFDocument document,String fileAddress)
    {
        XWPFParagraph Paragraph = document.createParagraph();
        Paragraph.setAlignment(ParagraphAlignment.CENTER);//对齐方式
        XWPFRun run = Paragraph.createRun();
        try (FileInputStream is = new FileInputStream
                (fileAddress)) {
            run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG,
                    fileAddress,
                    Units.toEMU(392), Units.toEMU(280)); // 200x200 pixels
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //创建段落并插入文字
    public static void createParagraphAndInsertWord(XWPFDocument document,String date) {
        XWPFParagraph Paragraph = document.createParagraph();
        //设置行距固定值20磅
        //setLineSpace(Paragraph,30);
        Paragraph.setAlignment(ParagraphAlignment.LEFT);//对齐方式
        //paragraph_2.setFirstLineIndent(400);//首行缩进
        XWPFRun run = Paragraph.createRun();
        run.setText(date);
        run.setBold(false);//加粗
        run.setFontSize(12);
        run.setFontFamily("Times New Roman");
    }
    //创建一级标题的内容
    public static void createFirstLevelTopic(XWPFDocument document,String date)
    {
        XWPFParagraph Paragraph = document.createParagraph();
        Paragraph.setAlignment(ParagraphAlignment.LEFT);//对齐方式
        //BarChart.setLineSpace(Paragraph,30);
        XWPFRun run = Paragraph.createRun();
        run.setText(date);
        run.setBold(true);//加粗
        run.setFontSize(16);
        run.setFontFamily("Times New Roman");
    }
    //创建二级标题的内容
    public static void createSecondLevelTopic(XWPFDocument document,String date)
    {
        XWPFParagraph Paragraph = document.createParagraph();
        Paragraph.setAlignment(ParagraphAlignment.LEFT);//对齐方式
        //BarChart.setLineSpace(Paragraph,30);
        XWPFRun run = Paragraph.createRun();
        run.setText(date);
        run.setBold(true);//加粗
        run.setFontSize(12);
        run.setFontFamily("Times New Roman");
    }
    //创建图片标题的内容
    public static void setPicTitle(XWPFDocument document,String date)
    {
        XWPFParagraph Paragraph = document.createParagraph();

//        Paragraph.setAlignment(ParagraphAlignment.CENTER);
//// 边框
//        Paragraph.setBorderBottom(Borders.NIL);
//        Paragraph.setBorderTop(Borders.NIL);
//        Paragraph.setBorderRight(Borders.NIL);
//        Paragraph.setBorderLeft(Borders.NIL);
//        Paragraph.setBorderBetween(Borders.SINGLE);
//        Paragraph.setSpacingAfter(5);
//        Paragraph.setSpacingBeforeLines(5);
//        Paragraph.setSpacingBetween(5);
        Paragraph.setAlignment(ParagraphAlignment.CENTER);//对齐方式
        BarChart.setLineSpace(Paragraph,25);
        XWPFRun run = Paragraph.createRun();
//        run.addCarriageReturn();
        run.setText(date);
        run.setBold(true);//加粗
        run.setFontSize(10);
//        run.setFontFamily("Times New Roman");
    }
    //设置题目
    public static void setTitle(XWPFDocument document,String date)
    {
        XWPFParagraph title = document.createParagraph();
        title.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun runTitle = title.createRun();
        runTitle.setText(date);
        runTitle.setBold(true);
        runTitle.setFontSize(20);
        runTitle.setFontFamily("Times New Roman");
    }
    //设置行间距
    public static void setLineSpace(XWPFParagraph titleParagraph,int size) {
        CTP ctp = titleParagraph.getCTP();
        CTPPr ppr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr();
        CTSpacing spacing = ppr.isSetSpacing()? ppr.getSpacing() : ppr.addNewSpacing();
        spacing.setAfter(BigInteger.valueOf(0));
        spacing.setBefore(BigInteger.valueOf(0));
        //设置行距类型为 EXACT
        spacing.setLineRule(STLineSpacingRule.EXACT);
        //1磅数是20
        spacing.setLine(BigInteger.valueOf(size*20));
    }

    public static String getDoubleNumber(Double d)
    {
        DecimalFormat df = new DecimalFormat("#.00");
       return df.format(d);
    }
    public static String changeDate(String date)
    {
        String s1 = date.substring(0, 4);
        String s2 = date.substring(4, 6);
        String s3 = date.substring(6, date.length());
        return  s1+"-"+s2+"-"+s3;
    }



}