package com.ssj.service.sys.poster.service.impl;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

import javax.imageio.ImageIO;

import com.ssj.bean.sys.poster.domain.PosterActivityJoin;
import com.ssj.dao.sys.poster.dao.*;
import com.ssj.framework.weixin.news.bean.Template;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ssj.bean.sys.poster.domain.PosterActivity;
import com.ssj.bean.sys.poster.domain.PosterJoin;
import com.ssj.bean.sys.poster.domain.PosterTemplate;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.framework.weixin.util.ImageUtil;
import com.ssj.framework.weixin.util.ImgBean;
import com.ssj.service.sys.poster.service.PosterJoinService;

@Service
@Transactional
public class PosterJoinServiceImpl extends BaseServiceImpl<PosterJoin, String> implements PosterJoinService {

	private  Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Autowired
    private PosterJoinDao dao;
    
    @Autowired
    private PosterActivityDao posterActivityDao;
    
    @Autowired
    private PosterTemplateDao posterTemplateDao;

    @Autowired
    private PosterActivityJoinDao activityJoinDao;
    
    @Autowired
    private PosterQueryDao posterQueryDao;
    
    @Override
	public PagingAndSortingRepository<PosterJoin, String> getDao() {
		return dao;
	}

	@Override
	public Page<Map<String, Object>> findJoinByPage(Map<String, Object> params, Pageable initPage) {
		return posterQueryDao.findJoinByPage(params, initPage);
	}

