package com.ssj.service.sys.push.service.impl;


import com.alibaba.fastjson.JSON;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.conch.conch.domain.SconPadInfo;
import com.ssj.bean.sys.push.domain.SconPushMessage;
import com.ssj.bean.sys.push.domain.SconXinge;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.dao.sys.push.dao.SconXingeDao;
import com.ssj.enums.XinGePushMessageTypeEnum;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.conch.conch.service.SconPadInfoService;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.push.service.SconPushMessageService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.sys.push.service.task.*;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.taskthread.ThreadPool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SconXingeServiceImpl extends BaseServiceImpl<SconXinge,String> implements SconXingeService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SconXingeDao dao;
    @Autowired
    private SconPushMessageService sconPushMessageService;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private ConchDerverService conchDerverService;
    @Autowired
	private EasemobService easemobService;
    @Autowired
    private UserService userService;
    @Autowired
    private SconPadInfoService sconPadInfoService;

    @Override
    public PagingAndSortingRepository<SconXinge, String> getDao() {
        return dao;
    }

	@Override
	public void saveOrUpdate(String userId, String xingeToken, String platform,int platformType) {
        SconXinge sconXinge = dao.findTopByPushUserIdAndPlatformType(userId,platformType);
        if(sconXinge == null) {
            //新增用户信鸽token信息
            sconXinge = new SconXinge();
            sconXinge.setPushUserId(userId);
            sconXinge.setPlatformType(platformType);
        }
        if(PushConstants.PUSH_ANDROID.equals(platform)) {
            sconXinge.setAndroidToken(xingeToken);
            sconXinge.setIosToken(null);
        }else if(PushConstants.PUSH_IOS.equals(platform)){
            sconXinge.setIosToken(xingeToken);
            sconXinge.setAndroidToken(null);
        }
        sconXinge.setCreateTime(new Date());
        this.save(sconXinge);
	}

	@Override
	public SconXinge findByPushUserIdAndPlatformType(String userId,int platformType) {
		return dao.findTopByPushUserIdAndPlatformType(userId,platformType);
	}
	
	@Override
	public void asynPushPdThreadTask(String derver, String content) {
		try {
			//贝壳端
			//通过贝壳获取小孩用户
			ConchDerver conchDerver = conchDerverService.findByDerver(derver);
			
			//上海版本的推送
			SconXinge sconXinge = this.findByPushUserIdAndPlatformType(derver, 1);
			if(sconXinge != null) {
				//判断当前环境是开发还是生产
	        	String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
				ThreadPool.getInstance().addTask(new XingePushThreadTask("私塾家", content, sconXinge.getAndroidToken(), sconXinge.getIosToken(), Constant.CONCH_PLATFORM_TYPE,null,null,null,Integer.valueOf(sysEnv),0));
				sconPushMessageService.savePushMessage(derver, Constant.CONCH_PLATFORM_TYPE, null, content, PushConstants.MESSAGE_TYPE_XINGE);
			}
			String  easemobName=tokenManager.getEasemob(derver);
			easemobName=StringUtils.isNotBlank(easemobName)?easemobName:conchDerver.getEasemobName();
			//上海的版本则走环信推送，环信号为conch_derver.user_id
			if(StringUtils.isNotBlank(easemobName)) {
				ThreadPool.getInstance().addTask(new EasemobConchPushThreadTask(easemobName, "私塾家", content, easemobService));
				sconPushMessageService.savePushMessage(derver, Constant.CONCH_PLATFORM_TYPE, null, content, PushConstants.MESSAGE_TYPE_EASEMOB);
			}
		}catch (Exception e) {
		}
	}
	
	
	@Override
	public void asynPushThreadTask(String pushUserId, String vipId, int platformType, String content, String pushModule) {
		try {
			String token = tokenManager.getToken(pushUserId,"APP");
			//如果是贝壳则走环信推送，其他端走信鸽推送
			if(platformType == 1) {
				//贝壳端
				//通过贝壳获取小孩用户
				ConchDerver conchDerver = conchDerverService.findByDerver(pushUserId);
				//校验小孩是否现在还是绑定该小塾
				if(StringUtils.isNotBlank(vipId) && !vipId.equals(conchDerver.getVipId())) {
					//该小孩当前不是绑定该小塾则不推送
					return;
				}
				if(conchDerver != null) {
					//如果是深圳的版本则走环信推送
					if(StringUtils.isNotBlank(conchDerver.getUserId())) {
						User childUser = userService.getById(conchDerver.getUserId());
						if(StringUtils.isNotBlank(childUser.getEasemobName())) {
							ThreadPool.getInstance().addTask(new EasemobConchPushThreadTask(childUser.getEasemobName(), "私塾家", content, easemobService));
							sconPushMessageService.savePushMessage(pushUserId, platformType, null, content, PushConstants.MESSAGE_TYPE_EASEMOB);
						}
					}
				}
			}else if(token != null){
				//判断用户的token是否失效，如果失效则不推送
				//走信鸽推送
				SconXinge sconXinge = this.findByPushUserIdAndPlatformType(pushUserId, platformType);
				if(sconXinge != null){
					if(PushConstants.PUSH_OTHER.equals(pushModule)) {
						//推送其他模块
						if(sconXinge.getOtherRemind() == 1) {
							return;
						}
					}else if(PushConstants.PUSH_HOMEWORK.equals(pushModule)) {
						//推送作业模块
						if(sconXinge.getHomeworkRemind() == 1) {
							return;
						}
					}else if(PushConstants.PUSH_PROBLEM.equals(pushModule)) {
						//推送难题模块
						if(sconXinge.getProblemRemind() == 1) {
							return;
						}
					}else if(PushConstants.PUSH_LESSON.equals(pushModule)) {
						//推送一对一模块
						if(sconXinge.getLessonRemind() == 1) {
							return;
						}
					}else if(sconXinge.getIsRemind() == 0 && platformType == 4) {
					    //如果是老师端设置了不推送
                        return;
                    }
					//判断当前环境是开发还是生产 ,安卓所有推通知去掉改推应用内消息
//		        	String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
//					ThreadPool.getInstance().addTask(new XingePushThreadTask("私塾家", content, sconXinge.getAndroidToken(), sconXinge.getIosToken(), platformType,null,null,null,Integer.valueOf(sysEnv),this.getAppBadge(pushUserId)));
//					sconPushMessageService.savePushMessage(pushUserId, platformType, null, content, PushConstants.MESSAGE_TYPE_XINGE);

					//判断当前环境是开发还是生产
					String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
					SconPushMessage sconPushMessage = sconPushMessageService.savePushMessage(pushUserId, platformType, "私塾家", content, PushConstants.MESSAGE_TYPE_XINGE);
					Map<String, Object> messageMap = new HashMap<>();
					//应用内消息
					messageMap.put("type", "NOTIFY_MESSAGE");
					messageMap.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));

					Map<String, Object> dataMap = new HashMap<>();
					dataMap.put("pushMessageId", sconPushMessage.getId());
					dataMap.put("title", sconPushMessage.getTitle());
					dataMap.put("content", sconPushMessage.getContent());
					dataMap.put("createTime", DateUtil.format_yyyyMMddHHmmss(sconPushMessage.getCreateTime()));
					messageMap.put("data", dataMap);
					if (StringUtils.isNotBlank(sconXinge.getAndroidToken())) {
						//推送Android客户端
						ThreadPool.getInstance().addTask(new XingeAndroidPushThreadTask("私塾家", JSON.toJSONString(messageMap), null, sconXinge.getAndroidToken(), platformType, "message"));
					} else if (StringUtils.isNotBlank(sconXinge.getIosToken())) {
						//推送IOS客户端
						ThreadPool.getInstance().addTask(new XingeIosPushThreadTask(content, sconXinge.getIosToken(), platformType, null, messageMap, Integer.valueOf(sysEnv),this.getAppBadge(pushUserId)));
					}
				}
			}
		}catch (Exception e) {
		}
	}

	@Override
	public void asynPushAllThreadTask(String title, String content, String platform, int platformType) {
		//判断当前环境是开发还是生产
    	String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
		ThreadPool.getInstance().addTask(new XingePushAllThreadTask(title, content, platform, platformType,Integer.valueOf(sysEnv)));
	}

	@Override
	public void asynPushOnlineMessageThreadTask(String pushUserId, Map<String, Object> custom) {
		//推送聊天应用内消息
		String token = tokenManager.getToken(pushUserId,"APP");
		//判断用户的token是否失效，如果失效则不推送
    	String content = JSON.toJSONString(custom);
    	//判断是否是有使用贝壳用户
    	ConchDerver conchDerver = conchDerverService.findByUserId(pushUserId);
    	if(conchDerver != null && StringUtils.isNotBlank(conchDerver.getUserId())) {
    		//贝壳端
			//通过贝壳获取小孩用户
			User childUser = userService.getById(conchDerver.getUserId());
			if(StringUtils.isNotBlank(childUser.getEasemobName())) {
				ThreadPool.getInstance().addTask(new EasemobConchPushThreadTask(childUser.getEasemobName(), "你有一条新消息!", content, easemobService));
				sconPushMessageService.savePushMessage(pushUserId, Constant.CONCH_PLATFORM_TYPE, null, content, PushConstants.MESSAGE_TYPE_EASEMOB);
			}
    	}
    	//推送给小塾学伴pad端
		List<SconPadInfo> padList = sconPadInfoService.findByUserId(pushUserId);
		for (SconPadInfo sconPadInfo : padList) {
			String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
			//判断是哪个平台
			if(PushConstants.PUSH_ANDROID.equals(sconPadInfo.getPlatform())) {
				//推送Android客户端
				ThreadPool.getInstance().addTask(new XingeAndroidPushThreadTask("私塾家", content, null, sconPadInfo.getXingeToken(), 6, "message"));
				sconPushMessageService.savePushMessage(sconPadInfo.getUserId(), 6, "私塾家", content, PushConstants.MESSAGE_TYPE_XINGE);
			}else if(PushConstants.PUSH_IOS.equals(sconPadInfo.getPlatform())) {
				//推送IOS客户端
				ThreadPool.getInstance().addTask(new XingeIosPushThreadTask("你有一条新消息!", sconPadInfo.getXingeToken(), 6, null, custom, Integer.valueOf(sysEnv),(int)custom.get("badge")));
				sconPushMessageService.savePushMessage(sconPadInfo.getUserId(), 6, "你有一条新消息!", content, PushConstants.MESSAGE_TYPE_XINGE);
			}
		}

    	if(token != null) {
			SconXinge sconXinge = dao.findTopByPushUserIdAndPlatformType(pushUserId, Constant.PARENT_PLATFORM_TYPE);
			if(sconXinge != null){
				//判断当前环境是开发还是生产
                sconPushMessageService.savePushMessage(pushUserId, Constant.PARENT_PLATFORM_TYPE, null, content, PushConstants.MESSAGE_TYPE_XINGE);
                String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
                if (StringUtils.isNotBlank(sconXinge.getAndroidToken())) {
                    //推送Android客户端
                    ThreadPool.getInstance().addTask(new XingeAndroidPushThreadTask("私塾家", content, custom, sconXinge.getAndroidToken(), Constant.PARENT_PLATFORM_TYPE, "message"));
                } else if (StringUtils.isNotBlank(sconXinge.getIosToken())) {
                    //推送IOS客户端
                    ThreadPool.getInstance().addTask(new XingeIosPushThreadTask("你有一条新消息!", sconXinge.getIosToken(), Constant.PARENT_PLATFORM_TYPE, null, custom, Integer.valueOf(sysEnv),(int)custom.get("badge")));
                }
			}
        }
	}

	@Override
	public void asynPushThreadTask(String pushUserId, int platformType, String messageType, String businessType, String title, String content, String tokenType, String pushModule) {
		try {
			String token = tokenManager.getToken(pushUserId, tokenType);
			if (token != null) {
				//判断用户的token是否失效，如果失效则不推送
				//走信鸽推送
				SconXinge sconXinge = this.findByPushUserIdAndPlatformType(pushUserId, platformType);
				if (sconXinge != null) {
					if (PushConstants.PUSH_OTHER.equals(pushModule)) {
						//推送其他模块
						if (sconXinge.getOtherRemind() == 1) {
							return;
						}
					} else if (PushConstants.PUSH_HOMEWORK.equals(pushModule)) {
						//推送作业模块
						if (sconXinge.getHomeworkRemind() == 1) {
							return;
						}
					} else if (PushConstants.PUSH_PROBLEM.equals(pushModule)) {
						//推送难题模块
						if (sconXinge.getProblemRemind() == 1) {
							return;
						}
					} else if (PushConstants.PUSH_LESSON.equals(pushModule)) {
						//推送一对一模块
						if (sconXinge.getLessonRemind() == 1) {
							return;
						}
					}else if(sconXinge.getIsRemind() == 0 && platformType == 4) {
                        //如果是老师端设置了不推送
                        return;
                    }
					//判断当前环境是开发还是生产
					String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
					SconPushMessage sconPushMessage = sconPushMessageService.savePushMessage(pushUserId, platformType, title, content, PushConstants.MESSAGE_TYPE_XINGE);
					Map<String, Object> messageMap = null;
					if ("message".equals(messageType)) {
						//应用内消息
						messageMap = new HashMap<>();
						messageMap.put("type", businessType);
						messageMap.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));

						Map<String, Object> dataMap = new HashMap<>();
						dataMap.put("pushMessageId", sconPushMessage.getId());
						dataMap.put("title", sconPushMessage.getTitle());
						dataMap.put("content", sconPushMessage.getContent());
						dataMap.put("createTime", DateUtil.format_yyyyMMddHHmmss(sconPushMessage.getCreateTime()));
						messageMap.put("data", dataMap);
					}
                    if (StringUtils.isNotBlank(sconXinge.getAndroidToken())) {
                        //推送Android客户端
                        ThreadPool.getInstance().addTask(new XingeAndroidPushThreadTask("私塾家", JSON.toJSONString(messageMap), null, sconXinge.getAndroidToken(), platformType, "message"));
                    } else if (StringUtils.isNotBlank(sconXinge.getIosToken())) {
                        //推送IOS客户端
                        ThreadPool.getInstance().addTask(new XingeIosPushThreadTask(content, sconXinge.getIosToken(), platformType, null, messageMap, Integer.valueOf(sysEnv),this.getAppBadge(pushUserId)));
                    }
				}
			}
		} catch (Exception e) {
			logger.error("信鸽异步推送异常", e);
		}
	}

	@Override
	public void asynPushGrowthReportThreadTask(String pushUserId, String vipId, String content, String businessType) {
		try {
			String token = tokenManager.getToken(pushUserId, "APP");
			if (StringUtils.isNotBlank(token)) {
				//判断用户的token是否失效，如果失效则不推送
				//走信鸽推送
				SconXinge sconXinge = this.findByPushUserIdAndPlatformType(pushUserId, 2);
				if (sconXinge != null) {
					//推送其他模块
					if (sconXinge.getOtherRemind() == 1) {
						return;
					}
					//判断当前环境是开发还是生产
					String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
					SconPushMessage sconPushMessage = sconPushMessageService.savePushMessage(pushUserId, 2, "学习成长报告", content, PushConstants.MESSAGE_TYPE_XINGE);
					//应用内消息
					Map<String, Object> messageMap = new HashMap<>();
					messageMap.put("type", businessType);
					messageMap.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));

					Map<String, Object> dataMap = new HashMap<>();
					dataMap.put("pushMessageId", sconPushMessage.getId());
					dataMap.put("title", sconPushMessage.getTitle());
					dataMap.put("vipId", vipId);
					dataMap.put("content", sconPushMessage.getContent());
					dataMap.put("createTime", DateUtil.format_yyyyMMddHHmmss(sconPushMessage.getCreateTime()));
					messageMap.put("data", dataMap);
					if (StringUtils.isNotBlank(sconXinge.getAndroidToken())) {
						//推送Android客户端
						ThreadPool.getInstance().addTask(new XingeAndroidPushThreadTask("私塾家", JSON.toJSONString(messageMap), null, sconXinge.getAndroidToken(), 2, XinGePushMessageTypeEnum.Message.getCode()));
					} else if (StringUtils.isNotBlank(sconXinge.getIosToken())) {
						//推送IOS客户端
						ThreadPool.getInstance().addTask(new XingeIosPushThreadTask(content, sconXinge.getIosToken(), 2, null, messageMap, Integer.valueOf(sysEnv),this.getAppBadge(pushUserId)));
					}
				}
			}
		} catch (Exception e) {
			logger.error("信鸽异步推送异常", e);
		}
	}

    /**
     * 通过vipId查询scon_pad_info表获取信鸽推送消息推送不同平台
     * @param vipId 小孩vipId
     * @param custom 推送json内容
     */
    @Override
    public void asynPushPadThreadTask(String vipId, String title, Map<String, Object> custom) {
        List<SconPadInfo> padList = sconPadInfoService.findByVipId(vipId);
        //判断当前环境是开发还是生产
        String sysEnv = (String) SystemResourceLocator.getValue("SYS_ENV");
        for (SconPadInfo sconPadInfo : padList) {
            if(sconPadInfo.getIsRemind() == 1) {
                //判断是哪个平台
                if(PushConstants.PUSH_ANDROID.equals(sconPadInfo.getPlatform())) {
                    //推送Android客户端
					if(custom == null) {
						SconPushMessage sconPushMessage = sconPushMessageService.savePushMessage(sconPadInfo.getUserId(), sconPadInfo.getType(), "私塾家", title, PushConstants.MESSAGE_TYPE_XINGE);
						custom = new HashMap<>();
						//应用内消息
						custom.put("type", "NOTIFY_MESSAGE");
						custom.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));

						Map<String, Object> dataMap = new HashMap<>();
						dataMap.put("pushMessageId", sconPushMessage.getId());
						dataMap.put("title", sconPushMessage.getTitle());
						dataMap.put("content", sconPushMessage.getContent());
						dataMap.put("createTime", DateUtil.format_yyyyMMddHHmmss(sconPushMessage.getCreateTime()));
						custom.put("data", dataMap);
					}else {
						custom.put("title", "私塾家");
						custom.put("content", title);
						sconPushMessageService.savePushMessage(sconPadInfo.getUserId(), sconPadInfo.getType(), title, JSON.toJSONString(custom), PushConstants.MESSAGE_TYPE_XINGE);
					}
                    ThreadPool.getInstance().addTask(new XingeAndroidPushThreadTask(title, JSON.toJSONString(custom), null, sconPadInfo.getXingeToken(), sconPadInfo.getType(), "message"));
                }else if(PushConstants.PUSH_IOS.equals(sconPadInfo.getPlatform())) {
                    //推送IOS客户端
                    ThreadPool.getInstance().addTask(new XingeIosPushThreadTask(title, sconPadInfo.getXingeToken(), sconPadInfo.getType(), null, custom, Integer.valueOf(sysEnv),0));
                    sconPushMessageService.savePushMessage(sconPadInfo.getUserId(), sconPadInfo.getType(), title, JSON.toJSONString(custom), PushConstants.MESSAGE_TYPE_XINGE);
                }
            }
        }
    }

    private int getAppBadge(String userId) {
        String badge = tokenManager.getString("APP_BADGE_"+userId);
        if(StringUtils.isNotBlank(badge)) {
            return  Integer.valueOf(badge);
        }
        return  0;
    }

}
