package com.ssj.sys.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.menu.domain.*;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.weixin.util.WeixinUtil;
import com.ssj.service.sys.menu.service.MenuService;
import com.ssj.service.sys.menu.service.WxMaterialService;
import com.ssj.service.sys.menu.service.WxMsgEventService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RequestMapping("sys/menu")
@Controller
public class MenuController extends BaseController {
	
	@Autowired
	private TokenManager tokenManager;
	 
	@Autowired
	private MenuService menuService;
	
	@Autowired
    private WxMaterialService wxMaterialService;
    
	@Autowired
    private WxMsgEventService wxMsgEventService;
	
	  @RequestMapping("/sysAllMenuQuery")
	  @ResponseBody
	  public List<Menu> sysAllMenuQuery() {
		List<Menu> menuList = menuService.findAll();
	    return menuList;
	  }
	  
		@RequestMapping("/wxmenu")
		public String wxmenu(Model model)throws Exception {
			logger.info("当前微信微信公众号getSSJAccessToken："+tokenManager.getSSJAccessToken());
			return "sys/menu/wxmenu";
		}
	  
	   
	    @RequestMapping(value = "/getwxmenu", method = RequestMethod.GET)
	    @ResponseBody
	    public ResponseEntity wxmenu() {
	    	ResponseEntity responseEntity = new ResponseEntity();
	    	try{
		        String accessToken = tokenManager.getSSJAccessToken();
		        String url = WeixinUtil.API_MENU_GET.replace("ACCESS_TOKEN",accessToken);
		        JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST","");
		        logger.info("请求微信菜单结果："+jsonObject.toJSONString());
		    	String menu=jsonObject.get("menu").toString();
		    	Map<String, Object> map =new HashMap<String, Object>();
		    	map.put("menu", menu);
		    	responseEntity.success(map,"操作成功");
	    	}catch (Exception e) {
	  	      e.printStackTrace();
		    }
	    	return responseEntity;
	    }
	    
