package com.goafanti.message.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goafanti.common.dao.JpushEasemobAccountMapper;
import com.goafanti.common.dao.MessageFromSystemMapper;
import com.goafanti.common.dao.MessageProducerMapper;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.JpushEasemobAccount;
import com.goafanti.common.model.MessageConsumer;
import com.goafanti.common.model.MessageFromSystem;
import com.goafanti.common.model.MessageProducer;
import com.goafanti.common.model.User;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.message.JGMessageHelper;
import com.goafanti.message.bo.IndexBo;
import com.goafanti.message.bo.MessageBo;
import com.goafanti.message.bo.MessageListBo;
import com.goafanti.message.enums.ConsumerType;
import com.goafanti.message.enums.RecommendType;
import com.goafanti.message.enums.SubjectType;
import com.goafanti.message.service.MessageService;

@Service
public class MessageServiceImpl  extends BaseMybatisDao<MessageFromSystemMapper> implements MessageService{
	@Autowired
	private MessageFromSystemMapper messageFromSystemMapper;
	@Autowired
	private MessageProducerMapper messageProducerMapper;
	@Autowired
	private JpushEasemobAccountMapper jpushEasemobAccountMapper;
	@Autowired
	private JGMessageHelper jgMessageHelper;
	@Override
	public String selectSendUser(Map<Integer, String> selectMap,Integer type) {
		if(selectMap.containsKey(ConsumerType.PERSON_CUSTOMER_RETAIL.getTypeCode())){ //客户散户
			return selectMap.get(ConsumerType.PERSON_CUSTOMER_RETAIL.getTypeCode());
		}else if(selectMap.containsKey(ConsumerType.ORGANIZATION_CUSTOMER_RETAIL.getTypeCode())){
			return selectMap.get(ConsumerType.ORGANIZATION_CUSTOMER_RETAIL.getTypeCode());
		}else if(selectMap.containsKey(ConsumerType.USER_RETAIL.getTypeCode())){
			return selectMap.get(ConsumerType.USER_RETAIL.getTypeCode()); //用户散户
		}else if(selectMap.containsKey(ConsumerType.SOCIETY_TAG.getTypeCode())){ // 社会标签
			String sql  = "select group_concat(id) from user where source=0 and status != 2 and society_tag in("+ selectMap.get(ConsumerType.SOCIETY_TAG.getTypeCode()) +")";		
			return messageFromSystemMapper.selectSendTarget(sql);
		}else if(selectMap.containsKey(ConsumerType.LOCATION.getTypeCode())){ //用户地区
			String sql = "";
			String result = "";
			if(selectMap.containsKey(ConsumerType.LOCATION_PROVINCE.getTypeCode())){ //省
				sql = "select group_concat(a.id) from user a left join user_identity b on a.id = b.uid where a.source=0 and b.province in (" + selectMap.get(ConsumerType.LOCATION_PROVINCE.getTypeCode()) + ")";
				String tmp=messageFromSystemMapper.selectSendTarget(sql);
				result +="," + tmp==null?"":tmp;
			}
			if(selectMap.containsKey(ConsumerType.LOCATION_CITY.getTypeCode())){ //市
				sql = "select group_concat(a.id) from user a left join user_identity b on a.id = b.uid where a.source=0 and b.city in (" + selectMap.get(ConsumerType.LOCATION_CITY.getTypeCode()) + ") and a.status != 2";
				String tmp=messageFromSystemMapper.selectSendTarget(sql);
				result +="," + tmp==null?"":tmp;
			}
			if(selectMap.containsKey(ConsumerType.LOCATION_AREA.getTypeCode())){ //区
				sql = "select group_concat(a.id) from user a left join user_identity b on a.id = b.uid where a.source=0 and b.area in (" + selectMap.get(ConsumerType.LOCATION_AREA.getTypeCode()) + ") and a.status != 2";
				String tmp=messageFromSystemMapper.selectSendTarget(sql);
				result +="," + tmp==null?"":tmp;
			}
			if(!result.equals("")&&result!=null){
				String data[] = result.substring(1).split(",");
				List<String> list = new ArrayList<String>();
				boolean flag;
				for(int i=0; i< data.length;i++){
					flag = false;
					for(int j=0; j<list.size(); j++){
						if(data[i].equals(list.get(j))){
							flag = true;
							break;
						}
					}
					if(!flag) list.add(data[i]);
				}
				String[] tmp = (String[])list.toArray(new String[list.size()]);
				return Arrays.toString(tmp);
			}
		}else if(selectMap.containsKey(ConsumerType.INDUSTRY.getTypeCode())){ //行业
			String sql = "select group_concat(a.id) from user a left join user_identity b on a.id = b.uid where a.source=0 and b.industry in (" + selectMap.get(ConsumerType.INDUSTRY.getTypeCode()) + ") and a.status != 2";
			if(messageFromSystemMapper.selectSendTarget(sql)==null){
				return "";
			}
			return messageFromSystemMapper.selectSendTarget(sql);
		}
		return "";
	}

