package com.iamberry.wechat.handles.wechat.firstAccess;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.wx.FirstJoinKey;
import com.iamberry.wechat.face.wechat.FirstJoinKeyService;
import com.iamberry.wechat.face.wechat.ImageTextInfoService;
import com.iamberry.wechat.tools.NameUtils;
/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月3日
 * @explain	微信后台管理-首次关注的回复
 */
@Controller
@RequestMapping("/admin/wx")
public class FirstJoinKeyHandler {
	
	@Autowired
	private FirstJoinKeyService firstJoinKeyService;
	
	@Autowired
	private AdminUtils adminUtils;
	
	@Autowired
	private ImageTextInfoService imageTextInfoService;
	/**
	 * 根据微信公众号， 查询到首次关注的自动回复的所有内容
	 * 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/showFirstAnswer")
	public ModelAndView getBywxpublicNO(HttpSession session) throws Exception {
		ModelAndView mv = new ModelAndView();
		String sessionToken = adminUtils.byte2hex(adminUtils.createRandomByte());
		session.setAttribute("firstAnswer", sessionToken);
		mv.addObject("token", sessionToken);
		FirstJoinKey firstJoinKey = firstJoinKeyService.getBywxpublicNO(NameUtils.pubNo);
		if(firstJoinKey != null) {
			if(firstJoinKey.getReMessageType().equals("2")) {
				//根据ID获取图文信息
				Map<Object, Object> imageTextInfo = imageTextInfoService.findImageTextMore(firstJoinKey.getImageTextNo());
				mv.addObject("imageTextInfo", imageTextInfo);
			}
			mv.addObject("firstJoinKey", firstJoinKey);
		}
		mv.setViewName("admin/wx/firseAccess/firstanswers");
		return mv;
	}
	
	/**
	 * 保存或修改首次关注自动回复内容
	 * @throws IOException 
	 */
	@RequestMapping("/updateandaddFirstJoinKey/{token}")
	@ResponseBody
	public JSONObject updatebyFirstJoinKey(HttpSession session,
									@PathVariable("token") String token,
									@RequestParam(value="type", defaultValue="1") String firstAnswerType,
									@RequestParam(value="bodyEdit", defaultValue="") String reText,
									@RequestParam(value="imageTextId", defaultValue="imageTextId") String imageTextId) throws IOException {
		String errInfo = null;
		String sessionToken = (String) session.getAttribute("firstAnswer");
		session.removeAttribute("firstAnswer");
		String firstAnswerToken = adminUtils.byte2hex(adminUtils.createRandomByte());
		if(sessionToken != null && token != null && token.equals(sessionToken)) {
			//先在数据库库查询是否有该微信公众号的首次关注回复的记录表，返回一个FirstJoinKey对象
			FirstJoinKey selectfirstJoinKey =  firstJoinKeyService.getBywxpublicNO(NameUtils.pubNo);
			//将在客户端传过来的数据保存到这个FirstJoinKey这个对象中
			FirstJoinKey firstJoinKey = new FirstJoinKey();
			firstJoinKey.setCreateTime(new Date());
			firstJoinKey.setWxpublicNo(NameUtils.pubNo);  
			firstJoinKey.setReMessageType(firstAnswerType);
			if(firstAnswerType.trim().equals("1") && reText != null && !reText.equals("")) {
				//添加文字回复
				firstJoinKey.setReText(reText != null ? reText.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
				//如果这个对象不为空，那么证明存在该记录，只需根据需求修改首次关注回复的内容即可
				//若这个对象为空，那么证明不存在该记录，这时我们需要添加首条记录
				int status = 0;
				if(selectfirstJoinKey != null ) {
					status = firstJoinKeyService.updatebyFirstJoinKey(firstJoinKey);
				} else {
					status = firstJoinKeyService.addFirstJoinKey(firstJoinKey);
				}
				session.setAttribute("firstAnswer", firstAnswerToken);
				errInfo = "{'msg':'success','token':'"+firstAnswerToken+"'}";
			} else if(firstAnswerType.trim().equals("2") && imageTextId != null && !imageTextId.equals("")){
				//添加素材回复
				imageTextId = adminUtils.decryptObject(imageTextId, "imageTextNo");
				firstJoinKey.setImageTextNo((imageTextId == null || imageTextId.equals("")) ? 0L : new Long(imageTextId));
				int status = 0;
				if(selectfirstJoinKey != null ) {
					status = firstJoinKeyService.updatebyFirstJoinKey(firstJoinKey);
				} else {
					status = firstJoinKeyService.addFirstJoinKey(firstJoinKey);
				}
				session.setAttribute("firstAnswer", firstAnswerToken);
				errInfo = "{'msg':'success','token':'"+firstAnswerToken+"'}";
			} else {
				//验证失败
				session.setAttribute("firstAnswer", firstAnswerToken);
				errInfo = "{'msg':'验证失败!','token':'"+firstAnswerToken+"'}";
			}
		} else {
			errInfo = "{'msg':'tokenerr'}";
		}
		JSONObject json = JSONObject.fromObject(errInfo);
		return json;
	}
}
