package com.ssj.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.sys.role.domain.AdminOrg;
import com.ssj.bean.sys.role.domain.Role;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.MD5;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.PasswordUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.sys.role.service.AdminOrgService;
import com.ssj.service.sys.role.service.AdminService;
import com.ssj.service.sys.role.service.RoleService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibOrderDetailsService;
import com.ssj.service.weixin.sales.service.LibStaffingService;
import com.ssj.weixin.utils.MenuManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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 java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("sys/role")
@Controller
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private AdminService adminService;
	
    @Autowired
	private ILibJoinService libJoinService;
    
    @Autowired
	private TokenManager tokenManager;
    
    @Autowired
	private LibOrderDetailsService orderDetailService;
    
    @Autowired
	private PushTemplateService pushTemplateService;
    
    @Autowired
	private LibStaffingService libStaffingService;
    @Autowired
    private AdminOrgService adminOrgService;
    
	/**
	 * 列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping("/rolelist")
	 public String rolelist(Model model,
	    		@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("name", request.getParameter("name")==null?"":request.getParameter("name"));
		    SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	     Page<Map<String, Object>> page= roleService.findForPage(params, initPage(pageNo,pageSize));
		 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/role/rolelist";
	 }
	 /**
	  * 新增角色或修改角色
	  * @param model
	  * @return
	  */
	 @RequestMapping("/addrole")
	 public String addrole(Model model,@RequestParam(required = false, defaultValue = "1")String id){
		 Role role = roleService.getById(id);
		 if(role ==null ) role =new Role();
		 model.addAttribute("role", role);
		 return "sys/role/roleadd";
	 }
        /**
         * 保存角色
         * @param role
         * @return
         */
	 
	    @RequestMapping(value = "/save", method = RequestMethod.POST)
	    @ResponseBody
	    public Response save(Role role){
	    	Response response = new  Response();
	    	role.setCreateTime(new Date());
	    	role.setUpdateTime(new Date());
	    	role=roleService.save(role);
	    	response.success(role);
	        return response;
	    }
	    /**
	     * 保存角色权限
	     * @param role
	     * @return
	     */
	    @RequestMapping(value = "/addRoleCompetence", method = RequestMethod.POST)
	    @ResponseBody
	    public Response addRoleCompetence(String id, @RequestParam(value = "menuIds[]")String[] menuIds){
	    	return roleService.addRoleCompetence(id, menuIds);
	    }
	    /**
	     * 保存角色权限
	     * @param role
	     * @return
	     */
	    @RequestMapping(value = "/saveAdminOrgCode", method = RequestMethod.POST)
	    @ResponseBody
	    public Response saveAdminOrgCode(String  datatmp,String adminId){
	    	Response response = new  Response();
	    	List<AdminOrg> org =JSON.parseArray(datatmp, AdminOrg.class);
	    	adminOrgService.saveAdminOrg(org, adminId);
			response.success();
			return response;
	    }
	    /**
	     * 删除角色
	     * @param id
	     * @return
	     */
	    @RequestMapping(value = "/delete", method = RequestMethod.POST)
	    @ResponseBody
	    public Response delete(String id){
	    	return roleService.deleteRole(id);
	    }
	    /**
	     * 验证角色名是否存在
	     * @param name
	     * @param id
	     * @return
	     */
	    @RequestMapping("/validateRole")
		@ResponseBody
		public boolean validateRole(String name,String id) {
			return roleService.validateRole(name, id);
	    }
	    /**
	     * 分配资源
	     * @param model
	     * @param id
	     * @return
	     */
	     @RequestMapping("/competence")
		 public String competence(Model model,String id){
			 model.addAttribute("id", id);
			 return "sys/role/competence";
		 }
	     @RequestMapping("/competenceAdmin")
	     public String competenceAdmin(Model model,String id){
	    	 model.addAttribute("id", id);
	    	 return "sys/role/competenceAdmin";
	     }
	     /**
	      * 获取角色已有的菜单权限
	      * @param id
	      * @return
	      */
	     @RequestMapping(value = "/getAdminOrg", method = RequestMethod.POST)
	     @ResponseBody
	     public List<AdminOrg>  getAdminOrg(String id){
	    	 List<AdminOrg>  list = adminOrgService.findByAdminId(id);
	    	 return list;
	     } 
	     /**
	      * 获取角色已有的菜单权限
	      * @param id
	      * @return
	      */
	     @RequestMapping(value = "/getRoleMenu", method = RequestMethod.POST)
	     @ResponseBody
	     public List<String>  getRoleMenu(String id){
	    	 List<String>  list = roleService.getRoleMenu(id);
	    	 return list;
	     } 
	     
	     
	     
	     /**
	 	 * 用户列表
	 	 * @param model
	 	 * @param pageSize
	 	 * @param pageNo
	 	 * @return
	 	 * @throws Exception
	 	 */
	 	 @RequestMapping("/adminlist")
	 	 public String adminlist(Model model,
	 	    		@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("nickName",  request.getParameter("nickName")==null?"":request.getParameter("nickName"));
		 		// params.put("orgCode", orgCode());
		 		// params.put("operId", adminId());
		 		 
	 			    SplitPage sp = new SplitPage();
	 		        sp.setAction(request.getRequestURI().toString());
	 		        sp.setPageNo(pageNo);
	 		        sp.setPageSize(pageSize);
	 		        sp.setParams(params);
	 		     Page<Map<String, Object>> page= adminService.findByPageMap(params, initPage(pageNo,pageSize));
	 			 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/role/adminlist";
	 	 }
	 	 /**
	 	  *  新增用户
	 	  * @param model
	 	  * @param id
	 	  * @return
	 	  */
	 	 @RequestMapping("/adminAdd")
	 	 public String adminAdd(Model model,@RequestParam(required = false, defaultValue = "1")String id){
	 		 Admin admin = adminService.getById(id);
	 		 if(admin !=null){
	 			 model.addAttribute("admin", admin);
		 		 return "sys/role/adminEdit";
	 		 }else{
	 			admin =new Admin();
	 			admin.setOperId(adminId());
	 		 }
	 		 model.addAttribute("admin", admin);
	 		 return "sys/role/adminAdd";
	 	 }
	 	 /**
	 	  * 验证改用户是否存在
	 	  * @param loginName
	 	  * @return
	 	  */
	 	    @RequestMapping("/validateLoginName")
	 	    @ResponseBody
	 	    public boolean validateLoginName( String loginName,String id) {
	 	        return adminService.validateLoginName(loginName, id);
	 	    }
	 	    /**
	 	     * 保存用户
	 	     * @param admin
	 	     * @return
	 	     */
	 	    @RequestMapping(value = "/saveAdmin", method = RequestMethod.POST)
	 	    @ResponseBody
	 	    public Response saveAdmin(Admin admin){
	 	    	Response response = new  Response();
				String md5Pwd = MD5.getMD5(admin.getPassword().getBytes());
	 	    	if(StringUtils.isNotEmpty(admin.getId())){
					Admin oldAdmin = adminService.getById(admin.getId());
					if (md5Pwd.equals(oldAdmin.getPassword())) {
						return response.failure("新密码不能与旧密码一致");
					}
				}
				if (md5Pwd.equals(admin.getLoginName())) {
					return response.failure("密码不能和用户名一致");
				}
				if (!PasswordUtil.checkRule(admin.getPassword())) {
					return response.failure(PasswordUtil.CHECK_FAIL_MESSAGE);
				}
				if(StringUtils.isEmpty(admin.getId())) {
					admin.setCreateTime(new Date());
				}
	 	    	admin.setUpdateTime(new Date());
	 	    	admin.setPassword(md5Pwd);
	 	    	admin.setStatus(1);
	 	    	adminService.save(admin);
	 	    	//roleService.saveAdminRole(admin.getId(), "cac0a05e-2e81-4a51-9593-ec7a4fd40cf4");
	 	    	response.success();
	 	    	return response;
	 	    }
	 	    /**
	 	     * 删除用户
	 	     * @param id
	 	     * @return
	 	     */
	 	    @RequestMapping(value = "/deleteAdmin", method = RequestMethod.POST)
	 	    @ResponseBody
	 	    public Response deleteAdmin(String id){
	 	    	Response response = new  Response();
	 	    	Admin admin =adminService.getById(id);
	 	    	admin.setStatus(2);
	 	    	adminService.save(admin);
	 	    	response.success();
	 	    	return response;
	 	    }
	 	    /**
	 	     * 分配权限
	 	     * @param model
	 	     * @param id
	 	     * @return
	 	     */
	 	    @RequestMapping("/adminRoleList")
	 	    public String adminRoleList(Model model,@RequestParam(defaultValue = "1")String id,
		    		@RequestParam(required = false, defaultValue = "20") int pageSize,
					@RequestParam(required = false, defaultValue = "1") int pageNo){
	 	    	 Map<String, Object> params = new HashMap<String, Object>();
	 			 params.put("name", request.getParameter("name") !=null ? request.getParameter("name"):"");
	 			 params.put("id", request.getParameter("id") !=null ? request.getParameter("id") :id);
	 			    SplitPage sp = new SplitPage();
	 		        sp.setAction(request.getRequestURI().toString());
	 		        sp.setPageNo(pageNo);
	 		        sp.setPageSize(pageSize);
	 		        sp.setParams(params);
	 		     Page<Map<String, Object>> page= roleService.findForPage(params, initPage(pageNo,pageSize));
	 			 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/role/adminRoleList";
	 	    }
		   
	 	    
	 	   /**
	 	    * 获取所有的角色 
	 	    * @return
	 	    */
	 	    @RequestMapping(value = "/queryAllRoleList", method = RequestMethod.POST)
		    @ResponseBody
		    public List<Role> queryAllRoleList(){
		        return roleService.findAll();
		    }
	 	    
	 	   /**
		      * 获取用户对应的角色
		      * @param id
		      * @return
		      */
		     @RequestMapping(value = "/getAdminRole", method = RequestMethod.POST)
		     @ResponseBody
		     public List<String>  getAdminRole(String id){
		    	 List<String>  list = roleService.getAdminRole(id);
		    	 return list;
		     } 
		     
		     
		     /**
			     * 保存角色权限
			     * @param role
			     * @return
			     */
			    @RequestMapping(value = "/saveAdminRole", method = RequestMethod.POST)
			    @ResponseBody
			    public Response saveAdminRole(String id, @RequestParam(value = "roleIds[]")String[] roleIds){
			    	return roleService.saveAdminRole(id, roleIds);
			    } 
			    
			    
		 /**
		  * 生成微信菜单	    
		  * @param model
		  * @return
		  */
		 @RequestMapping("/weixinMenu")
	     public String weixinMenu(Model model){
			  return "sys/role/weixinMenu";
		 }
		 /**
		  * 保存微信菜单
		  * @param menu
		  * @return
		  */
		@RequestMapping(value = "/saveWeiXinMenu", method = RequestMethod.POST)
		@ResponseBody
		public Response updateUserIsTeacherType(String menu) {
		 		Response response = new Response();
		 		try {
		 			if(menu!=null){
		 				JSONObject jsonObject =	MenuManager.getMenu(tokenManager.getSSJAccessToken(), menu);
		 				logger.error("修改微信菜单返回信息--->"+jsonObject);
		 				if (null != jsonObject) {  
		 					if(jsonObject.getIntValue("errcode")==0){
		 						response.success("修改成功");
		 					}else{
		 						response.failure("修改失败");
		 					}
		 				}else{
		 					response.failure("修改失败");
		 				}
		 			
		 			}else{
		 				response.failure("修改失败");
		 			}
		 		} catch (Exception e) {
		 			e.printStackTrace();
		 			response.failure("修改失败：" + e.getMessage());
		 		}
		 		return response;
		 	}
		