	@Override
	public String selectSendAdmin(Map<Integer, String> selectMap,Integer type) {
		String sql = "";
		if(selectMap.containsKey(ConsumerType.COMPANY.getTypeCode())){			
			sql = "select group_concat(id) from admin where department_id in ("+ changeSql(selectMap.get(ConsumerType.COMPANY.getTypeCode())) + ")";
		}else if(selectMap.containsKey(ConsumerType.ROLE.getTypeCode())){
			sql = "select group_concat(id) from admin a left join user_role b on a.id = b.uid where b.rid in (" + changeSql(selectMap.get(ConsumerType.ROLE.getTypeCode())) + ")";
		}
		if(!sql.equals("")) return messageFromSystemMapper.selectSendTarget(sql);
		return "";
	}

	@Override
	public List<MessageFromSystem> selectRecommend(Map<Integer, String> selectMap,Integer type){
		String sql = "";
		if(selectMap.containsKey(RecommendType.TECH_SERVICE.getTypeCode())){ //科技服务
			sql = "select bname as title,introduce as body,id as resourceId from business_project where id in (" + changeSql(selectMap.get(RecommendType.TECH_SERVICE.getTypeCode())) + ")";
		}else if(selectMap.containsKey(RecommendType.PERSON_ACHIEVEMENT.getTypeCode())){ //个人成果
			sql = "select name as title,summary as body,id as resourceId from achievement  where id in (" + changeSql(selectMap.get(RecommendType.PERSON_ACHIEVEMENT.getTypeCode()))  +")";
		}else if(selectMap.containsKey(RecommendType.ORGANIZATION_ACHIEVEMENT.getTypeCode())){ //组织成果
			sql = "select name as title,summary as body,id as resourceId from achievement  where id in (" + changeSql(selectMap.get(RecommendType.ORGANIZATION_ACHIEVEMENT.getTypeCode())) +")";
		}else if(selectMap.containsKey(RecommendType.PERSONAL_DEMAND.getTypeCode())){ //个人需求
			sql = "select name as title,problem_des as body,id as resourceId from demand where id in (" + changeSql(selectMap.get(RecommendType.PERSONAL_DEMAND.getTypeCode())) +")";
		}else if(selectMap.containsKey(RecommendType.ORGANIZATION_DEMAND.getTypeCode())){ //组织需求
			sql = "select name as title,problem_des as body,id as resourceId from demand where id in (" + changeSql(selectMap.get(RecommendType.ORGANIZATION_DEMAND.getTypeCode())) +")";
		}else if(selectMap.containsKey(RecommendType.EXPERT.getTypeCode())){ //专家
			sql = "select nickname as title ,introduction as body,id as resourceId from user where id in("+ changeSql(selectMap.get(RecommendType.EXPERT.getTypeCode())) +")";
		}else if(selectMap.containsKey(RecommendType.NEWS.getTypeCode())){ //政策
			sql = "select title,summary as body,id as resourceId from news where id in("+ changeSql(selectMap.get(RecommendType.NEWS.getTypeCode())) +")";
		}
		if(!sql.equals("")) return messageFromSystemMapper.selectRecommendTarget(sql);
		return null;
	}
	