	    @RequestMapping(value = "/materiallist", method = RequestMethod.GET)
	    @ResponseBody
	    public ResponseEntity materiallist() {
	    	ResponseEntity responseEntity = new ResponseEntity();
	    	try{
	    		List<WxMaterialGroupResult> wxMaterialGroupResults=new ArrayList<WxMaterialGroupResult>();
		    	List<WxMaterial> wxMaterials=  wxMaterialService.listByWxMaterial();
		    	Map<String, List<WxMaterial>> wxMaterialMap=new HashMap<String, List<WxMaterial>>();
				for (WxMaterial wxMaterial : wxMaterials) {
					String materialId=wxMaterial.getMediaId();
					List<WxMaterial> wxMaterialList=wxMaterialMap.get(materialId);
					if(wxMaterialList==null){
						wxMaterialList=new ArrayList<WxMaterial>();
						wxMaterialList.add(wxMaterial);
						wxMaterialMap.put(materialId, wxMaterialList);
					}else{
						wxMaterialList.add(wxMaterial);
					}
				}
				Set<String> keys= wxMaterialMap.keySet();
				WxMaterialGroupResult wxMaterialGroupResult=null;
				for (String key : keys) {
					wxMaterialGroupResult=new WxMaterialGroupResult();
					wxMaterialGroupResult.setMediaId(key);
					wxMaterialGroupResult.setWxMaterials(wxMaterialMap.get(key));
					wxMaterialGroupResults.add(wxMaterialGroupResult);
				}
		    	Map<String, Object> map =new HashMap<String, Object>();
		    	map.put("rows", wxMaterialGroupResults);
		    	responseEntity.success(map,"操作成功");
	    	}catch (Exception e) {
		  	     e.printStackTrace();
			}
	    	return responseEntity;
	    }
	    
	    
	    @RequestMapping(value="/saveMenu")
	    @ResponseBody
	    public ResponseEntity saveMenu(HttpServletRequest request, HttpServletResponse response,String jsondata,String channel){
	    	ResponseEntity responseEntity = new ResponseEntity();
	    	try{
		    	logger.info("请求保存微信菜单:"+jsondata);
			    JSONObject jsonobj=JSONObject.parseObject(jsondata);
			    jsondata="{\"button\":"+jsonobj.get("menu").toString()+"}";
			    String accessToken = tokenManager.getSSJAccessToken();
			    String url =WeixinUtil.API_MENU_CREATE.replace("ACCESS_TOKEN",accessToken);
			    JSONObject res = WeixinUtil.httpRequest(url, "POST", jsondata);  
			    logger.info("保存微信菜单结果:"+res.toJSONString());
			    if ("0".equals(res.getString("errcode"))) {
			    	String mediakey=jsonobj.get("mediakey").toString();
			    	String delkey=jsonobj.get("delkey").toString();
			    	JSONArray array=JSONArray.parseArray(mediakey);
			    	if(array!=null && array.size()>0){
			    		for (Object object : array) {
			    			JSONObject obj=(JSONObject)object;
			    			WxMsgEvent wxMsgEvent=new WxMsgEvent();
				    		wxMsgEvent.setCreateDate(new Date());
				    		wxMsgEvent.setEvent("CLICK");
				    		wxMsgEvent.setEventKey(obj.get("key").toString());
				    		wxMsgEvent.setWeixinid("");
				    		wxMsgEvent.setRemark("");
			    			if("text".equals(obj.get("type"))){
			    				WxMaterial wxMaterial=new WxMaterial();
			    				wxMaterial.setMsgType("text");
			    				List<WxMaterial>  wxMaterials=wxMaterialService.getByWxMaterialId(obj.get("key").toString());
			    				if(wxMaterials!=null && wxMaterials.size()>0){
			    					wxMaterial=wxMaterials.get(0);
			    					wxMaterial.setContent(obj.get("media").toString());
			    					wxMaterial.setMediaId(obj.get("key").toString());
			    					wxMaterialService.updateWxMaterialById(wxMaterial);
			    				}else{
			    					wxMaterial.setContent(obj.get("media").toString());
				    				wxMaterial.setMediaId(obj.get("key").toString());
									wxMaterialService.saveWxMaterial(wxMaterial);
			    				}
								wxMsgEvent.setMediaId(obj.get("key").toString());
			    			}else{
			    				wxMsgEvent.setMediaId(obj.get("media").toString());
			    			}
				    		wxMsgEventService.saveWxMsgEvent(wxMsgEvent);
						}
			    	}
			    	if(StringUtils.isNotEmpty(delkey)){
			    		String[] delkeys=delkey.split(",");
			    		for (String eventKey : delkeys) {
			    			wxMsgEventService.delWxMsgEvent(eventKey);
						}
			    	}
		        } 
			    Map<String, Object> map =new HashMap<String, Object>();
			    map.put("ret", res.toJSONString());
			    responseEntity.success(map,"操作成功");
	    	}catch (Exception e) {
		  	     e.printStackTrace();
			}
	   	    return responseEntity;
			
	    }
	    
	    @RequestMapping(value="/getmaterial")
	    @ResponseBody
	    public ResponseEntity getmaterial(HttpServletRequest request, HttpServletResponse response,String eventKey,String event){
	    	ResponseEntity responseEntity = new ResponseEntity();
	    	try{
		    	WxMsgEvent  wxMsgEvent=wxMsgEventService.getWxMsgEventByKey(eventKey, event);
		    	Map<String, Object> map =new HashMap<String, Object>();
		    	map.put("wxMsgEvent", wxMsgEvent);
		    	responseEntity.success(map,"操作成功");
	    	}catch (Exception e) {
		  	     e.printStackTrace();
			}
	   	    return responseEntity;
			
	    }
	    
	    
	    @RequestMapping(value="/domaterial")
	    @ResponseBody
	    public ResponseEntity domaterial(HttpServletRequest request, HttpServletResponse response){
	    	ResponseEntity responseEntity = new ResponseEntity();
	    	try{
		        String accessToken =tokenManager.getSSJAccessToken();
		        doNews(accessToken);//下载图文
		        doImages(accessToken);//下载图片
	    	}catch (Exception e) {
		  	     e.printStackTrace();
			}
	        return responseEntity;
	    }
	    