//		@RequestMapping(value = "/sendMsg")
//		@ResponseBody
//		public ResponseEntity sendMsg(HttpServletRequest request,Model model, final String sendType,final String sendMan){
//			ResponseEntity response = new ResponseEntity();
//	   	    Thread t1 = new Thread(new Runnable() {
//	           public void run() {
//	           	send(sendType,sendMan);
//	           }
//	       });
//	       t1.start();
//	   	response.success();
//			return response;
//		}
		
		/**
		 * 列表
		 * @param model
		 * @param pageSize
		 * @param pageNo
		 * @return
		 * @throws Exception
		 */
		 @RequestMapping("/pushlist")
		 public String pushlist(Model model,
		    		@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("name", request.getParameter("name")==null?"":request.getParameter("name"));
			    SplitPage sp = new SplitPage();
		        sp.setAction(request.getRequestURI().toString());
		        sp.setPageNo(pageNo);
		        sp.setPageSize(pageSize);
		        sp.setParams(params);
		     Page<Map<String, Object>> page= roleService.findForPushPage(params, initPage(pageNo,pageSize));
			 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/role/pushlist";
		 }
		
		 @RequestMapping(value = "/pushOne", method = RequestMethod.POST)
		 @ResponseBody
		public Response pushOne(String child_name,String details,String flowId,String price,String endTime,String libId,String xs_openid,String league_name,String wx_account) {
	 		Response response = new Response();
	 		try {
	 			Map<String,String> data =new HashMap<String, String>();
				data.put("first", "销售您好，"+child_name+"的会员卡，即将到期，请及时跟进沟通\n");
				data.put("keyword1",details);
				data.put("keyword2",flowId);
				data.put("keyword3", price);
				data.put("keyword4", DateHelper.format(DateHelper.parseDate(endTime, "yyyy-MM-dd HH:mm:ss.SSS"),"yyyy年MM月dd日 HH:mm ") );
				data.put("remark", "\n请注意时间，防止过期失效");
				String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate102");
				SendTemplateShort sendTemplateShort=new SendTemplateShort(xs_openid, template_id_short, null, data);
				pushTemplateService.savePushWxTemplate(sendTemplateShort);
				
				//推送给CD
				List<String> userList= libStaffingService.findByCDAndOpenId(libId, "s_cd");
				if(userList !=null && userList.size()>0){
					for (String openId : userList) {
						    data =new HashMap<String, String>();
							data.put("first", "馆长您好，"+child_name+"的会员卡，即将到期，请及时跟进沟通\n");
							data.put("keyword1",details);
							data.put("keyword2",flowId);
							data.put("keyword3", price);
							data.put("keyword4",DateHelper.format(DateHelper.parseDate(endTime, "yyyy-MM-dd HH:mm:ss.SSS"),"yyyy年MM月dd日 HH:mm ") );
							data.put("remark", "\n请注意时间，防止过期失效");
							template_id_short=(String) SystemResourceLocator.getValue("sendTemplate102");
							sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
							pushTemplateService.savePushWxTemplate(sendTemplateShort);
							
						}
				}
				//会员卡到期通知，家长端收到模板消息推送，动态跳转到购买页面
				// wU5wpGnTXT2jBu0RAlsL1lu6LDfPyT37KZqjiieadH0
				Map<String,String> dataMap =new HashMap<String, String>();
				dataMap.put("first", child_name+"妈妈/爸爸，您好，您为孩子在"+league_name+"购买的会员卡，即将到期\n");
				dataMap.put("keyword1",details);
				dataMap.put("keyword2", DateHelper.format(DateHelper.parseDate(endTime, "yyyy-MM-dd HH:mm:ss.SSS"), "yyyy年MM月dd日 HH:mm "));
				dataMap.put("remark", "\n请注意时间，防止过期失效");
				template_id_short=(String) SystemResourceLocator.getValue("sendTemplate103");
				 String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/payment/xuVipBuy_"+libId+".html";
				sendTemplateShort=new SendTemplateShort(wx_account, template_id_short, url, dataMap);
				pushTemplateService.savePushWxTemplate(sendTemplateShort);
				response.success("推送成功");
			} catch (Exception e) {
				response.failure("推送失败：" + e.getMessage());
			}
	 		 
	 		return response;
		}
		 
		@RequestMapping(value = "/pushAll", method = RequestMethod.POST)
		@ResponseBody
		public Response pushAll() {
	 		Response response = new Response();
	 		try {
	 			orderDetailService.getExpiredTemplate();
	 			response.success("推送成功");
			} catch (Exception e) {
				response.failure("推送失败：" + e.getMessage());
			}
	 		return response;
		}
		 
		public void send(String sendType,String sendMan){
//			TbActivity activity = activityService.findCurrentlyActivity();
//			List<TbActivityJoin> joinList = joinService.findAll();
//			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/activity/toRanking.html";
//			String endUrl=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/activity/doubleNinth.html";
//			String template_id=(String) SystemResourceLocator.getValue("sendTemplate27");
//			if(sendType.equals("1") && sendMan.equals("1")){ //sendType ==1 活动没结束 sendMan = 1测试人员
//				//发送给纯真 67ae161a-9cfe-4150-9afd-4dfb6131754b
//				User user = userService.getById("67ae161a-9cfe-4150-9afd-4dfb6131754b");
//				Map<String, Object> map = joinService.findUserScore(user.getId(),activity.getId());
//				
//				Map<String,String> data =new HashMap<String, String>();
//				data.put("first","感谢您参与重阳节活动\n");
//				data.put("keyword1",map.get("integral").toString()+",排名第"+map.get("ranking").toString());
//				data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
//				data.put("remark","\n距离活动结束还有1天，抓紧时间继续邀请好友助力吧~");
//				NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,url,data));
//			}else if (sendType.equals("2") && sendMan.equals("1")){ //活动结束，测试人员
//				User user = userService.getById("67ae161a-9cfe-4150-9afd-4dfb6131754b");
//				Map<String, Object> map = joinService.findUserScore(user.getId(),activity.getId());
//				Map<String,String> data =new HashMap<String, String>();
//				data.put("first","亲爱的"+user.getName()+"，您参加的重阳节活动已经结束啦！");
//				data.put("keyword1",map.get("integral").toString());
//				data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
//				data.put("remark","\n快来看看你的排名及获奖情况吧~");
//				NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,endUrl,data));
//			}else if (sendType.equals("1") && sendMan.equals("2")){
//				for(TbActivityJoin join : joinList){
//					User user = userService.getById(join.getUserId());
//					Map<String, Object> map = joinService.findUserScore(join.getUserId(),activity.getId());
//					Map<String,String> data =new HashMap<String, String>();
//					data.put("first","感谢您参与重阳节活动\n");
//					data.put("keyword1",map.get("integral").toString()+",排名第"+map.get("ranking").toString());
//					data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
//					data.put("remark","\n距离活动结束还有1天，抓紧时间继续邀请好友助力吧~");
//					NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,url,data));
//				}
//			}else if(sendType.equals("2") && sendMan.equals("2")){
//				for(TbActivityJoin join : joinList){
//					User user = userService.getById(join.getUserId());
//					Map<String, Object> map = joinService.findUserScore(join.getUserId(),activity.getId());
//					Map<String,String> data =new HashMap<String, String>();
//					data.put("first","亲爱的"+user.getName()+"，您参加的重阳节活动已经结束啦！");
//					data.put("keyword1",map.get("integral").toString());
//					data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
//					data.put("remark","\n快来看看你的排名及获奖情况吧~");
//					NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,endUrl,data));
//				}
//			}
			
		}	
	
}
