package com.ssj.taskasync;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.weixin.push.domain.PushTemplate;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.push.domain.TbWxTemplate;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.NewsUtil;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.util.WxTemplateCacheUtils;

@Component	
public class SyncSaveAndSendPushTask {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Async("taskExecutor")
	public void run(SendTemplateShort sendTemplateShort) {
		logger.error("立即微信推送任务开始---------------");
		try {
			TokenManager tokenManager = (TokenManager)SystemResourceLocator.getBean(TokenManager.class,"tokenManager");
			PushTemplateService pushTemplateService = (PushTemplateService)SystemResourceLocator.getBean(PushTemplateService.class);
			PushTemplate pushTemplate=null;
			if(StringUtils.isNotEmpty(sendTemplateShort.getPushTemplateId())){
				pushTemplate=pushTemplateService.getById(sendTemplateShort.getPushTemplateId());
				logger.error("查询PushTemplateId："+sendTemplateShort.getPushTemplateId()+"data:"+JSONObject.toJSONString(pushTemplate));
			}
			if(pushTemplate==null){
				logger.error("pushTemplate为空...");
				pushTemplate =new PushTemplate();
				pushTemplate.setClickUrl(sendTemplateShort.getUrl());
				pushTemplate.setInterVal(sendTemplateShort.getInterVal());
				pushTemplate.setOpenid(sendTemplateShort.getTouser());
				pushTemplate.setTopColor(sendTemplateShort.getTopColor());
				pushTemplate.setTotal(sendTemplateShort.getTotal());
				pushTemplate.setWxTplSid(sendTemplateShort.getTemplate_id_short());
				pushTemplate.setContent(JSONObject.toJSONString(sendTemplateShort.getData()));
				if(sendTemplateShort.getMiniprogram()!=null && StringUtils.isNotEmpty(sendTemplateShort.getMiniprogram().getAppid())){
					pushTemplate.setMiniprogram(JSONObject.toJSONString(sendTemplateShort.getMiniprogram()));
				}
				pushTemplate.setCreateTime(new Date());
				pushTemplate.setCurTotal(0);
				pushTemplate.setIsSuccess(0);
				pushTemplate.setStat(1);
				pushTemplate.setTryTime(0);
			}
			
			TbWxTemplate tbWxTemplate= WxTemplateCacheUtils.getTbWxTemplate(pushTemplate.getWxTplSid(),null,null);
			if(StringUtils.isEmpty(pushTemplate.getOpenid())){
				 pushTemplate.setRemark("OPENID为空，请注意检查来源代码逻辑...");
				 pushTemplate.setTryTime(pushTemplate.getTryTime()+1);
			}else if(tbWxTemplate!=null && StringUtils.isNotEmpty(tbWxTemplate.getTemplateId())){
				try {
					String msg= NewsUtil.WX_TPL_BODY
							  	 .replace(NewsUtil.TPL_CODE_OPENID, pushTemplate.getOpenid())
							  	 .replace(NewsUtil.TPL_CODE_TPLID, tbWxTemplate.getTemplateId())
					             .replace(NewsUtil.TPL_CODE_URL, StringUtils.isNotEmpty(pushTemplate.getClickUrl())?pushTemplate.getClickUrl():"")
					             .replace(NewsUtil.TPL_CODE_DATA, pushTemplate.getContent())
					             .replace(NewsUtil.TPL_CODE_TOPCOLOR, StringUtils.isNotEmpty(pushTemplate.getTopColor())?pushTemplate.getTopColor():"");
					 if(StringUtils.isNotEmpty(pushTemplate.getMiniprogram())){
						 msg=msg.replace(NewsUtil.TPL_CODE_MINIPROQRAM_TEXT, NewsUtil.TPL_SUB_MINIPROQRAM_DATA);
						 msg=msg.replace(NewsUtil.MINIPROQRAM_DATA, pushTemplate.getMiniprogram());
					 }else{
						 msg=msg.replace(NewsUtil.TPL_CODE_MINIPROQRAM_TEXT, "");
					 }
					 
					 //再去查询，防止重复推送,定时推送数据锁定一分钟
					 if(StringUtils.isNotEmpty(pushTemplate.getId())){
						 pushTemplate=pushTemplateService.getById(pushTemplate.getId());
						 logger.error("查询pushTemplate对象："+pushTemplate.getId()+"data:"+JSONObject.toJSONString(pushTemplate));
					 }
					 if(pushTemplate.getIsSuccess()==0){
						 JSONObject result =NewsUtil.sendTemplate(tokenManager.getSSJAccessToken(), msg);
						 logger.error("[PushTemplateServiceImpl]  WxTplSid: " + pushTemplate.getWxTplSid() + ", result: " + result);
						 if(result != null && "0".equals(result.getString("errcode"))){
							 pushTemplate.setIsSuccess(1);
							 pushTemplate.setSuccessTime(new Date());
							 pushTemplate.setCurTotal(pushTemplate.getCurTotal()+1); 
							 pushTemplate.setRemark("");
						 }else{
							 pushTemplate.setTryTime(pushTemplate.getTryTime()+1);
							 pushTemplate.setRemark("errcode:"+result.getString("errcode"));
						 }
					 }
				} catch (Exception e) {
					 pushTemplate.setTryTime(pushTemplate.getTryTime()+1);
					 pushTemplate.setRemark("exception:"+e.getMessage());
				}
			 }else{
				 pushTemplate.setRemark("模板池无法得到微信模板ID...");
				 pushTemplate.setTryTime(pushTemplate.getTryTime()+1);
			 }
			pushTemplateService.save(pushTemplate);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存推送信息异常...");
		}
		logger.error("立即微信推送任务结束---------------");
	}

	
	
	

}