	    private Integer doNews(String accessToken){
	    	 String total_count="0";
	    	 WeixinMaterialListParam param = new WeixinMaterialListParam();
	    	 param.setType("news");
		     param.setOffset(0);
		     param.setCount(20);
	    	 try{
		        String wxurl = WeixinUtil.API_MATERIAL_GET.replace("ACCESS_TOKEN",accessToken);
		        JSONObject obj = WeixinUtil.httpRequest(wxurl, "POST",JSONObject.toJSON(param).toString());//只接受json格式参数
		        logger.info("下载微信图文信息结果:"+obj.toJSONString());
		        if(obj != null){
		            JSONArray array = obj.getJSONArray("item");
		            total_count = obj.getString("total_count");
	                
		            for (Object object : array) {
		            	try{
			                JSONObject o = (JSONObject)object;
			                String mediaId = o.getString("media_id");
			                
			                List<WxMaterial> list = wxMaterialService.getByWxMaterialId(mediaId);
			                if(list!=null && list.size()>0){//存在则不再保存
			                    continue;
			                }
			                JSONObject contents = o.getJSONObject("content");
			                Long createTime = contents.getLong("create_time");
			                JSONArray newItemArray = contents.getJSONArray("news_item");
			                for (Object object2 : newItemArray) {
			                    JSONObject o2 = (JSONObject)object2;
			                    String title = o2.getString("title");
			                    String author = o2.getString("author");
			                    String digest = o2.getString("digest");
			                    String content = o2.getString("content");
			                    String contentSourceUrl = o2.getString("content_source_url");
			                    String thumbMediaId = o2.getString("thumb_media_id");
			                    int showCoverPic = o2.getIntValue("show_cover_pic");
			                    String url = o2.getString("url");
			                    String thumbUrl = o2.getString("thumb_url");
			                    WxMaterial material = new WxMaterial();
			                    material.setTitle(title);
			                    material.setAuthor(author);
			                    material.setDigest(digest);
			                    material.setContent(content);
			                    material.setContentSourceUrl(contentSourceUrl);
			                    material.setThumbMediaId(thumbMediaId);
			                    material.setShowCoverPic(showCoverPic);
			                    material.setUrl(url);
			                    material.setMsgType(param.getType());
			                    material.setThumbUrl(thumbUrl);
			                    material.setMediaId(mediaId);
			                    material.setCreateDate(new Date(createTime * 1000));
			                    wxMaterialService.saveWxMaterial(material);
			                }
		            	 }catch (Exception e) {
		   				  e.printStackTrace();
		   		       }
		            }
		        }
		    }catch (Exception e) {
		    	 e.printStackTrace();
		    }
	    	 return Integer.parseInt(total_count);
	    }
	    