	@Override
	public PosterJoin generatePosterImg(PosterJoin posterJoin,String activityId,String templateId ) {
		PosterTemplate posterTemplate=posterTemplateDao.getOne(templateId);
		
		if(StringUtils.isEmpty(posterJoin.getLogoImg()) || StringUtils.isEmpty(posterJoin.getQrcodeImg1())) {
			return posterJoin;
		}
		if(StringUtils.isNotEmpty(posterTemplate.getQrcodePosition2()) && StringUtils.isEmpty(posterJoin.getQrcodeImg2())) {
			return posterJoin;
		}
		String activityName = posterActivityDao.getOne(activityId).getName();
		String posterImg=runGeneratePosterImg(posterTemplate, posterJoin,activityName);
		if(StringUtils.isNotEmpty(posterImg)) {
			//查询是否是存在的数据，存在就更新
			PosterActivityJoin join = activityJoinDao.findOneByAnyP(posterJoin.getId(),activityId,templateId);
			if(join == null){join = new PosterActivityJoin();}
			join.setJoinId(posterJoin.getId());
			join.setCreateTime(new Date());
			join.setTemplateId(templateId);
			join.setActivityId(activityId);
			join.setPosterImg(posterImg);
			activityJoinDao.save(join);
		}
		return posterJoin;
	}
	
	
	public static void main(String[] args) {
		
		PosterTemplate posterTemplate=new PosterTemplate();
		posterTemplate.setBackImg("3-1.png");
		posterTemplate.setAddressPosition("307;1622;150");
		posterTemplate.setNumberPosition("307;1580;150");
		posterTemplate.setLogoPosition("64;63");
		posterTemplate.setQrcodePosition1("155;155;110;1511");
		posterTemplate.setFontColor("59;63;66;1");
		posterTemplate.setFontSize(28);
		posterTemplate.setBackLength(1000);
		//posterTemplate.setQrcodePosition2("123;123;300;505");

		PosterJoin posterJoin=new PosterJoin();
		posterJoin.setLogoImg("logo.png");
		posterJoin.setQrcodeImg1("qr1.png");
		posterJoin.setName("活动");
		posterJoin.setPhone("吴老师 13265096161");
		posterJoin.setAddress("广州市海珠区罗马家园中盛路拜庭二期04-06 商铺");

//		String url=runGeneratePosterImg(posterTemplate, posterJoin,"测试");
//		System.out.println(url);


	}
	
    
	public  String runGeneratePosterImg(PosterTemplate posterTemplate,PosterJoin posterJoin,String activityName) {
    	try {
    		String savePath =PropertiesUtil.getValue("file_save_path");
    		String posterPath ="/poster/";
    		//String savePath="E:";
	    	// 按/poster/活动/机构/海报 保存
	    	String save_path = savePath+posterPath+activityName+"/"+posterJoin.getName()+"/";
	    	String target_path =  save_path+IdWorker.generateId() + ".png";
	    	// 创建文件夹
	    	File f = new File(save_path);
	    	if (!f.exists()) {f.mkdirs();}
	    	 
	    	//读取模板
	    	BufferedImage source_template = ImgBean.loadImageLocal(savePath+posterTemplate.getBackImg());
	    	
	    	//合成logo
	    	String[] logoPositions=posterTemplate.getLogoPosition().split(";");
	    	BufferedImage logoImage = ImageIO.read(new File(savePath+posterJoin.getLogoImg()));
	    	BufferedImage target_template=ImgBean.modifyImagetogeter(logoImage, source_template,Integer.parseInt(logoPositions[0]),Integer.parseInt(logoPositions[1]));
	    	if(StringUtils.isNotEmpty(posterTemplate.getLogoPosition2()) && StringUtils.isNotEmpty(posterJoin.getLogoImg2())){
				//合成logo2
				logoImage = ImageIO.read(new File(savePath+posterJoin.getLogoImg2()));
				target_template=ImgBean.modifyImagetogeter(logoImage, target_template,Integer.parseInt(logoPositions[2]),Integer.parseInt(logoPositions[3]));
			}

	    	//合成二维码1
	    	String[] qrcodePositions=posterTemplate.getQrcodePosition1().split(";");
	       	String code=save_path+IdWorker.generateId()+ ".png";
	     	ImageUtil.resizeImg(savePath+posterJoin.getQrcodeImg1(), code, Integer.parseInt(qrcodePositions[0]),  Integer.parseInt(qrcodePositions[1]), 1.0f);
	     	BufferedImage codeImage = ImageIO.read(new File(code));
	     	int w1 = codeImage.getWidth();
	        int h1 = codeImage.getHeight();
	        BufferedImage codeOutput = new BufferedImage(w1, h1,BufferedImage.TYPE_INT_ARGB);
	        Graphics2D g3 = codeOutput.createGraphics();
	        g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
	        g3.setColor(Color.WHITE);
	        g3.fill(new RoundRectangle2D.Float(0, 0, w1, h1, 0,0));
	        g3.setComposite(AlphaComposite.SrcAtop);
	        g3.drawImage(codeImage, 0, 0, null);
	        g3.dispose();
	    	ImgBean.modifyImagetogeter(codeOutput, target_template,Integer.parseInt(qrcodePositions[2]),Integer.parseInt(qrcodePositions[3]));
			logger.error("生成海报3-1[{}]",target_path);
	    	//合成后删除图片
			File code1File = new File(code);
			code1File.delete();
	    	//合成二维码2
	    	if(StringUtils.isNotEmpty(posterTemplate.getQrcodePosition2()) && StringUtils.isNotEmpty(posterJoin.getQrcodeImg2())) {
		    	qrcodePositions=posterTemplate.getQrcodePosition2().split(";");
		       	code=save_path+IdWorker.generateId()+ ".png";
		     	ImageUtil.resizeImg(savePath+posterJoin.getQrcodeImg1(), code, Integer.parseInt(qrcodePositions[0]),  Integer.parseInt(qrcodePositions[1]), 1.0f);
		     	codeImage = ImageIO.read(new File(code));
		     	w1 = codeImage.getWidth();
		        h1 = codeImage.getHeight();
		        codeOutput = new BufferedImage(w1, h1,BufferedImage.TYPE_INT_ARGB);
		        g3 = codeOutput.createGraphics();
		        g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		        g3.setColor(Color.WHITE);
		        g3.fill(new RoundRectangle2D.Float(0, 0, w1, h1, 0,0));
		        g3.setComposite(AlphaComposite.SrcAtop);
		        g3.drawImage(codeImage, 0, 0, null);
		        g3.dispose();
		    	ImgBean.modifyImagetogeter(codeOutput, target_template,Integer.parseInt(qrcodePositions[2]),Integer.parseInt(qrcodePositions[3]));

				//合成后删除图片
				File code1File2 = new File(code);
				code1File2.delete();
	    	}
			logger.error("生成海报3-2[{}]",target_path);
	    	//设置字体大小
			int fontSize = posterTemplate.getFontSize();
            Font font = new Font("黑体", Font.BOLD, fontSize);

	    	//String[] colorRgba = posterTemplate.getFontColor().split(";");
			//Color color = new Color(Integer.parseInt(colorRgba[0]),Integer.parseInt(colorRgba[1]) ,Integer.parseInt(colorRgba[2]) ,Integer.parseInt(colorRgba[3]));
            Color color = new Color(0,0,0);
	    	//合成联系人 x;y
	    	String[] numberPositions=posterTemplate.getNumberPosition().split(";");
	    	String phone = "联系人："+posterJoin.getPhone();
	    	int leftX = Integer.parseInt(numberPositions[0]);
	    	int topY = Integer.parseInt(numberPositions[1]);
	    	if(posterJoin.getPhone().contains("/n")){
	    		String[] phones = phone.split("/n");
				ImgBean.modifyImage(target_template,phones[0],leftX,topY,color,font);
				phone = phones[1];
				leftX = leftX+fontSize*4;
				topY = topY+fontSize+2;
			}
            //ImgBean.modifyImage(target_template,"联系人："+posterJoin.getPhone(),leftX,topY,new Color(240,240,240),new Font("黑体", Font.PLAIN, 28));
	    	ImgBean.modifyImage(target_template,phone,leftX,topY,color,font);
	    	//合成地址 x;y;rx
	    	//长500的，最多33个字，500/33=15px  (33-Address.le)/2=?
	    	String[] addressPositions=posterTemplate.getAddressPosition().split(";");
            int leftAddress = Integer.parseInt(addressPositions[0]);
            int topAddress = Integer.parseInt(addressPositions[1]);
            int rightAddress = Integer.parseInt(addressPositions[2]);
	    	int maxNum = (posterTemplate.getBackLength()-leftAddress-rightAddress)/fontSize;
	    	String address = "地址："+posterJoin.getAddress();
	    	//换行
	    	if(address.length()>maxNum){
                ImgBean.modifyImage(target_template,address.substring(0,maxNum),leftAddress,topAddress,color,font);
                address = address.substring(maxNum);
                leftAddress = leftAddress+fontSize*3;
                topAddress = topAddress+fontSize+2;
            }
	    	ImgBean.modifyImage(target_template,address,leftAddress,topAddress,color,font);

	    	//生成海报
	    	ImgBean.writeImageLocal(target_path,  source_template);
	    	return target_path.replaceAll(savePath, "");
	    	
    	} catch (Exception e) {
    		e.printStackTrace();
		}
    	return null;
    }
	
	
	
 
}
