package cn.com.tenlion.buildingpictures.service.picturestemplatebuilding.impl;

import cn.com.tenlion.buildingpictures.pojo.dtos.picturestemplate.PicturesTemplateBuildingDTO;
import cn.com.tenlion.buildingpictures.pojo.dtos.picturestemplate.PicturesTemplateDTO;
import cn.com.tenlion.buildingpictures.pojo.dtos.picturestemplatearea.PicturesTemplateAreaBuildingDTO;
import cn.com.tenlion.buildingpictures.pojo.dtos.picturestemplatearea.PicturesTemplateAreaDTO;
import cn.com.tenlion.buildingpictures.service.picturestemplate.IPicturesTemplateService;
import cn.com.tenlion.buildingpictures.service.picturestemplatearea.IPicturesTemplateAreaService;
import cn.com.tenlion.buildingpictures.service.picturestemplatebuilding.IPicturesTemplateBuildingService;
import cn.com.tenlion.buildingpictures.util.BaiDuMapUtil;
import cn.com.tenlion.buildingpictures.util.BarCodeUtils;
import cn.com.tenlion.buildingpictures.util.CreateImageBean;
import cn.com.tenlion.buildingpictures.util.WeiXinBarCodeUtils;
import com.github.pagehelper.util.StringUtil;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.SaveException;
import ink.wgink.module.file.pojo.vos.FileVO;
import ink.wgink.module.file.service.IFileService;
import ink.wgink.pojo.pos.FilePO;
import ink.wgink.properties.FileProperties;
import ink.wgink.util.UUIDUtil;
import ink.wgink.util.date.DateUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: PicturesTemplateBuildingServiceImpl
 * @Description: 图片套版模板的区域设置
 * @Author: WenG
 * @Date: 2020-10-20 15:08
 * @Version: 1.0
 **/
@Primary
@Service
public class PicturesTemplateBuildingServiceImpl extends DefaultBaseService implements IPicturesTemplateBuildingService {

    @Autowired
    private IPicturesTemplateAreaService picturesTemplateAreaService;
    @Autowired
    private IPicturesTemplateService picturesTemplateService;
    @Autowired
    private IFileService iFileService;
    @Autowired
    private FileProperties fileProperties;

