package com.pcloud.book.copyright.tools;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.copyright.dto.DateDTO;
import com.pcloud.book.copyright.entity.BookAuthCode;
import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.enums.ImageTypeEnum;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.LocalDateUtils;
import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.zip.CompressUtils;

import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.imageio.ImageIO;

/**
 * @author lily
 * @date 2018/12/4 16:37
 */
@Component("copyrightTools")
public class CopyrightTools {
    private static final Logger LOGGER = LoggerFactory.getLogger(CopyrightTools.class);
    private static String ZIP_FILE_PATH = OSConstant.USERDIR + "/zip/";
    private static String FILE_LOCAL_PATH = OSConstant.USERDIR + "/download/";
    private static String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};


    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 11; i++) {
            String str = uuid.substring(i * 2, i * 2 + 2);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3C]);
        }
        return shortBuffer.toString().toLowerCase();
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        System.out.println(createShortUuidByCount(100000));
        long time1 = System.currentTimeMillis();
        System.out.println(time1 - time);
    }

    /**
     * 生成count位非重复的数
     *
     * @return
     */
    public static List<String> createShortUuidByCount(Integer count) {
        Map<String, String> numbers = new HashMap<>();
        Set<String> numSet = numbers.keySet();
        while (numSet.size() < count) {
            String uuid = generateShortUuid();
            numbers.put(uuid, uuid);
        }
        return new ArrayList<>(numbers.keySet());
    }


    public static String generateBarCode128Local(String strBarCode, String dimension, String barheight) {
        try {
            BufferedImage bi = null;
            JBarcode productBarcode = new JBarcode(Code128Encoder.getInstance(), WidthCodedPainter.getInstance(), EAN13TextPainter.getInstance());
            productBarcode.setXDimension(Double.valueOf(dimension));
            productBarcode.setBarHeight(Double.valueOf(barheight));
            productBarcode.setWideRatio(Double.valueOf(30.0D));
            productBarcode.setShowText(true);
            productBarcode.setTextPainter(BaseLineTextPainter.getInstance());
            bi = productBarcode.createBarcode(strBarCode);
            String imageUrl = uploadImage(bi);
//            File file = new File("BARCODE" + strBarCode + ".jpg");
//            ImageIO.write(bi, ImageTypeEnum.JPG.value, file);
            return imageUrl;
        } catch (Exception var7) {
            var7.printStackTrace();
            return "encodeError";
        }
    }

    /**
     * 生成条形码
     * @param bookAuthCodes
     * @param fileName
     * @param excelUrl
     * @return
     */
    public static String generateBar4Zip(List<BookAuthCode> bookAuthCodes, String fileName, String excelUrl) {
        fileName = FileUtils.formatName(fileName);
        String tempZipName = fileName + "_" + LocalDateUtils.getYmdhmss();
        String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
        String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
        FileUtils.isDir(fileFolderPath);
        UploadResultInfo uploadResultInfo;
        try {
            for (BookAuthCode bookAuthCode : bookAuthCodes) {
                BufferedImage bi;
                JBarcode productBarcode = new JBarcode(Code128Encoder.getInstance(), WidthCodedPainter.getInstance(), EAN13TextPainter.getInstance());
                productBarcode.setXDimension(0.5);
                productBarcode.setBarHeight(30d);
                productBarcode.setWideRatio(30.0D);
                productBarcode.setShowText(true);
                productBarcode.setTextPainter(BaseLineTextPainter.getInstance());
                bi = productBarcode.createBarcode(bookAuthCode.getFullCode());
                paintText(bi, bookAuthCode.getFullCode());
                File file = new File(fileFolderPath + "/" + bookAuthCode.getFullCode() + ".png");
                ImageIO.write(bi, ImageTypeEnum.PNG.value, file);
            }
            String downloadLocalPath = fileFolderPath + "/" + fileName + ".xls";
            FileUtils.downloadFileFromUrl(excelUrl, downloadLocalPath);
            // 检查压缩包临时文件夹是否存在，不存在就创建
            FileUtils.isDir(ZIP_FILE_PATH);
            CompressUtils.zip(fileFolderPath, zipFilePath);
            // 上传文件到服务器中
            uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, fileName);
        } catch (Exception e) {
            LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
            throw new FileException(FileException.ZIP_ERROR, "压缩失败！");
        } finally {
            // 删除产生的文件
            FileUtils.deleteDirectory(fileFolderPath);
            FileUtils.deleteFile(zipFilePath);
        }
        return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
    }

    /**
     * 生成二维码
     * @param bookAuthCodes
     * @param fileName
     * @param excelUrl
     * @return
     */
    public static String generateQrcode4Zip(List<BookAuthCode> bookAuthCodes, String fileName, String excelUrl) {
        fileName = FileUtils.formatName(fileName);
        String tempZipName = fileName + "_" + LocalDateUtils.getYmdhmss();
        String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
        String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
        FileUtils.isDir(fileFolderPath);
        UploadResultInfo uploadResultInfo;
        try {
            for (BookAuthCode bookAuthCode : bookAuthCodes) {
                LOGGER.info("【二维码】generateQrcode4Zip,<START>.[url]=" + bookAuthCode);
                Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                hints.put(EncodeHintType.MARGIN, 0); // 设置白边
                try {
                    // 生成矩阵
                    BitMatrix bitMatrix = new MultiFormatWriter().encode(bookAuthCode.getFullCode(), BarcodeFormat.QR_CODE, 55,
                            55, hints);
                    int width = bitMatrix.getWidth();
                    int height = bitMatrix.getHeight();
                    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

                    for(int x=0;x<width;x++){
                        for(int y=0;y<height;y++){
                            bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                        }
                    }
//                    paintQrcodeText(bufferedImage, bookAuthCode.getFullCode());
                    File file = new File(fileFolderPath + "/" + bookAuthCode.getFullCode() + ".png");
                    ImageIO.write(bufferedImage, ImageTypeEnum.PNG.value, file);
                } catch (Exception e) {
                    LOGGER.error("【二维码】创建二维码失败,<ERROR>:" + e.getMessage(), e);
                    throw new FileException(FileException.FILE_UPLOAD_FAILURE, "创建二维码失败");
                }
            }
            String downloadLocalPath = fileFolderPath + "/" + fileName + ".xls";
            FileUtils.downloadFileFromUrl(excelUrl, downloadLocalPath);
            // 检查压缩包临时文件夹是否存在，不存在就创建
            FileUtils.isDir(ZIP_FILE_PATH);
            CompressUtils.zip(fileFolderPath, zipFilePath);
            // 上传文件到服务器中
            uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, fileName);
        } catch (Exception e) {
            LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
            throw new FileException(FileException.ZIP_ERROR, "压缩失败！");
        } finally {
            // 删除产生的文件
            FileUtils.deleteDirectory(fileFolderPath);
            FileUtils.deleteFile(zipFilePath);
        }
        return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
    }


    public static String uploadImage(BufferedImage image) throws BizException {
        UploadResultInfo uploadResultInfo = null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, ImageTypeEnum.PNG.value, os);
            uploadResultInfo = OssUtils.uploadFileByte(os.toByteArray(), UUIDUitl.taskName(), ImageTypeEnum.PNG.value);
            os.close();
            return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
        } catch (Exception e) {
            throw new FileException(FileException.FILE_UPLOAD_FAILURE, "上传条形码失败");
        }
    }

    /**
     * 获取开始与结束时间
     */
    public static DateDTO getDateByType(Long days) {
        DateDTO dateDTO = new DateDTO();
        if (BookConstant.SEVEN.equals(days)) {
            dateDTO.setStartTime(DateUtils.getLongDateStr(DateUtils.getDayStartTime(DateUtils.addDay(new Date(), -7))));
            dateDTO.setEndTime(DateUtils.getLongDateStr(DateUtils.getDayEndTime(DateUtils.addDay(new Date(), -1))));
        } else if (BookConstant.FIFTEEN.equals(days)) {
            dateDTO.setStartTime(DateUtils.getLongDateStr(DateUtils.getDayStartTime(DateUtils.addDay(new Date(), -15))));
            dateDTO.setEndTime(DateUtils.getLongDateStr(DateUtils.getDayEndTime(DateUtils.addDay(new Date(), -1))));
        } else if (BookConstant.THIRTY.equals(days)) {
            dateDTO.setStartTime(DateUtils.getLongDateStr(DateUtils.getDayStartTime(DateUtils.addDay(new Date(), -29))));
            dateDTO.setEndTime(DateUtils.getLongDateStr(DateUtils.getDayEndTime(new Date())));
        }
        return dateDTO;
    }

    public static List<String> getLast6Months() {
        DecimalFormat df = new DecimalFormat("00");
        List<String> last6Months = new ArrayList<>(6);
        Calendar cal = Calendar.getInstance();
        for (int i = 1; i < 7; i++) {
            last6Months.add(cal.get(Calendar.YEAR) + "-" + df.format(cal.get(Calendar.MONTH) + 1));
            // 逐次往前推1个月
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
        }
        return last6Months;
    }

