package com.ssj.taskasync;

import java.util.Date;
import java.util.List;

import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.ssj.bean.weixin.push.domain.TbWxTemplate;
import com.ssj.bean.weixin.push.domain.TbWxTemplateInfo;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.news.bean.Template;
import com.ssj.framework.weixin.util.NewsUtil;
import com.ssj.service.weixin.push.service.WxTemplateInfoService;


@Component	
public class SyncTemplateInfoSaveTask {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Async("taskExecutor")
	public void run(String templateIdShort,TbWxTemplate tbWxTemplate,String accessToken) {
		
		synchronized(this){
			WxTemplateInfoService wxTemplateInfoService = (WxTemplateInfoService)SystemResourceLocator.getBean(WxTemplateInfoService.class);
		    try {
		    	if(StringUtil.isNotEmpty(templateIdShort)){
			    	List<TbWxTemplateInfo> tbWxTemplateInfos= wxTemplateInfoService.queryTbWxTemplateInfoByShort(templateIdShort);
			    	if(tbWxTemplateInfos==null || tbWxTemplateInfos.size()==0){
				    	List<Template> templates= NewsUtil.getAllTemplate(accessToken);
			  		    for (Template template : templates) {
			  			   if(template.getTemplate_id().equals(tbWxTemplate.getTemplateId())){
			  				   TbWxTemplateInfo tbWxTemplateInfo=new TbWxTemplateInfo();
			  				   tbWxTemplateInfo.setContent(template.getContent());
			  				   tbWxTemplateInfo.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
			  				   tbWxTemplateInfo.setDeputyIndustry(template.getDeputy_industry());
			  				   tbWxTemplateInfo.setExample(template.getExample());
			  				   tbWxTemplateInfo.setPrimaryIndustry(template.getTitle());
			  				   tbWxTemplateInfo.setTemplateIdShort(templateIdShort);
			  				   tbWxTemplateInfo.setTitle(template.getTitle());
			  				   wxTemplateInfoService.save(tbWxTemplateInfo);
			  				   break;
			  			   }
			  		   }    
			    	}
		    	}
	        } catch (Exception e) {
	        	logger.error(" 微信模板明细数据保存，异常---------------");
	        }
		}
		
	}

	
	

}