	    private Integer doImages(String accessToken){
	     String total_count="0";
	   	 WeixinMaterialListParam param = new WeixinMaterialListParam();
    	 param.setType("image");
	     param.setOffset(0);
	     param.setCount(20);
    	 try{
	        String wxurl = WeixinUtil.API_MATERIAL_GET.replace("ACCESS_TOKEN",accessToken);
	        JSONObject obj = WeixinUtil.httpRequest(wxurl, "POST",JSONObject.toJSON(param).toString());//只接受json格式参数
	        logger.info("下载微信图片信息结果:"+obj.toJSONString());
	        if(obj != null){
	            JSONArray array = obj.getJSONArray("item");
	            total_count = obj.getString("total_count");
	            for (Object object : array) {
	            	try{
		                JSONObject o = (JSONObject)object;
		                String mediaId = o.getString("media_id");
		                String url = o.getString("url");
		                String name = o.getString("name");
		                List<WxMaterial> list = wxMaterialService.getByWxMaterialId(mediaId);
		                if(list!=null && list.size()>0){//存在则不再保存
		                    continue;
		                }
		                WxMaterial material = new WxMaterial();
		                material.setTitle(name);
		                material.setThumbUrl(url);
		                material.setMsgType(param.getType());
		                material.setMediaId(mediaId);
		                wxMaterialService.saveWxMaterial(material); 
	            	 }catch (Exception e) {
	   				  e.printStackTrace();
	   		       }
	            }
	        }
	    }catch (Exception e) {
	    	 e.printStackTrace();
	    }
    	 return Integer.parseInt(total_count);
	  }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @return       
	    * 方法说明：管理目录页面
	     * @date 2017年10月31日 上午10:55:29
	     */
	    @RequestMapping("/main")
	    public String main() {
	        return "sys/menu/main";
	        
	        
	    }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @param parentId
	    * @param @return
	    * @param @throws Exception       
	    * 方法说明：管理目录页面数据
	     * @date 2017年11月1日 上午11:44:21
	     */
	    @RequestMapping("/tree")
	    @ResponseBody
	    public List<Menu> tree(@RequestParam(required = false, value = "id" ,defaultValue = "-1") String parentId) throws Exception {

	        return  menuService.getSubNodesByParentid(parentId);
	    }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @param model
	    * @param @param EQ_parentId
	    * @param @param pageSize
	    * @param @param pageNo
	    * @param @return
	    * @param @throws Exception       
	    * 方法说明：管理目录页面数据
	     * @date 2017年11月1日 上午11:44:57
	     */
	    @RequestMapping("/list")
	    public String list( Model model,@RequestParam(required = false, defaultValue = "0") String EQ_parentId,
				@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
	    	Map<String, Object> params = new HashMap<String, Object>();
	        params.put("EQ_parentId", EQ_parentId);
	        params.put("LIKE_menuName",request.getParameter("LIKE_menuName")==null?"":request.getParameter("LIKE_menuName"));
			SplitPage sp = new SplitPage();
		        sp.setAction(request.getRequestURI().toString());
		        sp.setPageNo(pageNo);
		        sp.setPageSize(pageSize);
		        sp.setParams(params);
		    Page<Menu> page= menuService.findByPage(params, initPage(pageNo,pageSize,Direction.ASC, new String[] { "menuOrder" }));
			sp.setRowCnt((int) page.getTotalElements());
			model.addAttribute("list", page.getContent());
			model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
			model.addAttribute("page", sp);
			model.addAttribute("search", params);
	        return "sys/menu/list";
	    }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @param id
	    * @param @param MenuOrder
	    * @param @return       
	    * 方法说明：修改排序
	     * @date 2017年10月31日 下午2:17:55
	     */
	    @RequestMapping(value = "/updateMenuOrder", method = RequestMethod.POST)
	    @ResponseBody
	    public Response updateMenuOrder(String id, Integer menuOrder){
	    	Response response = new  Response();
	    	menuService.updateMenuOrder(id, menuOrder);
	    	response.success();
	        return response;
	    }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @param request
	    * @param @param model
	    * @param @param id
	    * @param @param parentId
	    * @param @return
	    * @param @throws Exception       
	    * 方法说明：跳转添加目录页面
	     * @date 2017年10月31日 下午2:50:14
	     */
	    @RequestMapping(value = "/edit")
	    public String edit(HttpServletRequest request, Model model, String id,String parentId) throws Exception {
	    	Menu org = menuService.getById(id);
	    	if(org ==null){
	    		org = new Menu();
	    		org.setParentId(parentId);
	    	}
	    	 model.addAttribute("org", org);
	    	 return "sys/menu/edit";
	    }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @param org
	    * @param @return       
	    * 方法说明：保存目录方法
	     * @date 2017年11月1日 上午11:47:06
	     */
	    @RequestMapping(value = "/save", method = RequestMethod.POST)
	    @ResponseBody
	    public Response  updateMenuOrder(Menu org){
	    	Response response = new  Response();
	    	org.setInsertDate(new Date());
	    	org=menuService.save(org);
	    	response.success(org);
	        return response;
	    }
	    /**
	     * 
	    * 创建人:zhanglin
	    * @param @param id
	    * @param @return       
	    * 方法说明：删除目录方法
	     * @date 2017年11月1日 上午11:47:46
	     */
	    @RequestMapping(value = "/delete", method = RequestMethod.POST)
	    @ResponseBody
	    public Response  delete(String id){
	    	Response response = new  Response();
	    	menuService.delete(id);
	    	response.success();
	        return response;
	    }
	   
}
