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.weixin.message.domain.MessageReply;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
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.StringUtil;
import com.ssj.framework.weixin.util.MUDload;
import com.ssj.framework.weixin.util.WeixinMedia;
import com.ssj.service.sys.sort.service.SortService;
import com.ssj.service.weixin.message.service.MessageReplyService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
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.*;

@RequestMapping("sys/wx")
@Controller
public class WeiXinController  extends BaseController {
	
	@Autowired
	private UserService userService;
    @Autowired
    private SortService sortService;
    @Autowired
	private MessageReplyService messageReplyService;
    
    @Autowired
	private PushTemplateService pushTemplateService;

	@Autowired
	private TokenManager tokenManager;
	


	
    @RequestMapping("/userList")
	 public String userList(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"));
		 params.put("subscribe", request.getParameter("subscribe")==null?"":request.getParameter("subscribe"));
		 params.put("beginDate", request.getParameter("beginDate")==null?"":request.getParameter("beginDate"));
		 params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));
		SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	    Page<Map<String, Object>> page= userService.getWXUser(params, initPage(pageNo,pageSize));
	    List<Map<String, Object>> list = page.getContent();
		sp.setRowCnt((int)page.getTotalElements());
		model.addAttribute("list", list);
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		 
	     return "sys/wx/userList";
	 }
    
    
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Response update(String id){
    	Response response = new  Response();
    	userService.uploadUser(id);
    	response.success();
    	return response;
    }
    @RequestMapping(value = "/updateAll", method = RequestMethod.POST)
    @ResponseBody
    public Response updateAll(){
    	Response response = new  Response();
	    userService.uploadUserAll();
    	response.success();
    	return response;
    }
    
    
    @RequestMapping("/wxPush")
  	public String wxPush(Model model) throws Exception{
  	    return "sys/wx/wxPush";
    }
    
    
    @RequestMapping(value = "/sendPush", method = RequestMethod.POST)
    @ResponseBody
    public Response sendPush(String wxId,String openIds,String jsoText,String clickUrl){
    	Response response = new  Response();
    	if(StringUtils.isEmpty(openIds)){
    		response.failure("推送id为空");
    		return response;
    	}
    	if(StringUtils.isEmpty(openIds)){
    		response.failure("openIds为空");
    		return response;
    	}
    	if(StringUtils.isEmpty(jsoText)){
    		response.failure("jsoText为空");
    		return response;
    	}
    	Map<String,String> data =new HashMap<String, String>();
		JSONArray ja=JSONArray.parseArray(jsoText);
		for (Object object : ja) {
			JSONObject jo=(JSONObject)object;
			data.put(jo.getString("name"),jo.getString("val"));
		}
		String[] os=openIds.split(";");
		Set<String> oset=new HashSet<String>();//过滤重复
		for (String openId : os) {
			oset.add(openId);
		}
		for (String openId : oset) {
			try {
				SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, wxId, StringUtils.isNotEmpty(clickUrl)?clickUrl:null, data);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
			} catch (Exception e) {
				logger.error("/sendPush推送异常..."+e.getMessage());
			}
		}
    	response.success();
    	return response;
    }

	@RequestMapping("/messageReply")
	public String messageReply(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("LIKE_keyword", request.getParameter("LIKE_keyword")==null?"":request.getParameter("LIKE_keyword"));
		params.put("EQ_type","normal");
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<MessageReply> page= messageReplyService.findByPage(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/wx/messageReply";
	}
	@RequestMapping("/messageAdd")
	public String messageAdd(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {
		MessageReply message= messageReplyService.getById(id);
		if(message==null) {
			message = new MessageReply();
		}
		model.addAttribute("ws", message);
		return "sys/wx/messageAdd";
	}
	@RequestMapping(value = "/messageSave", method = RequestMethod.POST)
	@ResponseBody
	public Response messageSave(MessageReply message){
    	logger.info(message.toString());
		Response response = new Response();
		//调用微信公众号上传临时素材接口
		if(StringUtil.isNotBlank(message.getImgUrl())){
			try {
                WeixinMedia wxMedia = null;
				if(StringUtil.isNotBlank(message.getId())){//更新操作
					if(StringUtil.isNotBlank(message.getCreated())){//之前就存在图片
                        MessageReply oldMessage = messageReplyService.findById(message.getId());
                        Long created = Long.parseLong(message.getCreated());
                        Long now = System.currentTimeMillis();
                        //超过3天media_id失效或图片发生改变需重新获取
                        if(now/1000 - created >= 259200
                                || !(message.getImgUrl().equals(oldMessage.getImgUrl())) ){
                            wxMedia = MUDload.uploadMedia(tokenManager.getSSJAccessToken(), "image", message.getImgUrl());
                        }
                    }else{//之前只存在文字情况
                        wxMedia = MUDload.uploadMedia(tokenManager.getSSJAccessToken(), "image", message.getImgUrl());
                    }
				}else{//新增操作
                    wxMedia = MUDload.uploadMedia(tokenManager.getSSJAccessToken(), "image", message.getImgUrl());
				}
				if(wxMedia != null){
                    logger.info("上传图片返回数据-->"+JSONObject.toJSONString(wxMedia));
                    message.setMediaId(wxMedia.getMediaId());
                    message.setCreated(Integer.toString(wxMedia.getCreatedAt()));
                }
			}catch (Exception e){
				response.failure(e.getMessage());
				e.printStackTrace();
			}
		}
		message=messageReplyService.save(message);
		response.success(message);
		return response;
	}
	@RequestMapping(value = "/messageDelete", method = RequestMethod.POST)
	@ResponseBody
	public Response messageDelete(String id){
		Response response = new  Response();
		messageReplyService.delete(id);
		response.success();
		return response;
	}
	@RequestMapping("/posterReply")
	public String posterReply(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("LIKE_keyword", request.getParameter("LIKE_keyword")==null?"":request.getParameter("LIKE_keyword"));
		params.put("EQ_type","poster");
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<MessageReply> page= messageReplyService.findByPage(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/wx/posterReply";
	}
	@RequestMapping("/posterAdd")
	public String posterAdd(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {
		MessageReply message= messageReplyService.getById(id);
		if(message==null) {
			message = new MessageReply();
		}
		model.addAttribute("ws", message);
		return "sys/wx/posterAdd";
	}
    @RequestMapping(value = "/posterSave", method = RequestMethod.POST)
    @ResponseBody
    public Response posterSave(MessageReply message){
        logger.info(message.toString());
        Response response = new Response();
        messageReplyService.save(message);
        response.success();
        return response;
    }
}
