package com.iamberry.wechat.handles.wechat.keyword;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
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.KeyWord;
import com.iamberry.wechat.core.entity.wx.PagingDTO;
import com.iamberry.wechat.face.wechat.ImageTextInfoService;
import com.iamberry.wechat.face.wechat.KeyWordService;
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 KeyWordHandler {
	
	private static int pageNo = 1;
	private static final int selectNum = 10;
	
	@Autowired
	private KeyWordService keyWordService;
	
	@Autowired
	private ImageTextInfoService imageTextInfoService;
	
	@Autowired
	private AdminUtils adminUtils;
	
	/**
	 * 关键字列表
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/showKeyWordList")
	public ModelAndView getKeyWordList(@RequestParam(value="pageNO", defaultValue="1") Integer pageNO, @RequestParam(value="word", defaultValue="") String word, HttpServletRequest request) throws Exception {
		if("GET".equalsIgnoreCase(request.getMethod())) {
			word = new String(word.getBytes("iso-8859-1"),"utf-8");
		}
		ModelAndView mv = new ModelAndView("admin/wx/keyset/keywordlist");
		int pageSize = 3;
		List<KeyWord> klist = keyWordService.selectKeyList(NameUtils.pubNo, word, pageNO, pageSize);
		mv.addObject("klist", klist);
		mv.addObject("pageNO", pageNO);
		mv.addObject("word", word);
		mv.addObject("pageCount", pageSize);
		mv.addObject("pageSize", keyWordService.selectKeyListCount(NameUtils.pubNo, word, pageSize));
		mv.addObject("url", "/admin/wx/showKeyWordList?word="+word+"&pageNO=");
		return mv;
	}

	/**
	 * 批量删除关键字
	 */
	@RequestMapping("/batchDelKeyWord")
	@ResponseBody
	public JSONObject batchDelKeyWord(HttpServletRequest request) {
		String errInfo = "";
		String delJSON = request.getParameter("delJSON");
		if(delJSON != null) {
			JSONArray delArray = JSONArray.fromObject(delJSON);
			List<String> delList = new ArrayList<String>();
			delList = JSONArray.toList(delArray);
			List<Integer> delIdList = new ArrayList<Integer>();
			//解密ID
			for(String keyWordNO : delList) {
				keyWordNO = adminUtils.decryptObject(keyWordNO, "keyWordNo");
				if(keyWordNO != null) {
					delIdList.add(Integer.parseInt(keyWordNO));
				}
			}
			if(delIdList.size() >= 1) {
				keyWordService.batchDelKeyWordById(delIdList);
				errInfo = "{'msg':'success'}";
				return JSONObject.fromObject(errInfo);
			}
		}
		
		errInfo = "{'msg':'删除失败!'}";
		return JSONObject.fromObject(errInfo);
	}
	
	/**
	 * 删除单个关键字
	 */
	@RequestMapping("/delKeyWord/{idMd5}")
	@ResponseBody
	public JSONObject delKeyWord(@PathVariable("idMd5") String idMd5) {
		String errInfo = "";
		if(idMd5 != null && !idMd5.trim().equals("")) {
			idMd5 = adminUtils.decryptObject(idMd5, "keyWordNo");
			if(idMd5 != null) {
				keyWordService.deleteKeyWordById(Long.parseLong(idMd5));
				errInfo = "{'msg':'success'}";
				return JSONObject.fromObject(errInfo);
			}
		}
		errInfo = "{'msg':'删除失败!'}";
		return JSONObject.fromObject(errInfo);
	}
	
	
	/**
	 * 进入添加关键字
	 */
	@RequestMapping("/showEditKeyWordAnswer")
	public ModelAndView showEditKeyWordAnswer(HttpSession session) {
		ModelAndView mv = new ModelAndView("admin/wx/keyset/addkeywordanswer");
		String sessionToken = adminUtils.byte2hex(adminUtils.createRandomByte());
		session.setAttribute("addKeyWordToken", sessionToken);
		mv.addObject("token", sessionToken);
		return mv;
	}
	
	/**
	 * 添加关键字
	 */
	@RequestMapping("/addKeyWordAnswer/{token}")
	@ResponseBody
	public JSONObject addKeyWordAnswer(@PathVariable("token") String token,
										@RequestParam(value="keyWord", defaultValue="") String keyWord,
										@RequestParam(value="type", defaultValue="1") String answerType,
										@RequestParam(value="bodyEdit", defaultValue="") String answerBody,
										@RequestParam(value="imageTextId", defaultValue="") String imageTextId,
										HttpSession session) {
		String errInfo = "";
		//验证token
		String sessionToken = (String) session.getAttribute("addKeyWordToken");
		session.removeAttribute("addKeyWordToken");
		String keyWordToken = adminUtils.byte2hex(adminUtils.createRandomByte());
		imageTextId = adminUtils.decryptObject(imageTextId, "imageTextNo");
		if(sessionToken != null && token != null && token.equals(sessionToken)) {
			if(adminUtils.parseFieldLength(keyWord, 1, 50) && (answerType.trim().equals("1")||answerType.trim().equals("2"))) {
				if(answerType.trim().equals("1") && adminUtils.parseFieldLength(answerBody, 1, 200)) {
					KeyWord kw = new KeyWord();
					kw.setKeyWord(keyWord);
					kw.setWxpublicNo(NameUtils.pubNo);//只服务猫小贱公众号
					kw.setCreateTime(new Date());
					kw.setRefImageTextId((imageTextId == null || imageTextId.equals("")) ? 0L : new Long(imageTextId));
					kw.setReType(answerType);
					kw.setRefText(answerBody != null ? answerBody.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
					keyWordService.insert(kw);
					errInfo = "{'msg':'success'}";
				} else if(answerType.trim().equals("2") && imageTextId != null && imageTextId != "") {
					KeyWord kw = new KeyWord();
					kw.setKeyWord(keyWord);
					kw.setWxpublicNo(NameUtils.pubNo);//只服务猫小贱公众号
					kw.setCreateTime(new Date());
					kw.setRefImageTextId((imageTextId == null || imageTextId.equals("")) ? 0L : new Long(imageTextId));
					kw.setReType(answerType);
					kw.setRefText(answerBody != null ? answerBody.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
					keyWordService.insert(kw);
					errInfo = "{'msg':'success'}";
				} else {
					session.setAttribute("addKeyWordToken", keyWordToken);
					errInfo = "{'msg':'验证失败!','token':'"+keyWordToken+"'}";
				}
			}else {
				session.setAttribute("addKeyWordToken", keyWordToken);
				errInfo = "{'msg':'验证失败!','token':'"+keyWordToken+"'}";
			}
		} else {
			errInfo = "{'msg':'tokenerr'}";
		}
		JSONObject json = JSONObject.fromObject(errInfo);
		return json;
	}
	
	//获取图文资源
	@RequestMapping("/showImageTextSource")
	@ResponseBody
	public List<Map<Object, Object>> showImageTextSource() throws Exception {
		List<Map<Object, Object>> lists = imageTextInfoService.selectAllImageTextList(NameUtils.pubNo);
		if(lists != null) {
			return lists;
		}
		return null;
	}
	
	/**
	 * 进入修改图文资源页面
	 * @throws Exception 
	 */
	@RequestMapping("/showUpdateImageText/{keyWordId}")
	public ModelAndView showUpdateImageText(HttpSession session, @PathVariable("keyWordId") String keyWordId) throws Exception {
		ModelAndView mv = new ModelAndView("admin/wx/keyset/updatekeywordanswer");
		String sessionToken = adminUtils.byte2hex(adminUtils.createRandomByte());
		session.setAttribute("updateKeyWord", sessionToken);
		mv.addObject("keywordId", keyWordId);
		//根据ID，查询关键字回复信息
		if(keyWordId != null) {
			//id解密
			keyWordId = adminUtils.decryptObject(keyWordId, "keyWordNo");
			if(keyWordId != null && !keyWordId.trim().equals("")) {
				//获取关键字回复信息
				KeyWord keyword = keyWordService.getById(Long.parseLong(keyWordId));
				if(keyword.getReType().equals("2")) {
					//根据ID获取图文信息
					Map<Object, Object> imageTextInfo = imageTextInfoService.findImageTextMore(keyword.getRefImageTextId());
					mv.addObject("imageTextInfo", imageTextInfo);
				}
				mv.addObject("keyWord", keyword);
			}
		}
		mv.addObject("token", sessionToken);
		return mv;
	}
	
	
	/**
	 * 修改关键字回复
	 */
	@RequestMapping("/updateKeyWord/{token}")
	@ResponseBody
	public JSONObject updateKeyWord(@PathVariable("token") String token,
								@RequestParam(value="keyWordId", defaultValue="") String keywordId,
								@RequestParam(value="keyWord", defaultValue="") String keyWord,
								@RequestParam(value="type", defaultValue="1") String answerType,
								@RequestParam(value="bodyEdit", defaultValue="") String answerBody,
								@RequestParam(value="imageTextId", defaultValue="") String imageTextId,
								HttpSession session) {
		String errInfo = "";
		//验证token
		String sessionToken = (String) session.getAttribute("updateKeyWord");
		session.removeAttribute("updateKeyWord");
		String keyWordToken = adminUtils.byte2hex(adminUtils.createRandomByte());
		imageTextId = adminUtils.decryptObject(imageTextId, "imageTextNo");
		keywordId = adminUtils.decryptObject(keywordId, "keyWordNo");
		if(sessionToken != null && token != null && token.equals(sessionToken)) {
			if(adminUtils.parseFieldLength(keyWord, 1, 50) && (answerType.trim().equals("1")||answerType.trim().equals("2"))) {
				if(keywordId != null && !keywordId.trim().equals("")) {
					if(answerType.trim().equals("1") && adminUtils.parseFieldLength(answerBody, 1, 200)) {
						KeyWord kw = keyWordService.getById(Long.parseLong(keywordId));
						kw.setKeyWord(keyWord);
						kw.setWxpublicNo(NameUtils.pubNo);//只服务猫小贱公众号
						kw.setRefImageTextId((imageTextId == null || imageTextId.equals("")) ? 0L : new Long(imageTextId));
						kw.setReType(answerType);
						kw.setRefText(answerBody != null ? answerBody.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
						keyWordService.updateByPrimaryKey(kw);
						errInfo = "{'msg':'success'}";
					} else if(answerType.trim().equals("2") && imageTextId != null && !imageTextId.trim().equals("")) {
						KeyWord kw = keyWordService.getById(Long.parseLong(keywordId));
						kw.setKeyWord(keyWord);
						kw.setWxpublicNo(NameUtils.pubNo);//只服务猫小贱公众号
						kw.setRefImageTextId((imageTextId == null || imageTextId.equals("")) ? 0L : new Long(imageTextId));
						kw.setReType(answerType);
						kw.setRefText(answerBody != null ? answerBody.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
						keyWordService.updateByPrimaryKey(kw);
						errInfo = "{'msg':'success'}";
					} else {
						session.setAttribute("updateKeyWord", keyWordToken);
						errInfo = "{'msg':'验证失败1!','token':'"+keyWordToken+"'}";
					}
				} else {
					session.setAttribute("updateKeyWord", keyWordToken);
					errInfo = "{'msg':'验证失败2!','token':'"+keyWordToken+"'}";
				}
			}else {
				session.setAttribute("updateKeyWord", keyWordToken);
				errInfo = "{'msg':'验证失败3!','token':'"+keyWordToken+"'}";
			}
		} else {
			errInfo = "{'msg':'tokenerr'}";
		}
		JSONObject json = JSONObject.fromObject(errInfo);
		return json;
	}
	
	//以下为老代码
	
	/**
	 * 查询关键字
	 * @param request
	 * @return
	 */
	@RequestMapping("/get")
	public ModelAndView getKeyWord(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String keyServiceNo = request.getParameter("keyServiceNo");
		if(keyServiceNo != null){
			KeyWord keyword = keyWordService.getById(Long.parseLong(keyServiceNo));
			mv.addObject("keyword", keyword);
			mv.setViewName("forward:/main/keyset/keyservice/answer.jsp");
		}
		return mv;
	}
	
	/**
	 * 新增关键字
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/add")
	public void addKeyWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String reType = request.getParameter("reType");
		String keyWord = request.getParameter("keyWord");
		String refText = request.getParameter("refText");
		String refImageTextId = request.getParameter("refImageTextId");
		
		KeyWord keyword = new KeyWord();
		keyword.setKeyWord(keyWord);
		keyword.setWxpublicNo(NameUtils.pubNo);//只服务猫小贱公众号
		keyword.setCreateTime(new Date());
		keyword.setRefImageTextId(refImageTextId == null ? 0L : new Long(refImageTextId));
		keyword.setReType(reType);
		keyword.setRefText(refText != null ? refText.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
		keyWordService.insert(keyword);
		response.getWriter().write("true");
		response.getWriter().close();
	}
	
	/**
	 * 修改关键字
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/update")
	public void updateKeyWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String keyWord = request.getParameter("keyword");
		String reType = request.getParameter("reType");
		String refText = request.getParameter("refText");
		String keyServiceNo = request.getParameter("keyServiceNo");
		String refImageTextInfoNo = request.getParameter("refImageTextInfoNo");
		
		if(keyServiceNo !=null){
			KeyWord key = keyWordService.getById(Long.parseLong(keyServiceNo));
			if(key != null){
				key.setReType(reType);
				key.setKeyWord(keyWord);
				key.setRefText(refText != null ? refText.trim().replace("&lt;", "<") .replace("&gt;", ">") : null);
				key.setRefImageTextId(refImageTextInfoNo == null ? 0L : new Long(refImageTextInfoNo));
				keyWordService.updateByPrimaryKey(key);
			}
			response.getWriter().write("true");
			response.getWriter().close();
		}
	}
	
	/**
	 * 共多少页
	 */
	public int getPageNum(String pubNo, int selectNum) {
		return keyWordService.getPageNum(pubNo, selectNum);
	}
	
	/**
	 * 分页显示关键字列表
	 * 接受一个参数pageNO 为当前的页数
	 * @param request
	 * @return
	 */
	@RequestMapping("/getlistpage")
	public ModelAndView getKeyWordListPage(@RequestParam(value="pageNo",defaultValue="1") Integer pageNo1,HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		pageNo = pageNo1;
		PagingDTO pdto = new PagingDTO();
		pdto.setWxPublicNo(NameUtils.pubNo);
		pdto.setPageNo(pageNo);
		pdto.setSelectNum(selectNum);
		List<KeyWord> klist = keyWordService.getBypubNoAndPageNo(pdto);
		mv.addObject("klist", klist);
		mv.addObject("pageNO", pageNo);
		mv.addObject("url","/admin/keyword/getlistpage?pageNo=");
		mv.addObject("pageSize",this.getPageNum(pdto.getWxPublicNo(), selectNum));//所有的关键字页数
		mv.setViewName("forward:/main/keyset/keyservice/klist.jsp");
		return mv;
	} 
		
}