    @Override
    public String saveBase64ToFile(String base64) throws IOException {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64.replaceAll("data:image/png;base64,", ""));
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BufferedImage buffer = ImageIO.read(bais);
        String picturesUrl = saveBufferImageToFile(buffer);
        return picturesUrl;
    }

    @Override
    public String saveBufferImageToBase64(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", stream);
        // 对字节数组Base64编码
        Base64 base = new Base64();
        String base64 = base.encodeToString(stream.toByteArray());
        return "data:image/png;base64," + base64;
    }

    @Override
    public String saveBufferImageToFile(BufferedImage bufferedImage) {
        if(bufferedImage == null ) {
            throw new SaveException("图片不能为空");
        }
        // createImage("D:\\test1.png", bufferedImage);
        String fileName = UUIDUtil.get32UUID() + ".png";
        String baseUploadPath = this.fileProperties.getUploadPath();
        if (StringUtils.isBlank(baseUploadPath)) {
            throw new SaveException("上传路径未配置");
        }
        StringBuilder filePath = new StringBuilder();
        if (!baseUploadPath.endsWith(File.separator)) {
            filePath.append(baseUploadPath).append(File.separator);
        } else {
            filePath.append(baseUploadPath);
        }
        filePath.append("images");
        String days = DateUtil.getDays();
        filePath.append(File.separator).append(days).append(File.separator);
        File file = new File(filePath.toString());
        if(!file.exists()) {
            file.mkdirs();
        }
        String pathUrl = "images/" + days + "/" + fileName;
        filePath.append(fileName);
        createImage(filePath.toString() , bufferedImage);
        FileVO fileVO = new FileVO();
        fileVO.setFileName(fileName);
        fileVO.setFileType("png");
        fileVO.setFileUrl(pathUrl);
        File localFile = new File(filePath.toString());
        fileVO.setFileSize(localFile.length());
        fileVO.setFilePath(filePath.toString());
        String fileId = iFileService.saveFileByUserId("1", fileVO);
        return fileId;
    }

    @Override
    public PicturesTemplateBuildingDTO getPicturesTemplate(String picturesTemplateId) {
        Map<String, Object> queryParam = new HashMap<String, Object>();
        queryParam.put("picturesTemplateId", picturesTemplateId);
        PicturesTemplateBuildingDTO dto= picturesTemplateService.get(queryParam);
        queryParam.put("picturesTemplateId", dto.getPicturesTemplateId());
        List<PicturesTemplateAreaBuildingDTO> areaList = picturesTemplateAreaService.list(queryParam);
        dto.setAreaList(areaList);
        return dto;
    }

    @Override
    public List<PicturesTemplateBuildingDTO> getPicturesTemplateList(Map<String, Object> queryParams)  {
        List<PicturesTemplateBuildingDTO> dtoList = picturesTemplateService.list(queryParams);
        return dtoList;
    }

    @Override
    public List<PicturesTemplateBuildingDTO> getPicturesTemplateAreaList(Map<String, Object> queryParams) {
        List<PicturesTemplateBuildingDTO> dtoList = picturesTemplateService.list(queryParams);
        Map<String, Object> queryParam = new HashMap<String, Object>();
        for (PicturesTemplateBuildingDTO dto : dtoList) {
            queryParam.put("picturesTemplateId", dto.getPicturesTemplateId());
            List<PicturesTemplateAreaBuildingDTO> areaList = picturesTemplateAreaService.list(queryParam);
            dto.setAreaList(areaList);
        }
        return dtoList;
    }

    @Override
    public BufferedImage createBufferImage(List<CreateImageBean> list, File backFile, int backWidth, int backHeight) throws IOException {
        // 创建画布
        BufferedImage image = new BufferedImage(backWidth, backHeight, Image.SCALE_SMOOTH);
        // 得到图片操作对象
        Graphics2D imageGraphics = image.createGraphics();

        //消除文字锯齿
        imageGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //消除图片锯齿
        imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        image = imageGraphics.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT);
        Graphics graphics = image.getGraphics();

        // 对底图进行裁剪
        Image backImg = thumbnail(backFile, backWidth + 1, backHeight);
        // 将底图放入模板中
        graphics.drawImage(backImg, 0, 0,null);
        for (CreateImageBean bean : list) {
            System.out.println(bean.toString());
            // 不是图片 . 需要转换字体 / 颜色 / 大小
            if (!"2".equals(bean.getType())) {
                // 设置文字的颜色为黑色
                graphics.setColor(new Color(bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]));
                // 设置文字的字体,大小
                Font font = new Font(bean.getFontFamily() , bean.getFontBold(), bean.getFontSize());
                graphics.setFont(font);
            }
            // 文字
            if("1".equals(bean.getType())) {
                // 将文字从左侧放入模板中
                // graphics.drawString(bean.getContent(), bean.getX(), ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3);
                // 居中, 超出范围以后截取
                if("2".equals(bean.getCenter())) {
                    // 超出一行的内容剔除掉
                    String content = getTextSplice(bean.getContent(),  bean.getFontSize(), bean.getWidth());
                    bean.setContent(content);

                    int count = getTextCount(bean.getContent(), bean.getFontSize());
                    int startX = ((bean.getWidth()) - count) / 2;
                    // 将文字放入模板中
                    graphics.drawString(bean.getContent(), startX +  bean.getX(), ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3  ); // + ( bean.getHeight() - ( bean.getFontSize() / 2) )
                // 左侧, 超出范围以后会自动的换行
                }else if("1".equals(bean.getCenter())){
                    // 将文字放入模板中
                    List<String> rowList = createText(bean.getWidth(), bean.getFontSize(), bean.getContent());
                    int index = 1;
                    for (String fontContent : rowList) {
                        /**
                         * 对内容进行封装换行
                         */
                        int y =  bean.getY()  + (    (  (    ( bean.getHeight() / 2) + ( bean.getFontSize() / 2)   ) - 3 ) * index );
                        graphics.drawString(fontContent, bean.getX(), y);
                        index++;
                    }
                // 右侧,超出范围以后会向左延升
                }else{
                    int totalSize = getTextCount(bean.getContent(), bean.getFontSize());
                    int startX = (bean.getWidth() - totalSize) + bean.getX();
                    graphics.drawString(bean.getContent(), startX, ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3  );
                }
            }
            // 图片
            if("2".equals(bean.getType())) {
                // 设置文字的字体,大小
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("fileId", bean.getContent());
                FilePO filePO = iFileService.getPO(params);
                if(filePO != null ) {
                    File file = new File(filePO.getFilePath());
                    if(file.exists()) {
                        // 对图片进行裁剪
                        Image img = thumbnail(file, bean.getWidth(), bean.getHeight());
                        // 将图片放入模板中
                        graphics.drawImage(img, bean.getX(), bean.getY(),null);
                    }
                }
            }
            // 条形码
            if("3".equals(bean.getType())) {
                BufferedImage barcode = BarCodeUtils.getBarcode(bean.getContent(), bean.getWidth(), bean.getHeight(), new Color(bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]));
                if(barcode != null) {
                    // 将条形码放入模板中
                    graphics.drawImage(barcode, bean.getX(), bean.getY(),null);
                }
            }
            // 二维码
            if("4".equals(bean.getType())) {
                BufferedImage rq = BarCodeUtils.getRQ(bean.getContent(), bean.getWidth(), bean.getHeight(), new Color(bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]));
                if(rq != null) {
                    // 将二维码放入模板中
                    graphics.drawImage(rq, bean.getX(), bean.getY(),null);
                }
            }
            // 地图坐标
            if("5".equals(bean.getType())) {
                BufferedImage map = BaiDuMapUtil.getImage(bean.getContent(), bean.getWidth(), bean.getHeight());
                if(map != null) {
                    // 将地图放入模板中
                    graphics.drawImage(map, bean.getX(), bean.getY(), null);
                }
            }
            // 小程序二维码
            if("6".equals(bean.getType())) {
                BufferedImage weiXinImage = WeiXinBarCodeUtils.getBarCodeImage(bean.getContent(),bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]);
                if(weiXinImage != null) {
                    // 对二维码压缩裁剪
                    Image img = thumbnailBufferdImage(weiXinImage, bean.getWidth(), bean.getHeight());
                    // 将头像放入模板中
                    graphics.drawImage(img, bean.getX(), bean.getY(),null);
                }
            }
        }
        return image;
    }

    public List<String> createText(Integer width, Integer fontSize, String content) {
        char[] c = content.toCharArray();
        double count = 0;
        double rowCount = width / fontSize;
        List<String> contentList = new ArrayList<String>();
        StringBuffer rowContent = new StringBuffer();
        for(int i = 0; i < c.length; i ++) {
            String len = Integer.toBinaryString(c[i]);
            rowContent.append(c[i]);

            if(len.length() > 8) {
                count++;
            }else{
                count = (count + 0.5);
            }

            if((count+1) >= rowCount || i == c.length-1 || '\n' == c[i]) {
                count = 0;
                contentList.add(rowContent.toString().replace("\n", ""));
                rowContent.setLength(0);
            }
        }
        return contentList;
    }

    @Override
    public String createImage(List<CreateImageBean> list, File backFile, int backWidth, int backHeight) throws IOException {
       /* // 创建画布
        BufferedImage image = new BufferedImage(backWidth, backHeight, Image.SCALE_SMOOTH);
        // 得到图片操作对象
        Graphics2D graphics = image.createGraphics();

        //消除文字锯齿
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //消除图片锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);*/
        // 创建画布
        BufferedImage image = new BufferedImage(backWidth, backHeight, Image.SCALE_SMOOTH);
        // 得到图片操作对象
        Graphics2D imageGraphics = image.createGraphics();

        //消除文字锯齿
        imageGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //消除图片锯齿
        imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        image = imageGraphics.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT);
        Graphics graphics = image.getGraphics();

        // 对底图进行裁剪
        Image backImg = thumbnail(backFile, backWidth + 1, backHeight);
        // 将底图放入模板中
        graphics.drawImage(backImg, 0, 0,null);
        for (CreateImageBean bean : list) {
            System.out.println(bean.toString());
            // 不是图片 . 需要转换字体 / 颜色 / 大小
            if (!"2".equals(bean.getType())) {
                // 设置文字的颜色为黑色
                graphics.setColor(new Color(bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]));
                // 设置文字的字体,大小
                Font font = new Font(bean.getFontFamily() , bean.getFontBold(), bean.getFontSize());
                graphics.setFont(font);
            }
            // 文字
            if("1".equals(bean.getType())) {
                // 居中, 超出范围以后截取
                if("2".equals(bean.getCenter())) {
                    // 超出一行的内容剔除掉
                    String content = getTextSplice(bean.getContent(),  bean.getFontSize(), bean.getWidth());
                    bean.setContent(content);

                    int count = getTextCount(bean.getContent(), bean.getFontSize());
                    int startX = ((bean.getWidth()) - count) / 2;
                    // 将文字放入模板中
                    graphics.drawString(bean.getContent(), startX +  bean.getX(), ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3  ); // + ( bean.getHeight() - ( bean.getFontSize() / 2) )
                // 左侧, 超出范围以后会自动的换行
                }else if("1".equals(bean.getCenter())){
                    // 将文字放入模板中
                    List<String> rowList = createText(bean.getWidth(), bean.getFontSize(), bean.getContent());
                    int index = 1;
                    for (String fontContent : rowList) {
                        /**
                         * 对内容进行封装换行
                         */
                        int y =  bean.getY()  + (    (  (    ( bean.getHeight() / 2) + ( bean.getFontSize() / 2)   ) - 3 ) * index );
                        graphics.drawString(fontContent, bean.getX(), y);
                        index++;
                    }
                // 右侧,超出范围以后会向左延升
                }else{
                    int totalSize = getTextCount(bean.getContent(), bean.getFontSize());
                    int startX = (bean.getWidth() - totalSize) + bean.getX();
                    graphics.drawString(bean.getContent(), startX, ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3  );
                }
              /*  // 居中
                if("2".equals(bean.getCenter())) {
                    int count = getTextCount(bean.getContent(), bean.getFontSize());
                    int startX = ((bean.getWidth()) - count) / 2;
                    // 将文字放入模板中
                    graphics.drawString(bean.getContent(), startX +  bean.getX(), ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3  ); // + ( bean.getHeight() - ( bean.getFontSize() / 2) )
                // 左侧
                }else if("1".equals(bean.getCenter())){
                    // 将文字放入模板中
                    List<String> rowList = createText(bean.getWidth(), bean.getFontSize(), bean.getContent());
                    int index = 1;
                    for (String fontContent : rowList) {
                        *//**
                         * 对内容进行封装换行
                         *//*
                        int y =  bean.getY()  + (    (  (    ( bean.getHeight() / 2) + ( bean.getFontSize() / 2)   ) - 3 ) * index );
                        graphics.drawString(fontContent, bean.getX(), y);
                        index++;
                    }
                // 右侧
                }else{
                    int totalSize = getTextCount(bean.getContent(), bean.getFontSize());
                    int startX = (bean.getWidth() - totalSize) + bean.getX();
                    graphics.drawString(bean.getContent(), startX, ( bean.getY()  + ( bean.getHeight() / 2) + ( bean.getFontSize() / 2) ) - 3  );
                }*/
            }
            // 图片
            if("2".equals(bean.getType())) {
                // 设置文字的字体,大小
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("fileId", bean.getContent());
                FilePO filePO = iFileService.getPO(params);
                if(filePO != null ) {
                    File file = new File(filePO.getFilePath());
                    if(file.exists()) {
                        // 对图片进行裁剪
                        Image img = thumbnail(file, bean.getWidth(), bean.getHeight());
                        // 将图片放入模板中
                        graphics.drawImage(img, bean.getX(), bean.getY(),null);
                    }
                }
            }
            // 条形码
            if("3".equals(bean.getType())) {
                BufferedImage barcode = BarCodeUtils.getBarcode(bean.getContent(), bean.getWidth(), bean.getHeight(), new Color(bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]));
                if(barcode != null ) {
                    // 将条形码放入模板中
                    graphics.drawImage(barcode, bean.getX(), bean.getY(),null);
                }
            }
            // 二维码
            if("4".equals(bean.getType())) {
                BufferedImage rq = BarCodeUtils.getRQ(bean.getContent(), bean.getWidth(), bean.getHeight(), new Color(bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]));
                if(rq != null ) {
                    // 将二维码放入模板中
                    graphics.drawImage(rq, bean.getX(), bean.getY(),null);
                }
            }
            // 地图坐标
            if("5".equals(bean.getType())) {
                BufferedImage map = BaiDuMapUtil.getImage(bean.getContent(), bean.getWidth(), bean.getHeight());
                if(map != null ) {
                    // 将地图放入模板中
                    graphics.drawImage(map, bean.getX(), bean.getY(), null);
                }
            }
            // 小程序二维码
            if("6".equals(bean.getType())) {
                BufferedImage weiXinImage = WeiXinBarCodeUtils.getBarCodeImage(bean.getContent(),bean.getColor()[0],bean.getColor()[1],bean.getColor()[2]);
                if(weiXinImage != null ) {
                    // 对二维码压缩裁剪
                    Image img = thumbnailBufferdImage(weiXinImage, bean.getWidth(), bean.getHeight());
                    // 将头像放入模板中
                    graphics.drawImage(img, bean.getX(), bean.getY(),null);
                }
            }
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        // 对字节数组Base64编码
        Base64 base = new Base64();
        String base64 = base.encodeToString(stream.toByteArray());
        return "data:image/png;base64," + base64;
        // createImage("D:\\test1.png", image);
