package com.cftech.mp.wechat.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.cms.cfarticle.model.Cfarticle;
import com.cftech.cms.cfarticle.service.CfarticleService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.Constants;
import com.cftech.mp.wechat.model.Imagetext;
import com.cftech.mp.wechat.model.ImagetextRead;
import com.cftech.mp.wechat.service.ImagetextReadService;
import com.cftech.mp.wechat.service.ImagetextService;
import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/** 
 * @author 作者 lisw: 
 * @version 创建时间：2016年10月28日 下午4:40:31 
 * 图文消息
 */
@RestController
@RequestMapping("mobile/imagetext")
public class MobileImageTextController {
	
	private static final Logger logger = LoggerFactory.getLogger(MobileImageTextController.class);
	
	@Autowired
	private ImagetextService imageTextService;
	
	@Autowired
	private ImagetextReadService imageTextReadService;

	@Autowired
	private CfarticleService cfarticleService;
	
	
	@RequestMapping(value="/fetchImageText",method={RequestMethod.GET,RequestMethod.POST},produces={"application/json;charset=UTF-8"})
	public JSONObject fetchImageText(Long imageTextId, String appid, String openid){
		/**
		 * 阅读
		 */
		Conds conds = new Conds();
		conds.equal("delflag", Constants.DEL_FLAG_0);
		conds.equal("openid", openid);
		conds.equal("image_textid", imageTextId);
		
		if(!imageTextReadService.existByConds(conds)){
			ImagetextRead imageTextRead = new ImagetextRead();
			imageTextRead.setDelflag(Constants.DEL_FLAG_0);
			imageTextRead.setOpenid(openid);
			imageTextRead.setImageTextid(imageTextId);
			imageTextReadService.save(imageTextRead);
		}
		
		JSONObject rtnJson = new JSONObject();
		try {
			Cfarticle imageText = cfarticleService.fetchById(imageTextId);
			Conds condsCount = new Conds();
			condsCount.equal("image_textid",imageTextId);
			condsCount.equal("delflag", Constants.DEL_FLAG_0);
			int count = imageTextReadService.count(condsCount);
//			JsonConfig jsonConfig = new JsonConfig();
//			jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
//					new JsonDateValueProcessor("yyyy-MM-dd"));
//			JSONObject imageTextJson= JSONObject.fromObject(imageText,jsonConfig);
//			rtnJson.put("data",imageTextJson);
			imageText.setContent(ESAPI.encoder().decodeForHTML(imageText.getContent()));
			rtnJson.put("data",imageText);
			rtnJson.put("dataCount",count);
            rtnJson.put("errorNo", 0);
		} catch (Exception e) {
			logger.info("获取图文信息详情出现异常:"+e.getMessage());;
			rtnJson.put("errorNo",1);
		}
		return rtnJson;
	}
}
 