package com.cftech.common.typeappform.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.StringUtils;
import lombok.Data;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.owasp.esapi.ESAPI;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lisw
 * @program schaeffler
 * @description 促销品报表导出工具类
 * @createDate 2020-01-17 10:07:27
 **/
@Data
public class StatisticalCommonExportUtil {

    /**
     * 通用单元格样式
     */
    private CellStyle genterateCellStyle;

    /**
     * 金色填充
     */
    private CellStyle goldCellStyle;

    /**
     * 绿色填充
     */
    private CellStyle greenCellStyle;

    /**
     * 灰色25填充
     */
    private CellStyle grey25CellStyle;

    /**
     * 表格对象
     */
    private HSSFWorkbook wb;

    /**
     * 白色字体
     */
    private HSSFFont hssfFontWhite;

    /**
     * 黑色字体
     */
    private HSSFFont blackFont;

    /**
     * 绿色字体
     */
    private HSSFFont greenFont;

    /**
     * 行高
     */
    private short rowHeight=900;

    /**
     * 换行
     */
    private String lineStr = "\r\n";


   public StatisticalCommonExportUtil(HSSFWorkbook wb){
       this.wb=wb;
       //白色字体
       this.hssfFontWhite = wb.createFont();
       this.hssfFontWhite.setColor(HSSFColor.WHITE.index);
       this.hssfFontWhite.setFontName("Calibri");
       //黑色字体
       this.blackFont = wb.createFont();
       this.blackFont.setColor(HSSFColor.BLACK.index);
       this.blackFont.setFontName("Calibri");
       //绿色字体
       this.greenFont = wb.createFont();
       this.greenFont.setColor(HSSFColor.GREEN.index);
       this.greenFont.setFontName("Calibri");
       //样式
       this.genterateCellStyle = genterateHeader();
       this.goldCellStyle = rtnHeaderGold();
       this.greenCellStyle = rtnHeadersGreen();
       this.grey25CellStyle = rtnHeaderGREY25();
   }

   //灰色填充
    public CellStyle rtnHeaderGREY25(){
        CellStyle cellStyle =genterateHeader();
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
        cellStyle.setFont(greenFont);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return cellStyle;
    }

    //金色填充
    public CellStyle rtnHeaderGold(){
        CellStyle cellStyle =genterateHeader();
        cellStyle.setFillForegroundColor(IndexedColors.GOLD.index);
        cellStyle.setFont(hssfFontWhite);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return cellStyle;
    }

    //绿色填充
    public CellStyle rtnHeadersGreen(){
        CellStyle cellStyle = genterateHeader();
        short greenIndex = IndexedColors.GREEN.index;
        cellStyle.setFillForegroundColor(greenIndex);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFont(hssfFontWhite);
        return cellStyle;
    }

    //通用样式 边框定制
    public CellStyle genterateHeader(){
        CellStyle cellStyle =wb.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        //cellStyle.setFont(hssfFontWhite);
        //cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平布局：居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setFont(blackFont);
        return cellStyle;
    }

    /**
     * 数字正则表达式
     */
    Pattern integerP = Pattern.compile("^-?\\d+$");
    /**
     * double正则表达式
     */
   Pattern doubleP = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");

    //创建通用单元格
    public Cell createCell(int index, Object value, Row row){
        String v = "";
        if(value!=null && value instanceof Date){
            Date time = (Date)value;
            v= DateUtils.formatDate(time,"yyyy-MM-dd HH:mm");
        }else{
            v=value!=null?String.valueOf(value):"";
        }
        Cell cell = row.createCell(index);
        Matcher integerMatcher = integerP.matcher(v);
        Matcher doubleMatcher = doubleP.matcher(v);
        // 是数字
        if (integerMatcher.matches()) {
            Long maxValidate = Long.valueOf(v);
            if(maxValidate<Integer.MAX_VALUE){
                cell.setCellValue(Integer.valueOf(v));
            }else{
                cell.setCellValue(v);
            }
        } else if(doubleMatcher.matches()){
            cell.setCellValue(Double.valueOf(v));
        }else{
            cell.setCellValue(v);
        }
        cell.setCellStyle(getGenterateCellStyle());
        return cell;
    }

    /**
     * 创建千位制的单元格
     */
    public Cell createThousandBit(int index, Object value, Row row, HSSFWorkbook workbook){
       Cell cell = row.createCell(index);
        CellStyle cellStyle =genterateHeader();
       if(value!=null){
           if(StringUtils.isNotBlank(String.valueOf(value))){
               // 单元格格式，千分位加2位小数
               HSSFDataFormat df = workbook.createDataFormat();
               cell = row.createCell(index, Cell.CELL_TYPE_NUMERIC);
               cellStyle.setDataFormat(df.getFormat("#,#0.00"));
               cell.setCellValue(Double.valueOf(String.valueOf(value)));
           }else{
               cell.setCellValue("");
           }
       }
        cell.setCellStyle(cellStyle);
        return cell;
    }


    /**
     * 解析固化ITEMS JSON数据返回String管理员发货数量
     * @param items
     * @return
     */
    public String parseItemsManagerJSON(String items){
        StringBuffer parseBuffer = new StringBuffer();
        JSONArray array = JSON.parseArray(ESAPI.encoder().decodeForHTML(items));
        for(int k =0;k<array.size();k++){
            JSONObject obj = array.getJSONObject(k);
            String name = obj.getString("name");
            String count = obj.getString("managerGrantCount");
            parseBuffer.append(name+"*"+count+";"+getLineStr());
        }
        return parseBuffer.toString();
    }

    //解析固化ITEMS JSON数据返回String供应商发货数量
    public String parseItemsSupplierJSON(String items){
        StringBuffer parseBuffer = new StringBuffer();
        JSONArray array = JSON.parseArray(ESAPI.encoder().decodeForHTML(items));
        for(int k =0;k<array.size();k++){
            JSONObject obj = array.getJSONObject(k);
            String name = obj.getString("name");
            String count = obj.getString("disGrantCount");
            parseBuffer.append(name+"*"+count+";"+getLineStr());
        }
        return parseBuffer.toString();
    }

    /**
     * 数字转为千分制
     * @param obj
     * @return
     */
    public static String parseToThousandBit(Object obj){
       if(obj==null || StringUtils.isBlank(String.valueOf(obj))){
           return null;
       }
        /**
         *转为千分制字符串
         */
        String str = NumberFormat.getNumberInstance(Locale.getDefault()).format(new BigDecimal(obj.toString()));
        return str;
    }
}