//        String fileName = UUIDUtil.get32UUID() + ".png";
//        String baseUploadPath = this.fileProperties.getUploadPath();
//        if (StringUtils.isBlank(baseUploadPath)) {
//            throw new SystemException("上传路径未配置");
//        }
//        StringBuilder filePath = new StringBuilder();
//        if (!baseUploadPath.endsWith(File.separator)) {
//            filePath.append(baseUploadPath).append(File.separator);
//        } else {
//            filePath.append(baseUploadPath);
//        }
//        filePath.append("images");
//        String days = DateUtil.getDays();
//        filePath.append(File.separator).append(days).append(File.separator);
//        File file = new File(filePath.toString());
//        if(!file.exists()) {
//            file.mkdirs();
//        }
//        String pathUrl = "images/" + days + "/" + fileName;
//        filePath.append(fileName);
//        createImage(filePath.toString() , image);
//        FileVO fileVO = new FileVO();
//        fileVO.setFileName(fileName);
//        fileVO.setFileType("png");
//        fileVO.setFileUrl(pathUrl);
//        File localFile = new File(filePath.toString());
//        fileVO.setFileSize(localFile.length());
//        fileVO.setFilePath(filePath.toString());
//        String fileId = iFileService.saveFileByUserId("1", fileVO);
//        return fileId;
    }

    /**
     * 获取文件类型
     *
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        String[] names = fileName.split("\\.");
        if (names != null) {
            return names[names.length - 1].toLowerCase();
        }
        return "";
    }

    @Override
    public String buildingPictures(String picturesTemplateCode, Map<String, String> bean) throws Exception {
        PicturesTemplateDTO dto = picturesTemplateService.getPicturesTemplateByCode(picturesTemplateCode);
        List<PicturesTemplateAreaDTO> areaList = picturesTemplateAreaService.getPicturesTemplateAreaByPicturesTemplateId(dto.getPicturesTemplateId());
        List<CreateImageBean> list = new ArrayList<CreateImageBean>();
        for (PicturesTemplateAreaDTO areaDto : areaList) {
            String content = "2".equals(areaDto.getTemplateAreaServerLink()) ? areaDto.getTemplateAreaFile() : areaDto.getTemplateAreaFontValue();
            String index = areaDto.getTemplateAreaSource();
            /**
             * 1位占位区域 , 2为需要填充的区域
             */
            if("2".equals(areaDto.getTemplateAreaType())){
                if(bean != null) {
                    content = "";
                    for (Map.Entry<String, String> key : bean.entrySet()) {
                        if (key.getValue() != null && index.equals(key.getKey())) {
                            if (key.getValue().getClass() == String.class) {
                                content = key.getValue();
                            }
                        }
                    }
                }
            }
            CreateImageBean createImageBean = new CreateImageBean();
            if("1".equals(areaDto.getTemplateAreaServerLink())){
                /**
                 * 是否控制长度
                 */
                if(areaDto.getTemplateAreaFontLength() > 0) {
                    char[] c = content.toCharArray();
                    double countLength = 0;
                    for(int i = 0; i < c.length; i ++) {
                        String len = Integer.toBinaryString(c[i]);
                        if(len.length() > 8) {
                            countLength++;
                        }else{
                            countLength = (countLength + 0.5);
                        }
                    }
                    if(countLength > areaDto.getTemplateAreaFontLength()) {
                        throw new SaveException(areaDto.getPicturesTemplateTitle() + "超出长度");
                    }
                }
                createImageBean.setFontBold(Integer.valueOf(areaDto.getTemplateAreaFontBold()));
                createImageBean.setFontFamily(areaDto.getTemplateAreaFontFamily());
                createImageBean.setFontSize(Integer.valueOf(areaDto.getTemplateAreaFontSize()));
                createImageBean.setCenter(areaDto.getTemplateAreaFontCenter());
            }
            if(!"2".equals(areaDto.getTemplateAreaServerLink())){
                String newColor = areaDto.getTemplateAreaFontColor().substring(4, areaDto.getTemplateAreaFontColor().length() -1);
                String[] colorArr = newColor.split(",");
                int[] colorIntArr = new int[4];
                for (int i = 0; i < colorArr.length; i++) {
                    colorIntArr[i] = Integer.valueOf(colorArr[i].trim());
                }
                createImageBean.setColor(colorIntArr);
            }
            createImageBean.setContent(content);
            createImageBean.setType(areaDto.getTemplateAreaServerLink());
            createImageBean.setHeight(areaDto.getTemplateAreaHeight().intValue());
            createImageBean.setWidth(areaDto.getTemplateAreaWidth().intValue());
            createImageBean.setX(areaDto.getTemplateAreaLeft().intValue());
            createImageBean.setY(areaDto.getTemplateAreaTop().intValue());
            list.add(createImageBean);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("fileId", dto.getPicturesTemplateBackgroundImage());
        FilePO filePO = iFileService.getPO(params);
        if(filePO == null) {
            throw new Exception("背景图片丢失, 无法生成");
        }
        File backFile = new File(filePO.getFilePath());
        return createImage(list, backFile, dto.getPicturesTemplateWidth().intValue(), dto.getPicturesTemplateHeight().intValue());
    }

    @Override
    public String buildingPictures(String picturesTemplateCode, Object bean) throws Exception {
        PicturesTemplateDTO dto = picturesTemplateService.getPicturesTemplateByCode(picturesTemplateCode);
        List<PicturesTemplateAreaDTO> areaList = picturesTemplateAreaService.getPicturesTemplateAreaByPicturesTemplateId(dto.getPicturesTemplateId());
        List<CreateImageBean> list = new ArrayList<CreateImageBean>();
        for (PicturesTemplateAreaDTO areaDto : areaList) {
            String content = "2".equals(areaDto.getTemplateAreaServerLink()) ? areaDto.getTemplateAreaFile() : areaDto.getTemplateAreaFontValue();
            String index = areaDto.getTemplateAreaSource();
            /**
             * 1位占位区域 , 2为需要填充的区域
             */
            if("2".equals(areaDto.getTemplateAreaType())){
                if(bean != null) {
                    Field[] arr = bean.getClass().getDeclaredFields();
                    for (Field key : arr) {
                        key.setAccessible(true);
                        if (index.equals(key.getName())) {
                            if (key.getType() == String.class) {
                                if(key.get(bean) != null) {
                                    if(!StringUtil.isEmpty(key.get(bean).toString())) {
                                        content = key.get(bean).toString();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            CreateImageBean createImageBean = new CreateImageBean();
            if("1".equals(areaDto.getTemplateAreaServerLink())){
                /**
                 * 是否控制长度
                 */
                if(areaDto.getTemplateAreaFontLength() > 0) {
                    char[] c = content.toCharArray();
                    double countLength = 0;
                    for(int i = 0; i < c.length; i ++) {
                        String len = Integer.toBinaryString(c[i]);
                        if(len.length() > 8) {
                            countLength++;
                        }else{
                            countLength = (countLength + 0.5);
                        }
                    }
                    if(countLength > areaDto.getTemplateAreaFontLength()) {
                        throw new SaveException(areaDto.getPicturesTemplateTitle() + "超出长度");
                    }
                }
                createImageBean.setFontBold(Integer.valueOf(areaDto.getTemplateAreaFontBold()));
                createImageBean.setFontFamily(areaDto.getTemplateAreaFontFamily());
                createImageBean.setFontSize(Integer.valueOf(areaDto.getTemplateAreaFontSize()));
                createImageBean.setCenter(areaDto.getTemplateAreaFontCenter());
            }
            if(!"2".equals(areaDto.getTemplateAreaServerLink())){
                String newColor = areaDto.getTemplateAreaFontColor().substring(4, areaDto.getTemplateAreaFontColor().length() -1);
                String[] colorArr = newColor.split(",");
                int[] colorIntArr = new int[4];
                for (int i = 0; i < colorArr.length; i++) {
                    colorIntArr[i] = Integer.valueOf(colorArr[i].trim());
                }
                createImageBean.setColor(colorIntArr);
            }
            createImageBean.setContent(content);
            createImageBean.setType(areaDto.getTemplateAreaServerLink());
            createImageBean.setHeight(areaDto.getTemplateAreaHeight().intValue());
            createImageBean.setWidth(areaDto.getTemplateAreaWidth().intValue());
            createImageBean.setX(areaDto.getTemplateAreaLeft().intValue());
            createImageBean.setY(areaDto.getTemplateAreaTop().intValue());
            list.add(createImageBean);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("fileId", dto.getPicturesTemplateBackgroundImage());
        FilePO filePO = iFileService.getPO(params);
        if(filePO == null) {
            throw new Exception("背景图片丢失, 无法生成");
        }
        File backFile = new File(filePO.getFilePath());
        return createImage(list, backFile, dto.getPicturesTemplateWidth().intValue(), dto.getPicturesTemplateHeight().intValue());
    }

    /**
     * 将超出的文字截取掉
     * @param content
     * @param fontSize
     * @return
     */
    private String getTextSplice(String content, int fontSize, int width) {
        char[] c = content.toCharArray();
        double count = 0;
        int index = 0;
        for(int i = 0; i < c.length; i ++) {
            String len = Integer.toBinaryString(c[i]);
            if(len.length() > 8) {
                double outSize = ( ( (count + 1 ) * (fontSize + 3) )  - width ) ;
                if(outSize < 0.0) {
                    count++;
                    index++;
                }
            }else{
                double outSize = ( ( (count + 0.5 ) * ((fontSize + 3) / 2)) - width );
                if(outSize < 0.0) {
                    count = (count + 0.5);
                    index++;
                }
            }
        }
        if(content.length() > index) {
            return content.substring(0, index + 1);
        }else {
            return content;
        }
    }

    /**
     * 获得文字占用长度
     * @param content
     * @param fontSize
     * @return
     */
    private int getTextCount(String content, int fontSize) {
        char[] c = content.toCharArray();
        double count = 0;
        for(int i = 0; i < c.length; i ++) {
            String len = Integer.toBinaryString(c[i]);
            if(len.length() > 8) {
                count++;
            }else{
                count = (count + 0.5);
            }
        }
        return (int) (fontSize * count);
    }

    /**
     * 将image对象存储到本地
     * @Title : createImage
     * @功能描述 : TODO
     * @设定文件 : @param fileLocation 本地路径
     * @设定文件 : @param image 图片对象
     * @返回类型 : void
     * @throws :
     */
    private static void createImage(String fileLocation, BufferedImage image) {
        try {
            String formatName = fileLocation.substring(fileLocation.lastIndexOf(".") + 1);
            ImageIO.write(image, formatName , new File(fileLocation));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图片压缩-按照固定宽高原图压缩
     * @Title : thumbnail
     * @功能描述 : TODO
     * @设定文件 : @param img 本地图片地址
     * @设定文件 : @param width 图片宽度
     * @设定文件 : @param height 图片高度
     * @设定文件 : @return
     * @设定文件 : @throws IOException
     * @返回类型 : Image
     * @throws :
     */
    private static Image thumbnailBufferdImage(BufferedImage BI, int width, int height) throws IOException {
        Image image = BI.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return image;
    }

    /**
     * 图片压缩-按照固定宽高原图压缩
     * @Title : thumbnail
     * @功能描述 : TODO
     * @设定文件 : @param img 本地图片地址
     * @设定文件 : @param width 图片宽度
     * @设定文件 : @param height 图片高度
     * @设定文件 : @return
     * @设定文件 : @throws IOException
     * @返回类型 : Image
     * @throws :
     */
    private static Image thumbnail(File img, int width, int height) throws IOException {
        BufferedImage BI = ImageIO.read(img);
        Image image = BI.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return image;
    }

}