package com.qmth.distributed.print.business.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.qmth.distributed.print.business.bean.dto.PdfPackageDto;
import com.qmth.distributed.print.business.bean.dto.PdfSignDto;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.enums.ClassifyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * pdf模板内容填充
 */
public class PdfFillUtils {
    private final static Logger log = LoggerFactory.getLogger(PdfFillUtils.class);

    // 定义全局的字体静态变量
    public static Font textFont28;
    public static Font textFont24;
    public static Font textFont18;
    public static Font textFont12;
    public static Font textFont11;
    public static Font textFont10;
    public static Font textFont9;
    public static Font textFont8;

    // 静态代码块
    static {
        try {
            //解决中文不显示问题
            BaseFont bfChinese = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, BaseFont.NOT_EMBEDDED);
            textFont28 = new Font(bfChinese, 28);
            textFont24 = new Font(bfChinese, 24);
            textFont18 = new Font(bfChinese, 18);
            textFont12 = new Font(bfChinese, 12);
            textFont11 = new Font(bfChinese, 11);
            textFont10 = new Font(bfChinese, 10);
            textFont9 = new Font(bfChinese, 9);
            textFont8 = new Font(bfChinese, 8);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 签到表预览数据
     *
     * @param data     数据内容
     * @param fileName 文件名
     */
    public static JSONObject parseSignTempData(String data, String fileName) {
        PdfSignDto pdfFillDto = new PdfSignDto();
        pdfFillDto.setTitle("签到表样例");
        pdfFillDto.setPackageNumber("123456789");

        JSONObject jsonObject = JSON.parseObject(data);
        // 基础信息
        List<Map<String, String>> basicPlate = new ArrayList<>();
        String basicData = jsonObject.getString("basic");
        List<JSONObject> basicObjectList = JSON.parseArray(basicData, JSONObject.class).stream().filter(m -> m.getBoolean("enable")).collect(Collectors.toList());
        Map<String, String> basicMap;
        for (JSONObject object : basicObjectList) {
            basicMap = new HashMap<>();
            basicMap.put("code", object.getString("code"));
            basicMap.put("name", object.getString("name"));
            basicMap.put("value", "xxx");
            basicPlate.add(basicMap);
        }
        pdfFillDto.setBasicPlate(basicPlate);

        // 表头信息
        String studentData = jsonObject.getString("table");
        List<JSONObject> studentObjectList = JSON.parseArray(studentData, JSONObject.class).stream().filter(m -> m.getBoolean("enable")).collect(Collectors.toList());
        Map<String, String> studentHeadPlateMap = new LinkedHashMap<>();
        for (JSONObject object : studentObjectList) {
            studentHeadPlateMap.put(object.getString("code"), object.getString("name"));
        }
        studentHeadPlateMap.put("studentSign", "签名");
        pdfFillDto.setStudentHeadPlate(studentHeadPlateMap);


        // 考生信息
        List<Map<String, String>> studentPlate = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            Map<String, String> studentMap = new HashMap<>();
            for (JSONObject object : studentObjectList) {
                studentMap.put(object.getString("code"), "xxx");
            }
            studentMap.put("studentSign", "");
            studentPlate.add(studentMap);
        }
        pdfFillDto.setStudentPlate(studentPlate);
        try {
            CreatePrintPdfUtil createPrintPdfUtil = new CreatePrintPdfUtil();
            File file = createPrintPdfUtil.createSignPdf(pdfFillDto, fileName);
            PrintCommonService printCommonService = SpringContextHolder.getBean(PrintCommonService.class);
            return printCommonService.uploadPdfFile(file, ClassifyEnum.SIGN);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 卷袋贴临时数据
     *
     * @param data data
     */
    public static JSONObject packageTempData(String data, String fileName) {
        PdfPackageDto pdfPackageDto = new PdfPackageDto();
        pdfPackageDto.setTitle("卷袋贴样例");
        pdfPackageDto.setPackageNumber("123456789");

        List<JSONObject> basicObjectList = JSON.parseArray(data, JSONObject.class).stream().filter(m -> m.getBoolean("enable")).collect(Collectors.toList());
        // 基础信息
        List<Map<String, String>> basicPlate = new ArrayList<>();
        for (JSONObject object : basicObjectList) {
            Map<String, String> basicMap = new HashMap<>();
            basicMap.put("code", object.getString("code"));
            basicMap.put("name", object.getString("name"));
            // 实考人数默认为“”
            basicMap.put("value", !"actualExamCount".equals(object.getString("code")) ? "xxx" : " ");
            basicPlate.add(basicMap);
        }
        pdfPackageDto.setBasicPlate(basicPlate);

        try {
            CreatePrintPdfUtil createPrintPdfUtil = new CreatePrintPdfUtil();
            File file = createPrintPdfUtil.createPackagePdf(pdfPackageDto, fileName);
            PrintCommonService printCommonService = SpringContextHolder.getBean(PrintCommonService.class);
            return printCommonService.uploadPdfFile(file, ClassifyEnum.PACKAGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void saveFile(ByteArrayOutputStream baos, String fileName) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(baos.toByteArray());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 填充table
     *
     * @param value       cell内容
     * @param font        字体
     * @param cellColor   背景色
     * @param fixedHeight 垂直对齐方式
     */
    public static PdfPCell createCell(String value, Font font, BaseColor cellColor, float fixedHeight, int horizontalAlignment, int disableBorderSide, int rowspan, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setBorderWidth(0.1F);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(horizontalAlignment);
        cell.setUseAscender(true);
        if (font != null) {
            cell.setPhrase(new Phrase(value, font));
        } else {
            cell.setPhrase(new Phrase(value));
        }
        if (cellColor != null) {
            cell.setBackgroundColor(cellColor);
        }
        if (fixedHeight > 0) {
            cell.setFixedHeight(fixedHeight);
        }
        if (disableBorderSide > 0) {
            cell.disableBorderSide(disableBorderSide);
        }
        if (rowspan > 0) {
            cell.setRowspan(rowspan);
        }
        if (colspan > 0) {
            cell.setColspan(colspan);
        }
        return cell;
    }

    /**
     * 填充table
     *
     * @param value       cell内容
     * @param font        字体
     * @param fixedHeight 垂直对齐方式
     */
    public static PdfPCell createCell(String value, Font font, float fixedHeight, int horizontalAlignment, float paddingLeft) {
        PdfPCell cell = new PdfPCell();
        cell.setBorderWidth(0.1F);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(horizontalAlignment);
        cell.setUseAscender(true);
        if (font != null) {
            cell.setPhrase(new Phrase(value, font));
        } else {
            cell.setPhrase(new Phrase(value));
        }
        if (fixedHeight > 0) {
            cell.setFixedHeight(fixedHeight);
        }
        cell.disableBorderSide(15);
        if (paddingLeft > 0) {
            cell.setPaddingLeft(paddingLeft);
        }
        return cell;
    }

    /**
     * 填充table
     *
     * @param image       cell内容
     * @param fixedHeight 垂直对齐方式
     */
    public static PdfPCell createCell(Image image, float fixedHeight, int horizontalAlignment, int disableBorderSide, int rowspan, int colspan) {
        PdfPCell cell = new PdfPCell(image);
        cell.setBorderWidth(0.1F);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setUseAscender(true);
        cell.setHorizontalAlignment(horizontalAlignment);
//        cell.setExtraParagraphSpace(10);
        if (fixedHeight > 0) {
            cell.setFixedHeight(fixedHeight);
        }
        if (disableBorderSide > 0) {
            cell.disableBorderSide(disableBorderSide);
        }
        if (rowspan > 0) {
            cell.setRowspan(rowspan);
        }
        if (colspan > 0) {
            cell.setColspan(colspan);
        }
        return cell;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param columns 单元格数量
     */
    public static PdfPTable createTable(int columns) {
        PdfPTable table = new PdfPTable(columns);
        try {
            table.setWidthPercentage(100);// 表格宽度为100%
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param widths 宽度
     */
    public static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths.length);
        try {
            table.setTotalWidth(widths);
            table.setWidthPercentage(100);// 表格宽度为100%
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建条形码
     *
     * @param writer   writer
     * @param barCode  条形码(数字)
     * @param hideCode 是否隐藏条形码(数字)
     */
    public static Image createBarcode(PdfWriter writer, String barCode, Boolean hideCode, BaseColor barColor, BaseColor textColor) {
        Barcode128 barcode128 = new Barcode128();
        barcode128.setCode(barCode);//设置数字
        barcode128.setCodeType(Barcode.CODE128);
        //设置字体
        if (hideCode) {
            barcode128.setFont(null);
        }
        return barcode128.createImageWithBarcode(writer.getDirectContent(), barColor, textColor);
    }

}