	@Override
	@Transactional
	public int insertSystemMessage(Map<Integer, String> targetMap, Integer targetType,String title, String body, 
			Integer subject,Date createTime,Integer isDraft) {
		MessageFromSystem mfs = new MessageFromSystem();
		mfs.setId(UUID.randomUUID().toString());
		mfs.setTitle(title);
		mfs.setBody(body);
		mfs.setCreateTime(createTime);
		mfs.setSubject(subject);
		mfs.setConsumerType(getTargetType(targetType));
		mfs.setIsDraft(isDraft);
		mfs.setDeleteSign(Boolean.FALSE);
		if(SecurityUtils.getSubject().getPrincipal() instanceof Admin){
			Admin admin = (Admin)SecurityUtils.getSubject().getPrincipal();
			mfs.setCreater(admin.getName());
			mfs.setProducerId(admin.getId());
		}
		messageFromSystemMapper.insert(mfs);
		List<MessageProducer> producerTarget = new ArrayList<MessageProducer>();
		List<MessageBo> sendTarget = new ArrayList<MessageBo>();
		String[] cids;
		if(subject == SubjectType.KE_HU.getTypeCode()){
			String tmp = selectSendUser(targetMap,targetType);
			if(tmp !=null){
				cids = tmp.split(",");
				MessageProducer mp;
				MessageBo bo;
				String registrationId = "";
				for(String cid : cids){
					mp = new MessageProducer();
					mp.setId(UUID.randomUUID().toString());
					mp.setMessageId(mfs.getId());
					mp.setConsumerId(cid);
					mp.setCreateTime(createTime);
					mp.setSendTime(createTime);
					producerTarget.add(mp);
					registrationId = messageFromSystemMapper.selectJPushAcc(cid);
					if(StringUtils.isNotBlank(registrationId)){
						bo = new MessageBo();
						bo.setMessageId(mfs.getId());
						bo.setMessageTitle(mfs.getTitle());
						bo.setMessageBody(mfs.getBody());
						bo.setRegistrationId(registrationId);
						sendTarget.add(bo);
					}
				}
			}
		}else if(subject == SubjectType.YUN_YING.getTypeCode()){
			String tmp = selectSendUser(targetMap,targetType);
			if(tmp !=null){
				cids = tmp.split(",");
				MessageProducer mp;
				MessageBo bo;
				String registrationId = "";
				for(String cid : cids){
					mp = new MessageProducer();
					mp.setId(UUID.randomUUID().toString());
					mp.setMessageId(mfs.getId());
					mp.setConsumerId(cid);
					mp.setCreateTime(createTime);
					mp.setSendTime(createTime);
					producerTarget.add(mp);
					registrationId = messageFromSystemMapper.selectJPushAcc(cid);
					if(StringUtils.isNotBlank(registrationId)){
						bo = new MessageBo();
						bo.setMessageId(mfs.getId());
						bo.setMessageTitle(mfs.getTitle());
						bo.setMessageBody(mfs.getBody());
						bo.setRegistrationId(registrationId);
						sendTarget.add(bo);
					}
				}
			}			
		}
		if(producerTarget.size()>0) insertBatchProducer(producerTarget);
		//推送消息
		if(sendTarget.size()>0) jgMessageHelper.sendSystemMessage(sendTarget);
		return 1;
	}
	
