package com.ssj.service.weixin.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.weixin.message.custom.WxQRCode;
import com.ssj.bean.weixin.message.custom.WxQRCodeInfo;
import com.ssj.bean.weixin.message.custom.WxQRCodeScene;
import com.ssj.bean.weixin.user.domain.QrCode;
import com.ssj.dao.weixin.user.dao.QrCodeDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.framework.weixin.util.ImageUtil;
import com.ssj.framework.weixin.util.NewsUtil;
import com.ssj.service.weixin.user.service.QrCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class QrCodeServiceImpl extends BaseServiceImpl<QrCode, String> implements QrCodeService {
	 private static Logger log = LoggerFactory.getLogger(QrCodeServiceImpl.class);
	
	@Autowired
	private QrCodeDao qrcodeDao;
	
	@Autowired
	private TokenManager  tokenManager;
	@Override
	public PagingAndSortingRepository<QrCode, String> getDao() {
		return qrcodeDao;
	}

	@Override
	public QrCode generateQrcode(String userId) {
		QrCode qrcode=qrcodeDao.findByObjectId(userId);
			if(qrcode==null){
				qrcode = new  QrCode();
				qrcode.setType("QR_LIMIT_SCENE");//设置为永久的二维码
				String sceneid ="forever";
				Integer numsceneid=tokenManager.get(sceneid, Integer.class);
				if(numsceneid==null){
					numsceneid=11000;
				}else{
					numsceneid++;
				}
				tokenManager.set(sceneid, numsceneid,365 * 24 * 3600);
				qrcode.setObjectId(userId);//这里是校长的，老师的二维码
				qrcode.setParentId(userId);//永久的二维码 objectId=userId
				qrcode.setSceneId(numsceneid.toString());//永久二维码时最大值为100000（目前参数只支持1--100000）
				try {
					com.ssj.bean.weixin.message.custom.WxQRCode qRCode =new  com.ssj.bean.weixin.message.custom.WxQRCode();
				        qRCode.setExpire_seconds(qrcode.getExpireSeconds());
				        qRCode.setAction_name(qrcode.getType());
				        WxQRCodeInfo action_info   =new  WxQRCodeInfo();
				        WxQRCodeScene scene  =new   WxQRCodeScene();
				        scene.setScene_id(qrcode.getSceneId());
				        action_info.setScene(scene);
				        qRCode.setAction_info(action_info);
				        log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
				        JSONObject jsonObject=  NewsUtil.ticket(tokenManager.getSSJAccessToken(), qRCode);
				        if(null != jsonObject){
				        	log.info("腾讯服务器申请永久二维码返回json，"+jsonObject.toString());
				        	qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
				        	qrcode.setUrl(jsonObject.getString("url"));//生成URL
				        	qrcode.setQrcodeTime(new Date());//生成时间
							String file_path = (String) SystemResourceLocator.getValue("file_save_path");
								String fPath = "/userqrcode" +  DateHelper.formatDateByFormat(new Date(), "yyyyMMdd");
								if (!fPath.endsWith("/")) {
									fPath += "/";
								}
								File f = new File(file_path + fPath);
								if (!f.exists()) {
									f.mkdirs();
								}
								String fPathId = fPath + qrcode.getObjectId() + ".jpg";
								qrcode.setQrcodeUrl(fPathId);
					        try {
								BarcodeFactory.bookencode(qrcode.getUrl(), file_path + qrcode.getQrcodeUrl(), 400, 400);
							} catch (Exception e) {
								e.printStackTrace();
							}
				        }
					this.save(qrcode);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		return qrcode;
	}
	@Override
	public QrCode saveQrcode(String objectId,String parentId) {
		QrCode qrcode=qrcodeDao.findByObjectIdAndParentId(objectId, parentId);
		if(qrcode==null){
			qrcode=insertQrcode(objectId,qrcodeDao.count()+1,parentId);
		}
		return qrcode;
	}
	private QrCode insertQrcode(String objectId,long sceneId ,String parentId) {
		QrCode	qrcode = new  QrCode();
		qrcode.setType("QR_LIMIT_SCENE");//设置为永久的二维码
		//qrcode.setExpireSeconds("2592000");//时间最大为30天这里为30天
		qrcode.setObjectId(objectId);
		qrcode.setSceneId(sceneId+"");
		qrcode.setParentId(parentId);
		try {
			qrcode=this.ticket(qrcode);//下载生成二维码url 合成二维码
			this.save(qrcode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return qrcode;
	}
	
	@Override
	public QrCode saveQrcode(String objectId,String parentId,String headUrl,String userName) {
		QrCode qrcode=qrcodeDao.findByObjectIdAndParentId(objectId, parentId);
			if(qrcode==null){
				qrcode=insertQrcode(objectId,qrcodeDao.count()+1,parentId, headUrl, userName);
			}
		return qrcode;
	}
	
	private QrCode insertQrcode(String objectId,long sceneId ,String parentId,String headUrl,String userName) {
		QrCode	qrcode = new  QrCode();
		qrcode.setType("QR_LIMIT_SCENE");//设置为永久的二维码
		//qrcode.setExpireSeconds("2592000");//时间最大为30天这里为30天
		qrcode.setObjectId(objectId);
		qrcode.setSceneId(sceneId+"");
		qrcode.setParentId(parentId);
		try {
			qrcode=this.subTicket(qrcode,headUrl,userName);//下载生成二维码url 合成二维码
			this.save(qrcode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return qrcode;
	}
	
	
	private  QrCode  subTicket (QrCode qrcode,String headUrl,String userName) throws Exception{
	    com.ssj.bean.weixin.message.custom.WxQRCode qRCode =new  com.ssj.bean.weixin.message.custom.WxQRCode();
        qRCode.setExpire_seconds(qrcode.getExpireSeconds());
        qRCode.setAction_name(qrcode.getType());
        WxQRCodeInfo action_info   =new  WxQRCodeInfo();
        WxQRCodeScene scene  =new   WxQRCodeScene();
        scene.setScene_id(qrcode.getSceneId());
        action_info.setScene(scene);
        qRCode.setAction_info(action_info);
        log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
        JSONObject jsonObject=  NewsUtil.ticket(tokenManager.getSSJAccessToken(), qRCode);
        if(null != jsonObject){
        	qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
        	qrcode.setUrl(jsonObject.getString("url"));//生成URL
        	log.info("腾讯服务器申请二维码生成URL，"+qrcode.getUrl());
        	log.info("腾讯服务器申请二维码生成ticket，"+qrcode.getTicket());
        	log.info("腾讯服务器申请二维码返回json，"+jsonObject.toString());
        	qrcode.setQrcodeTime(new Date());//生成时间
        	String file_path = (String) SystemResourceLocator.getValue("file_save_path");
        		String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
        		if (!fPath.endsWith("/")) {
        			fPath += "/";
        		}
        		File  f = new File(file_path+fPath);
        		if (!f.exists()) {
        			f.mkdirs();
        		}
        		fPath = fPath + UUID.randomUUID() + ".jpg";
        		qrcode.setQrcodeUrl(fPath);
        		BarcodeFactory.encode(qrcode.getUrl(),file_path+"/images/favicon.png",file_path+qrcode.getQrcodeUrl(),220, 220, true);
        		log.info("二维码合成返回，"+fPath);
        		String guanzhuUrl =ImageUtil.compositeSubImg("/subimg.jpg", headUrl, fPath, userName);
        		log.info("打卡界面返回，"+guanzhuUrl);
        		qrcode.setGuanzhuUrl(guanzhuUrl);
        }
     return   qrcode;
}
	@Override
	public QrCode saveQrcode(String objectId,String parentId,String headUrl,String userName,String posterUrl) {
		QrCode qrcode=qrcodeDao.findByObjectIdAndParentId(objectId, parentId);
		if(qrcode==null){
			qrcode=insertQrcode(objectId,qrcodeDao.count()+1,parentId, headUrl, userName, posterUrl);
		}
		return qrcode;
	}

	private QrCode insertQrcode(String objectId,long sceneId ,String parentId,String headUrl,String userName,String posterUrl) {
		QrCode	qrcode = new  QrCode();
		qrcode.setType("QR_LIMIT_SCENE");//设置为永久的二维码
		//qrcode.setExpireSeconds("2592000");//时间最大为30天这里为30天
		qrcode.setObjectId(objectId);
		qrcode.setSceneId(sceneId+"");
		qrcode.setParentId(parentId);
		try {
			qrcode=this.subTicket(qrcode,headUrl,userName,posterUrl);//下载生成二维码url 合成二维码
			this.save(qrcode);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return qrcode;
	}


	private  QrCode  subTicket (QrCode qrcode,String headUrl,String userName,String posterUrl) throws Exception{
		 com.ssj.bean.weixin.message.custom.WxQRCode qRCode =new  com.ssj.bean.weixin.message.custom.WxQRCode();
		qRCode.setExpire_seconds(qrcode.getExpireSeconds());
		qRCode.setAction_name(qrcode.getType());
		WxQRCodeInfo action_info   =new  WxQRCodeInfo();
		WxQRCodeScene scene  =new   WxQRCodeScene();
		scene.setScene_id(qrcode.getSceneId());
		action_info.setScene(scene);
		qRCode.setAction_info(action_info);
		log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
		JSONObject jsonObject=  NewsUtil.ticket(tokenManager.getSSJAccessToken(), qRCode);
		if(null != jsonObject){
			qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
			qrcode.setUrl(jsonObject.getString("url"));//生成URL
			log.info("腾讯服务器申请二维码生成URL，"+qrcode.getUrl());
			log.info("腾讯服务器申请二维码生成ticket，"+qrcode.getTicket());
			log.info("腾讯服务器申请二维码返回json，"+jsonObject.toString());
			qrcode.setQrcodeTime(new Date());//生成时间
			String file_path = (String) SystemResourceLocator.getValue("file_save_path");
			String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
			if (!fPath.endsWith("/")) {
				fPath += "/";
			}
			File  f = new File(file_path+fPath);
			if (!f.exists()) {
				f.mkdirs();
			}
			fPath = fPath + UUID.randomUUID() + ".jpg";
			qrcode.setQrcodeUrl(fPath);
			BarcodeFactory.encode(qrcode.getUrl(),file_path+"/images/favicon.png",file_path+qrcode.getQrcodeUrl(),220, 220, true);
			log.info("二维码合成返回，"+fPath);
			String guanzhuUrl =ImageUtil.compositeSubImg(posterUrl, headUrl, fPath, userName);
			log.info("打卡界面返回，"+guanzhuUrl);
			qrcode.setGuanzhuUrl(guanzhuUrl);
		}
		return   qrcode;
	}
	
	
	private  QrCode    ticket (QrCode qrcode) throws Exception{
		 com.ssj.bean.weixin.message.custom.WxQRCode qRCode =new  com.ssj.bean.weixin.message.custom.WxQRCode();
	        qRCode.setExpire_seconds(qrcode.getExpireSeconds());
	        qRCode.setAction_name(qrcode.getType());
	        WxQRCodeInfo action_info   =new  WxQRCodeInfo();
	        WxQRCodeScene scene  =new   WxQRCodeScene();
	        scene.setScene_id(qrcode.getSceneId());
	        action_info.setScene(scene);
	        qRCode.setAction_info(action_info);
	        log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
	        JSONObject jsonObject=  NewsUtil.ticket(tokenManager.getSSJAccessToken(), qRCode);
	        if(null != jsonObject){
	        	qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
	        	qrcode.setUrl(jsonObject.getString("url"));//生成URL
	        	log.info("腾讯服务器申请二维码生成URL，"+qrcode.getUrl());
	        	log.info("腾讯服务器申请二维码生成ticket，"+qrcode.getTicket());
	        	log.info("腾讯服务器申请二维码返回json，"+jsonObject.toString());
	        	qrcode.setQrcodeTime(new Date());//生成时间
	        	String file_path = (String) SystemResourceLocator.getValue("file_save_path");
	        		String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
	        		if (!fPath.endsWith("/")) {
	        			fPath += "/";
	        		}
	        		File  f = new File(file_path+fPath);
	        		if (!f.exists()) {
	        			f.mkdirs();
	        		}
	        		fPath = fPath + UUID.randomUUID() + ".jpg";
	        		qrcode.setQrcodeUrl(fPath);
	        		BarcodeFactory.encode(qrcode.getUrl(),file_path+"/images/favicon.png",file_path+qrcode.getQrcodeUrl(),220, 220, true);
	        		log.info("二维码合成返回，"+fPath);
	        		String guanzhuUrl =ImageUtil.hechengDaka("/images/guanzhu.png", fPath);
	        		log.info("打卡界面返回，"+guanzhuUrl);
	        		qrcode.setGuanzhuUrl(guanzhuUrl);
	        }
	     return   qrcode;
	}
	@Override
	public  QrCode    creatTicket (String derver) throws Exception {
		log.info("小塾设备号:"+derver);
		Long lo =tokenManager.setnx(derver+derver,"1");
		if(lo==0){
			Thread.sleep(3000);
		}
		QrCode qrcode=qrcodeDao.findByObjectId(derver);

			if(qrcode !=null){
				//if(DateHelper.daysOfTwo( qrcode.getQrcodeTime(),new Date())>=29){
					if(!derver.equals(qrcode.getSceneId())){
						qrcode.setSceneId(derver);
					}
					WxQRCode(qrcode,qrcode.getQrcodeUrl());
					this.save(qrcode);
			//	}
				return   qrcode;
			}
			qrcode = new QrCode();
			qrcode.setObjectId(derver);
			qrcode.setExpireSeconds("2592000");
			qrcode.setType("QR_STR_SCENE");
			qrcode.setSceneId(derver);//场景值ID，临时二维码时为32位非0整型，
			qrcode.setParentId("conch");//贝壳统一为 conch
			WxQRCode(qrcode,null);
			this.save(qrcode);
		tokenManager.delString(derver+derver);
		return   qrcode;
	}
	private synchronized  void WxQRCode(QrCode qrcode,String qrcodeUrl){

		com.ssj.bean.weixin.message.custom.WxQRCode qRCode =new  com.ssj.bean.weixin.message.custom.WxQRCode();
		qRCode.setExpire_seconds(qrcode.getExpireSeconds());
		qRCode.setAction_name(qrcode.getType());
		WxQRCodeInfo action_info   =new  WxQRCodeInfo();
		WxQRCodeScene scene  =new   WxQRCodeScene();
		scene.setScene_id(qrcode.getSceneId());
		action_info.setScene(scene);
		qRCode.setAction_info(action_info);
		log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
		JSONObject jsonObject=  NewsUtil.ticket(tokenManager.getSSJAccessToken(), qRCode);
		if(null != jsonObject){
			qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
			qrcode.setUrl(jsonObject.getString("url"));//生成URL
			log.info("腾讯服务器申请二维码生成URL，"+qrcode.getUrl());
			log.info("腾讯服务器申请二维码生成ticket，"+qrcode.getTicket());
			log.info("腾讯服务器申请二维码返回json，"+jsonObject.toString());
			qrcode.setQrcodeTime(new Date());//生成时间
			String file_path = (String) SystemResourceLocator.getValue("file_save_path");
			if(qrcodeUrl==null){
				log.info("图片为空");
				String fPath = "/qrCode/" + qrcode.getObjectId();
				fPath += DateHelper.formatDateByFormat(new Date(), "yyyyMMdd");
				if (!fPath.endsWith("/")) {
					fPath += "/";
				}
				File f = new File(file_path + fPath);
				if (!f.exists()) {
					f.mkdirs();
				}
				String fPathId = fPath + qrcode.getObjectId() + ".jpg";
				qrcode.setQrcodeUrl(fPathId);
				log.info("图片地址"+fPathId);
			}else{
				log.info("图片地址"+file_path + qrcodeUrl);
				log.info("图片地址"+file_path + qrcode.getQrcodeUrl());
				File f = new File(file_path + qrcodeUrl);
				if (f.exists()) {
					log.info("图片删除成功");
					f.delete();
				}
			}
	        try {
				BarcodeFactory.bookencode(qrcode.getUrl(), file_path + qrcode.getQrcodeUrl(),378, 378);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public  QrCode createQrCode(QrCode qrcode){
		try {
			WxQRCode qRCode =new WxQRCode();
			qRCode.setExpire_seconds(qrcode.getExpireSeconds());
			qRCode.setAction_name(qrcode.getType());
			
			WxQRCodeInfo action_info=new WxQRCodeInfo();
			WxQRCodeScene scene=new  WxQRCodeScene();
			scene.setScene_id(qrcode.getSceneId());
			action_info.setScene(scene);
			qRCode.setAction_info(action_info);
			
			log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
			JSONObject jsonObject=  NewsUtil.ticket(tokenManager.getSSJAccessToken(), qRCode);
			if(null != jsonObject){
				qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
				qrcode.setUrl(jsonObject.getString("url"));//生成URL
				log.info("腾讯服务器申请二维码生成URL，"+qrcode.getUrl());
				log.info("腾讯服务器申请二维码生成ticket，"+qrcode.getTicket());
				log.info("腾讯服务器申请二维码返回json，"+jsonObject.toString());
				qrcode.setQrcodeTime(new Date());//生成时间
				String file_path = (String) SystemResourceLocator.getValue("file_save_path");
				String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
				if (!fPath.endsWith("/")) {
					fPath += "/";
				}
				File  f = new File(file_path+fPath);
				if (!f.exists()) {
					f.mkdirs();
				}
				fPath = fPath + UUID.randomUUID() + ".jpg";
				qrcode.setQrcodeUrl(fPath);
				BarcodeFactory.encode(qrcode.getUrl(),file_path+"/images/favicon.png",file_path+qrcode.getQrcodeUrl(),150, 150, true);
				this.save(qrcode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qrcode;
	}
	
	

	@Override
	public QrCode findByTicket(String ticket) {
		return qrcodeDao.findByTicket(ticket);
	}

	@Override
	public QrCode findByObjectIdAndParentId(String objectId,String parentId) {
		return qrcodeDao.findByObjectIdAndParentId(objectId,parentId);
	}

	@Override
	public QrCode findByQrcodeUrl(String qrcodeUrl) {
		return qrcodeDao.findByQrcodeUrl(qrcodeUrl);
	}

	@Override
	public QrCode findByUrl(String url) {
		return qrcodeDao.findByUrl(url);
	}


	public static void main(String[] args) {
		List<String> list = new ArrayList<String>(){
			{
				//白云 黄埔 天河 南山 嘉兴 扬州
				add("白云");
				add("黄埔");
				add("天河");
				add("南山");
				add("嘉兴");
				add("扬州");
			}
		};

		for (String str:list){
			QrCode	qrcode = new  QrCode();
			qrcode.setType("QR_STR_SCENE");//设置临时的二维码
			qrcode.setExpireSeconds("2592000");//时间最大为30天这里为30天
			qrcode.setObjectId(str);
			qrcode.setSceneId("");
			qrcode.setParentId("ad2020");
			try {
				WxQRCode qRCode =new WxQRCode();
				qRCode.setExpire_seconds(qrcode.getExpireSeconds());
				qRCode.setAction_name(qrcode.getType());

				WxQRCodeInfo action_info=new WxQRCodeInfo();
				WxQRCodeScene scene=new  WxQRCodeScene();
				scene.setScene_id(qrcode.getSceneId());
				action_info.setScene(scene);
				qRCode.setAction_info(action_info);

				log.info("腾讯服务器申请二维码请求参数，"+JSONObject.toJSONString(qRCode));
				JSONObject jsonObject=  NewsUtil.ticket("33_L25vGSRRv1qkyx3G7oSOsXgZRUH7vlOCRRhhBFhwoj5Pc0oZ68h-ePev5V_ECO-2V08Xg1MRDOkBR9eRUJMd0BK7LEui7HJ4OtHqxeHvHnh3fZKnIGbhmB1_NegJ1KvN-jrWxYGG5CwfcWSSKFXjAIAUPH", qRCode);
				if(null != jsonObject){
					qrcode.setTicket(jsonObject.getString("ticket"));//生成ticket
					qrcode.setUrl(jsonObject.getString("url"));//生成URL
					log.info("腾讯服务器申请二维码生成URL，"+qrcode.getUrl());
					log.info("腾讯服务器申请二维码生成ticket，"+qrcode.getTicket());
					log.info("腾讯服务器申请二维码返回json，"+jsonObject.toString());
					qrcode.setQrcodeTime(new Date());//生成时间
					String file_path = "F:\\";
					String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
					if (!fPath.endsWith("/")) {
						fPath += "/";
					}
					File  f = new File(file_path+fPath);
					if (!f.exists()) {
						f.mkdirs();
					}
					fPath = fPath + str + ".jpg";
					qrcode.setQrcodeUrl(fPath);
					BarcodeFactory.encode(qrcode.getUrl(),file_path+"/images/favicon.png",file_path+qrcode.getQrcodeUrl(),150, 150, true);
					StringBuffer stf = new StringBuffer();
					stf.append("insert into tb_qr_code(id,object_id,type,expire_seconds,qrcode_time,ticket,qrcode_url,url,parent_id) values('");
					stf.append(UUID.randomUUID()).append("','");
					stf.append(qrcode.getObjectId()).append("','");
					stf.append(qrcode.getType()).append("','");
					stf.append(qrcode.getExpireSeconds()).append("',now(),'");
					stf.append(qrcode.getTicket()).append("','");
					stf.append(qrcode.getQrcodeUrl()).append("','");
					stf.append(qrcode.getUrl()).append("','");
					stf.append(qrcode.getParentId()).append("');");
					System.out.println(stf.toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