//    public static void paintText(BufferedImage barCodeImage, String text) {
//        //绘图
//        Graphics g2d = barCodeImage.getGraphics();
//        //创建字体
//        Font font = new Font("console", Font.PLAIN, 15 );
//        g2d.setFont(font);
//        FontMetrics fm = g2d.getFontMetrics();
//        int height = fm.getHeight();
//        int center = (barCodeImage.getWidth() - fm.stringWidth(text)) / 2;
//        g2d.setColor(Color.WHITE);
//        g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() * 1 / 20);
//        g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10), barCodeImage.getWidth(), (height * 9 / 10));
//        g2d.setColor(Color.BLACK);
//        g2d.drawString(text, center, barCodeImage.getHeight() - (height / 10) - 2);
//    }

    public static void paintQrcodeText(BufferedImage barCodeImage, String text) {
        //绘图
        Graphics g2d = barCodeImage.getGraphics();
        //创建字体
        Font font = new Font("console", Font.PLAIN, 5);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int height = fm.getHeight();
//        int center = (barCodeImage.getWidth() - fm.stringWidth(text)) / 2;
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() / 20);
        g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10), barCodeImage.getWidth(), (height * 9 / 10));
        g2d.setColor(Color.BLACK);
        //g2d.drawString(text, center, barCodeImage.getHeight() - (height / 10) - 2);
        int start = 17;
        int length = (barCodeImage.getWidth() - 2 * start) / text.length();
        for (int i = 0; i < text.length(); i++) {
            g2d.drawString(text.substring(i, i + 1), start + i * length, barCodeImage.getHeight() - (height / 10) - 2);
        }
    }

    public static void paintText(BufferedImage barCodeImage, String text) {
        //绘图
        Graphics g2d = barCodeImage.getGraphics();
        //创建字体
        Font font = new Font("console", Font.PLAIN, 25);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int height = fm.getHeight();
//        int center = (barCodeImage.getWidth() - fm.stringWidth(text)) / 2;
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() / 20);
        g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10), barCodeImage.getWidth(), (height * 9 / 10));
        g2d.setColor(Color.BLACK);
        //g2d.drawString(text, center, barCodeImage.getHeight() - (height / 10) - 2);
        int start = 17;
        int length = (barCodeImage.getWidth() - 2 * start) / text.length();
        for (int i = 0; i < text.length(); i++) {
            g2d.drawString(text.substring(i, i + 1), start + i * length, barCodeImage.getHeight() - (height / 10) - 2);
        }
    }

}