	@Override
	@Transactional
	public int insertRecommendMessage(Map<Integer, String> sourceMap, Integer sourceType, Map<Integer, String> targetMap,
			Integer targetType,Integer subject,Integer isDraft) {
		List<MessageFromSystem> mfsList = selectRecommend(sourceMap, sourceType);
		List<MessageProducer> producerTarget = new ArrayList<MessageProducer>();
		List<MessageFromSystem> messageTarget = new ArrayList<MessageFromSystem>();
		List<MessageBo> sendTarget = new ArrayList<MessageBo>();
		if(mfsList != null && mfsList.size()>0){
			MessageFromSystem message = null;
			for(MessageFromSystem mfs : mfsList){
				message = new MessageFromSystem();
				String messageId = "";
				Date createTime = new Date();
				message.setCreateTime(createTime);	
				message.setSubject(subject);
				message.setConsumerType(getTargetType(targetType)); //适配客户类型
				message.setResourceType(getSourceType(sourceType)); //适配成果需求
				message.setIsDraft(isDraft);
				message.setDeleteSign(Boolean.FALSE);
				if(SecurityUtils.getSubject().getPrincipal() instanceof Admin){
					Admin admin = (Admin)SecurityUtils.getSubject().getPrincipal();
					message.setCreater(admin.getName());
					message.setProducerId(admin.getId());
				}
				messageId = UUID.randomUUID().toString();
				message.setId(messageId);
				message.setTitle(mfs.getTitle());
				message.setBody(mfs.getBody());
				message.setResourceId(mfs.getResourceId());
				messageTarget.add(message);
				//插入消息推送表
				if(subject == SubjectType.KE_HU.getTypeCode()||subject == SubjectType.TUI_JIAN.getTypeCode()){ //只推客户
					MessageProducer mp = null;
					MessageBo bo = null;
					String tmp = selectSendUser(targetMap,targetType);
					String[] cids = null;
					if(tmp != null){
						cids = tmp.split(",");
						String registrationId = "";
						for(String cid : cids){
							mp = new MessageProducer();
							mp.setId(UUID.randomUUID().toString());
							mp.setConsumerId(cid);
							mp.setMessageId(messageId);
							mp.setCreateTime(createTime);
							mp.setSendTime(createTime);
							producerTarget.add(mp);
							registrationId = messageFromSystemMapper.selectJPushAcc(cid);
							if(StringUtils.isNotBlank(registrationId)){
								bo = new MessageBo();
								bo.setMessageId(message.getId());
								bo.setMessageTitle(message.getTitle());
								bo.setMessageBody(message.getBody());
								bo.setResourceId(message.getResourceId());
								bo.setResourceType(String.valueOf(message.getResourceType()));
								bo.setRegistrationId(registrationId);
								sendTarget.add(bo);
							}
						}
					}
				}
			}
			//批量插入
			if(messageTarget.size()>0) messageFromSystemMapper.insertBatchMessage(messageTarget);
			if(producerTarget.size()>0) messageFromSystemMapper.insertBatchProducer(producerTarget);
			//推送消息
			if(sendTarget.size()>0) jgMessageHelper.sendSystemMessage(sendTarget);
			return 1;
		}
		return 0;
	}
	
	@Override
	public List<MessageBo> selectSyncMessage(String uid) {
		return messageFromSystemMapper.selectSyncMessage(uid);
	}
	
	@Override
	public int updateMessageProducer(List<MessageProducer> producerList){
		for(MessageProducer mp : producerList){
			messageProducerMapper.updateByPrimaryKeySelective(mp);
		}
		return 1;
	}
	
	@Override
	public int insertBatchProducer(List<MessageProducer> target){
		return messageFromSystemMapper.insertBatchProducer(target);
	}
	
	@Override
	public int insertBatchConsumer(List<MessageConsumer> target) {
		return messageFromSystemMapper.insertBatchConsumer(target);
	}

	@Override
	public int updateJpushEasemobAccount(String uuid,String registrationId,String easemobName, String easemobPass) {
		return messageFromSystemMapper.updateJpushEasemobAccount(uuid, registrationId,easemobName,easemobPass,TokenManager.getUserId(),new Date());
	}

