package com.huigou.topsun.common;

import com.itextpdf.text.pdf.BaseFont;
import freemarker.template.Template;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class CommonUtils {


    public static ByteArrayOutputStream createPDF(Object m, Template template){
        ByteArrayOutputStream  byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            // freemarkerConfigurer.getConfiguration().setClassForTemplateLoading(SapPermitApplicationImpl.class,"/template");
           // Template template = freemarkerConfigurer.getConfiguration().getTemplate(modelPath);
            StringWriter w = new StringWriter();
            template.process(m, w);
            w.flush();
            String s = w.toString();
            ITextRenderer iTextRenderer = new ITextRenderer();
            iTextRenderer.getFontResolver().addFont("font/simsun.ttc", BaseFont.IDENTITY_H, true);
            iTextRenderer.setDocumentFromString(s);
            iTextRenderer.layout();
            iTextRenderer.createPDF(byteArrayOutputStream,false);
            iTextRenderer.finishPDF();
            byteArrayOutputStream.flush();
        } catch (Exception e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        }finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayOutputStream;
    }


    public static void generateBarCode128(String msg, String imgType, OutputStream out,int dpi, double height, HumanReadablePlacement placement)
            throws IOException {
        if (msg == null || out == null) {
            return;
        }
        Code128Bean bean = new Code128Bean();
        //int dpi = 100;
        // module宽度 UnitConv.in2mm(1.f / dpi);
        double moduleWidth = 0.3;
        bean.setModuleWidth(moduleWidth);
        bean.setMsgPosition(placement);
        bean.setHeight(height);
        bean.doQuietZone(false);


        BitmapCanvasProvider canvas = new BitmapCanvasProvider(out, imgType,
                dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
        bean.generateBarcode(canvas, msg);
        canvas.finish();
    }

    public static File genBarCode128(String msg, String imgType, File file, int dpi, double height, HumanReadablePlacement placement)
            throws IOException {
          FileOutputStream out = new FileOutputStream(file);
        try {
            generateBarCode128(msg,imgType, out,dpi,height,placement);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return file;
    }

    /**
     * 获取Excel cell中的值并返回String类型
     *
     * @param cell
     * @return String类型的cell值
     */
    public static String getExcelCellValue(Cell cell) {
        String cellValue = "";
        if (null != cell) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    if (0 == cell.getCellType()) {// 判断单元格的类型是否则NUMERIC类型
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判断是否为日期类型
                            Date date = cell.getDateCellValue();
//                      DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                            DateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
                            cellValue = formater.format(date);
                        } else {
                            // 有些数字过大，直接输出使用的是科学计数法： 2.67458622E8 要进行处理
                            DecimalFormat df = new DecimalFormat("####.####");
                            cellValue = df.format(cell.getNumericCellValue());
                            // cellValue = cell.getNumericCellValue() + "";
                        }
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    cellValue = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    cellValue = cell.getBooleanCellValue() + "";
                    break;
                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    try {
                        // 如果公式结果为字符串
                        cellValue = String.valueOf(cell.getStringCellValue());
                    } catch (IllegalStateException e) {
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判断是否为日期类型
                            Date date = cell.getDateCellValue();
//                      DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                            DateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
                            cellValue = formater.format(date);
                        } else {
                            FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper()
                                    .createFormulaEvaluator();
                            evaluator.evaluateFormulaCell(cell);
                            // 有些数字过大，直接输出使用的是科学计数法： 2.67458622E8 要进行处理
                            DecimalFormat df = new DecimalFormat("####.####");
                            cellValue = df.format(cell.getNumericCellValue());
//                          cellValue = cell.getNumericCellValue() + "";
                        }
                    }
//              //直接获取公式
//              cellValue = cell.getCellFormula() + "";
                    break;
                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    cellValue = "";
                    break;
                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    cellValue = "非法字符";
                    break;
                default:
                    cellValue = "未知类型";
                    break;
            }
        }
        return cellValue;

    }
}
