package com.goafanti.message.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.JtMessageConsumerMapper;
import com.goafanti.common.dao.JtMessageProducerMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.model.JtMessageConsumer;
import com.goafanti.common.model.JtMessageProducer;
import com.goafanti.common.utils.MobileMessageUtils;
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.service.JtMessageProducerService;

@Service
public class JtMessageProducerServiceImpl  extends BaseMybatisDao<JtMessageProducerMapper> implements JtMessageProducerService{
	@Autowired
	private JtMessageProducerMapper jtMessageProducerMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private JtMessageConsumerMapper jtMessageConsumerMapper;
	@Autowired
	private JGMessageHelper jgMessageHelper;
	@Value(value = "${accessKey}")
	private String					accessKey			= null;
	@Value(value = "${accessSecret}")
	private String					accessSecret		= null;
	

	@Override
	public int addMessage(JtMessageProducer messageProducer) {
		//处理消息内容
		messageProducer.setId(UUID.randomUUID().toString());
		//获得当前登录用户名字
		String create = adminMapper.selectByPrimaryKey(TokenManager.getAdminId()).getName();
		if(StringUtils.isBlank(create)){
			create = userMapper.selectByPrimaryKey(TokenManager.getUserId()).getUsername();
		}
		if(StringUtils.isBlank(create)){
			return -1;
		}
		messageProducer.setCreater(create);
		if(null != messageProducer.getCreateTime()){
			messageProducer.setCreateTime(new Date());
		}
		if (messageProducer.getResourceType()==null) {
			messageProducer.setResourceType(-1);//安卓跳转处理
		}
		return jtMessageProducerMapper.insertSelective(messageProducer);
	}
	
	@Override
	public int addSendMessage(String messageId) {
		// 获得所有正常使用的注册用户
		List<JtMessageConsumer> list = userMapper.getAllUser();
		Iterator<JtMessageConsumer> it = list.iterator();
		while (it.hasNext()) {
			JtMessageConsumer mc = (JtMessageConsumer) it.next();
			mc.setId(UUID.randomUUID().toString());
			mc.setMessageId(messageId);
		}
		JtMessageProducer messageProducer = new JtMessageProducer();
		messageProducer.setId(messageId);
		messageProducer.setSendTime(new Date());
		messageProducer.setIsSend(true);
		messageProducer.setIsDraft(false);
		jtMessageProducerMapper.updateByPrimaryKeySelective(messageProducer);
		JtMessageProducer producer=jtMessageProducerMapper.selectByPrimaryKey(messageId);
		if (producer!=null) {
			if (producer.getSubject()==1) {
				//推送消息
				jgMessageHelper.sendPushMessage(producer);
			}
		}
		return jtMessageConsumerMapper.addBatch(list);
	}
	

	@Override
	public JtMessageProducer getMessageById(String messageId) {
		return jtMessageProducerMapper.selectByPrimaryKey(messageId);
	}

	@Override
	public int updateMessageById(JtMessageProducer messageProducer) {
		int count = 0;
		// 修改消息
		messageProducer.setCreateTime(null);//不修改创建时间
		count = jtMessageProducerMapper.updateByPrimaryKeySelective(messageProducer);
		// 推送消息
		if(messageProducer.getIsSend() && !messageProducer.getDeleteSign() && !messageProducer.getIsDraft()){
			if(null == messageProducer.getSendTime()) messageProducer.setSendTime(new Date());
			count += addSendMessage(messageProducer.getId());
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<JtMessageProducer> getMessageList(JtMessageProducer messageProducer, String sendStartTime, String sendEndTime,
			String messageCode,Integer subject,Integer pageNo,Integer pageSize){
		if(pageNo==null || pageNo<1)pageNo=1;
		if(pageSize==null ||pageSize<1)pageSize=10; 
		Map<String, Object> params=new HashMap<String,Object>();
		//params.put("create", TokenManager.getUserId());
		if(StringUtils.isNotBlank(messageProducer.getTitle()))params.put("title",messageProducer.getTitle());
		if(null != messageProducer.getIsDraft())params.put("isDraft",messageProducer.getIsDraft());
		if(null != messageProducer.getIsSend())params.put("isSend",messageProducer.getIsSend());
		if(StringUtils.isNotBlank(sendStartTime))params.put("sendStartTime",sendStartTime);
		if(StringUtils.isNotBlank(sendEndTime))params.put("sendEndTime",sendEndTime);
		if(StringUtils.isNotBlank(messageCode))params.put("code",messageCode);
		if(null!=subject)params.put("subject",subject);
		return (Pagination<JtMessageProducer>) findPage("getMyMessageList", "getMyMessageCount", params, pageNo, pageSize);
	}

	@Override
	public int saveMobileMessage(String messageCode) {
		String regex = "^(1[1-9][0-9])\\d{8}$";
		Pattern p = Pattern.compile(regex);
		List<String> mobileList=userMapper.getUserListMobile();
		String mobile="";
		for (String string : mobileList) {
			if (null!=string) {
				Matcher m = p.matcher(string);
			if ( m.matches()) {
				mobile+=string+",";
				}
			}
		}
		if(mobile.length()>1)mobile=mobile.substring(0, mobile.length()-1);
		String ret=MobileMessageUtils.sendMessage(messageCode, null, mobile, accessKey, accessSecret);
		if (StringUtils.isNotBlank(ret)) {
			return -1;
		}
		JtMessageProducer producer=new JtMessageProducer();
		producer.setId(UUID.randomUUID().toString());
		producer.setCreater(AFTConstants.DEFAULT_INITIATOR);
		producer.setTitle("");
		producer.setSubject(2);
		producer.setIsSend(true);
		producer.setIsDraft(false);
		producer.setDeleteSign(false);
		producer.setCode(messageCode);
		producer.setSendTime(new Date());
		jtMessageProducerMapper.insertSelective(producer);
		return 1;
		
	}


}