	@Override
	public int updateMessageConsumer(String messageId) {
		return messageFromSystemMapper.updateMessageConsumer(messageId, TokenManager.getUserId() , new Date());
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<MessageListBo> listSystemMessage(Integer isDraft,Integer subject,Integer pageNo,Integer pageSize) {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("isDraft", isDraft);
		params.put("subject", subject);
		return (Pagination<MessageListBo>)findPage("listSystemMessageByPage", "listSystemMessageCount", params, pageNo, pageSize);
	}

	@Override
	public int updateSystemMessage(String messageId, String title, String body, Integer isDraft) {
		MessageFromSystem mfs = new MessageFromSystem();
		mfs.setId(messageId);
		mfs.setTitle(title);
		mfs.setBody(body);
		mfs.setIsDraft(isDraft);
		return messageFromSystemMapper.updateByPrimaryKeySelective(mfs);
	}

	@Override
	public int deleteSystemMessage(String messageId) {
		MessageFromSystem mfs = new MessageFromSystem();
		mfs.setDeleteSign(Boolean.TRUE);
		mfs.setId(messageId);
		return messageFromSystemMapper.updateByPrimaryKeySelective(mfs);
	}

	@Override
	public IndexBo selectMessageWithGroup() {
		if(TokenManager.getToken() instanceof Admin){
			return messageFromSystemMapper.selectMessageWithGroup(TokenManager.getAdminId());
		}else if(TokenManager.getToken()  instanceof User){
			return messageFromSystemMapper.selectMessageWithGroup(TokenManager.getUserId());
		}
		return new IndexBo();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<MessageListBo> listPersonalMessage(Integer subject, Integer resourceType,Integer pageNo,Integer pageSize) {
		if(subject == SubjectType.KE_HU.getTypeCode() || subject == SubjectType.TUI_JIAN.getTypeCode()){
			Map<String,Object> params = new HashMap<String, Object>();
			if(null != subject) params.put("subject", subject);
			if(null != resourceType) params.put("resourceType", resourceType);
			params.put("uid", TokenManager.getUserId());
			return (Pagination<MessageListBo>)findPage("listPersonalMessageByPage", "listPersonalMessageCount", params, pageNo, pageSize);
		}
		return null;
	}

	@Override
	public MessageFromSystem selectSystemMessageDetail(String messageId) {
		return messageFromSystemMapper.selectByPrimaryKey(messageId);
	}
	
	/**
	 * 为个人和组织做转换
	 * @param sourceType
	 * @return
	 */
	private Integer getSourceType(Integer sourceType){
		if(RecommendType.PERSON_ACHIEVEMENT.getTypeCode() == sourceType 
				|| RecommendType.ORGANIZATION_ACHIEVEMENT.getTypeCode() == sourceType){
			sourceType = RecommendType.ACHIEVEMENT.getTypeCode();
		}else if(RecommendType.PERSONAL_DEMAND.getTypeCode() == sourceType
				|| RecommendType.ORGANIZATION_DEMAND.getTypeCode() == sourceType){
			sourceType = RecommendType.DEMAND.getTypeCode();
		}
		return sourceType;
	}

	/**
	 * 为个人和组织客户做转换
	 * @param targetType
	 * @return
	 */
	private Integer getTargetType(Integer targetType){
		if(ConsumerType.PERSON_CUSTOMER_RETAIL.getTypeCode() == targetType
				|| ConsumerType.ORGANIZATION_CUSTOMER_RETAIL.getTypeCode() == targetType){
			targetType = ConsumerType.CUSTOMER_RETAIL.getTypeCode();
		}
		return targetType;
	}
	@Override
	public JpushEasemobAccount selectSynAccByUid(String uid) {
		return jpushEasemobAccountMapper.selectSynAccByUid(uid);
	}
	
	private String changeSql(String source){
		String result = "";
		if(StringUtils.isNotBlank(source)){
			source = "'" + source + "'";
			result = source.replace(",", "','");
		}
		return result;
	}

	@Override
	public int addJpushEasemobAccount(String uuid,String uid,String easemobName,String easemobPass) {
		JpushEasemobAccount jea = new  JpushEasemobAccount();
		jea.setUid(uid);
		jea.setUuid(uuid);
		jea.setEasemobName(easemobName);
		jea.setEasemobPass(easemobPass);
		return jpushEasemobAccountMapper.insert(jea);
	}
	
}
