
package com.cftech.mp.wechat.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.mp.wechat.model.Menu;
import com.cftech.mp.wechat.service.MenuService;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.core.exception.WexinReqException;
import org.mp.api.core.req.model.menu.WeixinButton;
import org.mp.api.wxmenu.JwMenuAPI;
import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/** 
 * @author 作者 lisw: 
 * @version 创建时间：2016年10月31日 上午10:36:46 
 * 微信菜单设置
 */
@Controller
@RequestMapping("/a/mpMenu")
public class MpMenuController {
	
	private static final Logger logger = LoggerFactory.getLogger(MpMenuController.class);
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private MpAccountsService accountService;

	@Autowired
	private MpTokenUtil tokenUtil;


	
	@RequestMapping(value = "/list",method={RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.MPMENU_VIEW)
	public String list(Model model,Menu menu){
		return "managerwechat/menulist";
	}
	
	@RequestMapping(value="/fetchData",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public JSONObject fetchData(HttpServletRequest request, int iDisplayStart, int iDisplayLength, Menu menu){
		 Long id=UserUtils.getmpaccounts(request);
			Sort sort = new Sort("sort", OrderType.DESC); 
			Conds conds = new Conds();
			conds.equal("u.accountsid", id);
			conds.equal("u.del_flag", Constants.DEL_FLAG_0);


			JSONObject returnObj = new JSONObject();
			List<Menu> menuList = menuService.fetchSearchByPageSeach(conds, sort, iDisplayStart, iDisplayLength,menu.getId());
			// 获得总数
			int userCounts = menuService.fetchSearchByPageSeachCount(conds,menu.getId());
			returnObj.put("iTotalRecords", userCounts);
			returnObj.put("iTotalDisplayRecords", userCounts);
			returnObj.put("aaData", menuList);
			return returnObj;
	}

	/**
	 * 二级菜单
	 * @return
	 */
	@RequestMapping(value="getfetchDataChild",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public JSONObject getfetchDataChild(HttpServletRequest request){
		JSONObject rtnJson = new JSONObject();
		JSONArray array = new JSONArray();
		Long accountsid = UserUtils.getmpaccounts(request);
		Sort sort = new Sort("sort", OrderType.ASC);
		Conds conds = new Conds();
		conds.equal("del_flag",0);
		conds.equal("accountsid",accountsid);
		List<Menu> areaList = menuService.fetchSearchByPage(conds, sort, 0,0);


		JSONObject t = new JSONObject();
		t.put("id", 0);
		t.put("pId", -1);
		t.put("name", "公众号菜单");
		t.put("open",true);
		array.add(t);
		for(Menu menu : areaList){
			JSONObject tmp = new JSONObject();
			tmp.put("id",menu.getId());
			tmp.put("pId",menu.getParentId());
			tmp.put("name",menu.getName());
			array.add(tmp);


		}
		rtnJson.put("aaData", array);
		return rtnJson;
	}
	
	/**
	 * 获取所有一级菜单
	 * @return
	 */
	@RequestMapping(value="/fetchMenu",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public JSONObject fetchMenu(HttpServletRequest request){
		JSONObject rtnJson = new JSONObject();
		Long accountsid = UserUtils.getmpaccounts(request);
		Sort sort = new Sort("sort", OrderType.DESC);
		Conds conds = new Conds();
		conds.equal("accountsid", accountsid);
		conds.equal("del_flag", Constants.DEL_FLAG_0);
		conds.equal("parent_id",0);
		List<Menu> menuList = menuService.fetchSearchByPage(conds, sort, 0,0);
		rtnJson.put("result", menuList);
		return rtnJson;
	}
	
	
	@RequestMapping(value="/menuform",method={RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.MPMENU_EDIT)
	public String replyform(Menu menu,Model model){
		if(menu.getId()!=null){
			menu = menuService.fetchById(menu.getId());
			if(StringUtils.isNotBlank(menu.getNewsItem())){
				JSONArray array = JSON.parseArray(menu.getNewsItem());
				for(int i =0,j=i;j<array.size();j++){
					JSONObject rtnJson = array.getJSONObject(j);
					rtnJson.remove("content");
				}
				menu.setNewsItem(array.toString());
			}
			menu.setSourceContent(ESAPI.encoder().decodeForHTML(menu.getSourceContent()));
		}
		model.addAttribute("menu", menu);
		return "managerwechat/menuform";
	}
	
	/**
	 * @param menu
	 * @param request
	 * @return   errorNo:0  添加成功  errorNo:2  更新成功 
	 * 			 errorNo:3  一级菜单最多3个  errorNo:4二级菜单最多5个
	 *           errorNo:1  出现异常
	 */
	@RequestMapping(value="/addMpMenu",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject addreply(Menu menu,HttpServletRequest request,String sourcecontent){
		if(StringUtils.isNotBlank(sourcecontent)){
			menu.setSourceContent(sourcecontent);
		}
		if(menu!=null && menu.getParentId()==null){
			menu.setParentId(0L);
		}
		if(StringUtils.equals(menu.getMsgType(), "1")){
			menu.setSourceContent(menu.getSourceContent().replace("\n","<br/>"));
		}
		Conds conds = new Conds();
		 Long id=UserUtils.getmpaccounts(request);
		 conds.equal("accountsid",id);
		 conds.equal("del_flag",Constants.DEL_FLAG_0);
		 conds.equal("parent_id",menu.getParentId());
		 JSONObject rtnJson = new JSONObject();
		 int menus = menuService.count(conds);
		 try {
			 if(menu.getId()!=null){//修改
				Menu menuExits = menuService.fetchById(menu.getId());
				if(menuExits.getParentId()!=menu.getParentId() && menu.getParentId()==0 && menus>=3){
					 rtnJson.put("errorNo","3");
				}else if(menuExits.getParentId()!=menu.getParentId() && menu.getParentId()!=0 && menus>=5){
					 rtnJson.put("errorNo","4");
				}else{
					menu.setUpdateBy(UserUtils.getUser().getId());
					menuService.update(menu);
					rtnJson.put("errorNo", 2);
				}
			 }else{//添加
				 if(menu.getParentId()==0 && menus>=3){//一级菜单最多3个
					 rtnJson.put("errorNo","3");
				 }else if(menu.getParentId()!=0 && menus>=5){//二级菜单最多5个
					 rtnJson.put("errorNo","4");
				 }else{
					 menu.setAccountsid(id);
					 menu.setCreateBy(UserUtils.getUser().getId());
					 menu.setDelFlag(Constants.DEL_FLAG_0);
					 menu.setUpdateBy(UserUtils.getUser().getId());
					 menuService.save(menu);
					 rtnJson.put("errorNo", 0);
				 }
			 }
		} catch (Exception e) {
			e.printStackTrace(); 
			rtnJson.put("errorNo",1);
		}
		 return rtnJson;
	}
	
	@RequestMapping(value="/remove",method={RequestMethod.POST})
	//@RequiresPermissions(value=PermissionSign.MPMENU_EDIT)
	@ResponseBody
	public JSONObject removereply(Long id){
		JSONObject rtnJson = new JSONObject();
		rtnJson.put("errorNo",0);
		try {
			if(id!=null){
				menuService.delete(id);
				/**
				 * 删除子菜单
				 */
				menuService.update(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rtnJson.put("errorNo",1);
		}
		return rtnJson;
	}
	
	
	
	@RequestMapping(value="sync",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject sync(HttpServletRequest request) {
		JSONObject rtnJson = new JSONObject();
		Long id = UserUtils.getmpaccounts(request);
		MpAccountsEntity accounts= accountService.getDetail(id);
		if(accounts==null){
			rtnJson.put("errorNo",1);
		}
		Conds conds = new Conds();
		conds.equal("u.accountsid",id);
		conds.equal("u.del_flag",Constants.DEL_FLAG_0);
		conds.equal("u.parent_id",0);
		// 查询所有一级菜单
		List<Menu> rootMenus = menuService.fetchSearchByPageSeach(conds,null,0,0,null);
		if (rootMenus != null && rootMenus.size() > 0) {
			String rootStr = "";     //记录菜单json字符串
			List<WeixinButton> testsUb = new ArrayList<WeixinButton>();
			for (Menu root : rootMenus) {  //遍历一级菜单
				List<WeixinButton> sub_button = new ArrayList<WeixinButton>();
				WeixinButton w = new WeixinButton();//一级菜单
				if(root.getChildren()!=null && root.getChildren().size()>0){//有子菜单
					w.setName(root.getName());
					for(Menu u : root.getChildren()){
						WeixinButton wChildren = new WeixinButton();
						wChildren.setName(u.getName());
						if(u.getSourceType().equals("1")){//点击返回消息
							wChildren.setKey(u.getId().toString());
							wChildren.setType("click");
						}else if(u.getSourceType().equals("2")){//点击跳转链接
							wChildren.setType("view");
							wChildren.setUrl(ESAPI.encoder().decodeForHTML(u.getSourceContent()));;
						}
						sub_button.add(wChildren);
					}
					w.setSub_button(sub_button);
				}else{
					if(root.getSourceType().equals("3")){
						rtnJson.put("errorNo","2");
						return rtnJson;
					}
					w.setName(root.getName());
					if(root.getSourceType().equals("1")){//点击返回消息
						w.setKey(root.getId().toString());
						w.setType("click");
					}else if(root.getSourceType().equals("2")){//点击跳转链接
						w.setType("view");
						w.setUrl(ESAPI.encoder().decodeForHTML(root.getSourceContent()));
					}
				}
				testsUb.add(w);
			}
			try {
				rtnJson.put("errorNo","0");
				rootStr=JwMenuAPI.createMenu(tokenUtil.getToken(id),testsUb);
				logger.info("菜单同步:"+rootStr);
			} catch (WexinReqException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return rtnJson;
	}




}
 