package org.cs.mgr.user.service.impl;

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

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.cs.core.service.impl.BaseService;
import org.cs.mgr.user.dao.IMgmMessageDao;
import org.cs.mgr.user.dao.IMgmUserDao;
import org.cs.mgr.user.dao.IMsgDao;
import org.cs.mgr.user.dao.IMsgRecordDao;
import org.cs.mgr.user.model.*;
import org.cs.mgr.user.service.IMsgService;


import org.cs.util.JPush;
import org.cs.util.Pager;
import org.cs.util.PropUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

@Service("msgService")
public class MsgService extends BaseService<Msg> implements IMsgService {

	@Autowired 
	private IMsgDao msgDao;
	@Autowired
	private IMsgRecordDao msgRecordDao;

	@Autowired
	private IMgmMessageDao mgmMessageDao;
	@Autowired
	private IMgmUserDao mgmUserDao;
	
	@Override
	public JSONObject getMyMsg(Map<String, String> map) {
		String userId = map.get("userId");
		int page = Integer.parseInt(map.get("page"));
		
		Pager pager = msgDao.getMyMsgs(userId, new Pager(page));
		JSONObject data = new JSONObject();
		data.put("page", pager.getPage());
		data.put("list", pager.getResults());
		data.put("totalPage", pager.getPageTotal());
		
		return getJson(1, data,"");
	}

	@Override
	@Transactional(readOnly=false)
	public JSONObject getMsgInfo(Map<String, String> map) {
		String userId = map.get("userId");
		String msgId = map.get("id");
		
		Msg msg = msgDao.findById(Integer.parseInt(msgId));
		JSONObject json = getJson(1, msg, "");
		
		String sql = "SELECT 1 FROM app_msg_record WHERE msg_id="+msgId+" AND user_id="+userId+" ";
//		Map<String,Object> params = new HashMap<String,Object>();	
//		params.put("msgId", msgId);
		
		List<?> list = msgRecordDao.findBySql(sql)  ; //msgRecordDao.findBySql(sql, msgId,userId);
		if(list==null||list.size()==0){
			MsgRecord mr = new MsgRecord();
			mr.setMsgId(msg.getId());
			mr.setUserId(Integer.parseInt(userId));
			msgRecordDao.insert(mr);
		}
		
		return json;
	}
	
	
	@Override
	@Transactional(readOnly=false)
	public void sendMsg(int userId,String title,String note,String clientId,Map<String,Object> params) {
//		Msg msg = new Msg();
//		msg.setNote(note);
//		msg.setTitle(title);
//		msg.setUserId(userId+"");
//		msgDao.insert(msg);
//		
		MgmMessage mgmMessage = new MgmMessage();
		mgmMessage.setTitle(title);
		mgmMessage.setContent(note);
		mgmMessage.setUserId(userId);	
		mgmMessage.setState(0+"");
		mgmMessageDao.insert(mgmMessage);

		try {
			MgmUser u = mgmUserDao.findById(userId);

			//Admin user1 = (Admin) request.getSession().getAttribute(Constants.SESSION_USER);
			Model m = new Model();
			m.setAppName("dxt");
			m.setContent(note);
			m.setFromApp("dxt");
			m.setMsgType("2");
			m.setReceiverUserid(u.getPersonnelcode());
			m.setSendUserid("东旭通");
			m.setTitle(title);
			m.setUrl("");
			List<Model> list = new ArrayList<Model>();
			list.add(m);
			String model = JSON.toJSONString(list);
			Base64 base64 = new Base64();
			byte [] bytes = base64.encodeBase64(model.getBytes("utf-8"));
			model = new String(bytes);

			RestTemplate restTemplate = new RestTemplate();
			String url = PropUtil.getString("msg_url");
			url = url + "?systemId="+PropUtil.getString("msg_systemId")+"&token="+PropUtil.getString("msg_token")+"&timestamp="+System.currentTimeMillis()+"&model="+model;
			Object rt = restTemplate.postForObject(url, null, Object.class);
		} catch (Exception e) {
			e.printStackTrace();
		}


		Map<String,String> param = new HashMap<String,String>();
		param.put("type",params.get("type").toString());
		if(StringUtils.isNotBlank(clientId)){
			/**
			 * 因推送存在延迟性，
			 * 客户端在支付成功后调用登录接口刷新数据
			 * 不再维护推送参数
			 */
			try {
				JPush.sendByClientId(title, note, new String[]{clientId},param, 0);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				
			}
		}
	}
	
	@Override
	public Pager getMsgList(Integer userId, Pager page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT sms.id AS id, sms.title  AS message_title,sms.note AS message_body ,sms.create_date AS  message_time ");
		sql.append(" FROM app_msg sms ");
		sql.append(" WHERE (1=1) ");
		sql.append(" AND  sms.user_id =:userId ");
		sql.append(" ORDER BY sms.id DESC ");
		return msgDao.findPageBySql(sql.toString(), page, params);		
	}

	@Override
	public int countMyUnReadMsg(int userId) {
		
		return msgDao.count(userId);
	}
}
