package com.ifish.serviceImpl;

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

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ifish.dao.CommentDao;
import com.ifish.dao.InformationDao;
import com.ifish.dao.InformationStatsDao;
import com.ifish.dao.UeditorDao;
import com.ifish.dao.UserDao;
import com.ifish.dto.InformationDto;
import com.ifish.dto.JsonResult;
import com.ifish.dto.PageingDto;
import com.ifish.entity.Comment;
import com.ifish.entity.Information;
import com.ifish.entity.InformationStats;
import com.ifish.entity.Ueditor;
import com.ifish.entity.User;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.SubDirectoryEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.enums.UeditorTypeEnum;
import com.ifish.exception.IfishException;
import com.ifish.hibernate.Pagination;
import com.ifish.netease.NeteaseIM;
import com.ifish.service.InformationService;
import com.ifish.util.IfishFilePath;
import com.ifish.util.ResultUtil;
import com.ifish.validator.PageParam;

@Service
@Transactional
public class InformationServiceImpl implements InformationService{

	@Autowired
	private UserDao userDao;
	@Autowired
	private UeditorDao ueditorDao;
	@Autowired
	private CommentDao commentDao;
	@Autowired
	private InformationDao informationDao;
	@Autowired
	private InformationStatsDao informStatsDao;
	@Autowired
	private NeteaseIM neteaseIM;
	
	@Override
	public Object saveComment(Comment comment) {
		Integer ueditorId = comment.getUeditorId();
		Integer userId = comment.getUserId();
		String commentContent = comment.getCommentContent();
		if(ueditorId!=null && userId!=null && commentContent!=null && commentContent.length()>0){
			Integer asUserId = comment.getAsUserId();
			if(asUserId!=null){
				if(!asUserId.equals(userId)){
					//发送云信消息给所@的用户
					neteaseIM.sendMsg(userId.toString(), asUserId.toString(), "来自资讯的回复:"+commentContent,"");
				}
			}
			comment.setCreateTime(new Date());
			this.commentDao.save(comment);
			return true;
		}
		return false;
	}

	@Override
	public Ueditor findUeditorById(Integer ueditorId) {
		if(ueditorId!=null){
			return this.ueditorDao.get(ueditorId);
		}
		return null;
	}

	@Override
	public Map<String, Object> findCommentsByUeditorId(Integer ueditorId,Integer firstResult,Integer pageSize) {
		if(ueditorId!=null){
			if(firstResult==null){
				firstResult = 0;
			}
			if(pageSize==null){
				pageSize = 10;
			}
			Pagination<Comment> page = this.commentDao.findByCriteria(firstResult, pageSize, Order.desc("commentId"), Restrictions.eq("ueditorId", ueditorId));
			List<Comment> commentList = page.getList();
			for (Comment comment : commentList) {
				User user = this.userDao.get(comment.getUserId());
				if(user!=null){
					comment.setUserName(user.getNickName());
					comment.setUserImg(user.getUserImg());
				}
				if(comment.getAsUserId()!=null){
					User tmpUser = this.userDao.get(comment.getAsUserId());
					if(tmpUser!=null){
						comment.setAsUserName("<span style='color:#4374fb'>@"+tmpUser.getNickName()+" </span>");
					}
					else{
						comment.setAsUserName("");
					}
				}
				else{
					comment.setAsUserName("");
				}
			}
			firstResult+=commentList.size();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("commentList", commentList);
			map.put("firstResult", firstResult);
			map.put("totalCount", page.getTotalCount());
			return map;
		}
		else{
			return null;
		}
	}

	/**
	 * 分页获取资讯
	 */
	@Override
	public PageingDto<?> getInformationsByPage(PageParam pageParam) {
		//分页获取数据
		Integer firstResult = pageParam.getFirstResult();
		Pagination<Information> page = informationDao.findByCriteria(firstResult, pageParam.getPageSize(),Order.desc("infoId"),Restrictions.eq("appShow", BooleanEnum.YES.getKey()));
		List<Information> list = page.getList();
		firstResult+=list.size();
		//数据封装
		List<InformationDto> dtoList = new ArrayList<InformationDto>();
		for (Information info : list) {
			//资讯ID
			Integer infoId = info.getInfoId();
			InformationDto dto = new InformationDto(infoId);
			dtoList.add(dto);
			//标题内容图片
			dto.setTitle(info.getTitle());
			dto.setContents(info.getContents());
			dto.setImage(IfishFilePath.getPath(SubDirectoryEnum.information,info.getImage()));
			//点击数
			InformationStats infoStats = informStatsDao.get(infoId);
			if(infoStats!=null){
				dto.setClickNum(infoStats.getClickNum());
			}
			//编辑器
			Integer ueditorId = info.getUeditorId();
			if(ueditorId!=null){
					//链接
					StringBuilder link = new StringBuilder(IfishFilePath.getPath(SubDirectoryEnum.ueditorHtml,info.getLink()));
					//是否可以评论，可以评论则拼接用户ID
					if(UeditorTypeEnum.yespinglun.getKey().equals(info.getUeditorType())){
						link.append("&userId="+pageParam.getUserId());
					}
					//标题链接
					dto.setLink(link.toString());
					//评论数
					Integer pinglunNum = commentDao.getPinglunNum(ueditorId);
					dto.setPinglunNum(pinglunNum);
			}
			else{
				dto.setLink(info.getLink());
			}
		}
		//分页数据封装
		return new PageingDto<InformationDto>(ResultEnum.success.getKey(), firstResult, page.getTotalCount(), dtoList);
	}

	/**
	 * 加点击数
	 */
	@Override
	public JsonResult<?> addClickNum(Integer infoId) {
		//资讯统计信息
		InformationStats informStats = informStatsDao.get(infoId);
		if(informStats==null){
			throw new IfishException(ResultEnum.error402);
		}
		Integer cNum = informStats.getClickNum();
		informStats.setClickNum(++cNum);
		informStatsDao.update(informStats);
		//返回数据
		JSONObject json = new JSONObject();
		json.put("infoId", informStats.getInfoId());
		json.put("clickNum", informStats.getClickNum());
		return ResultUtil.success(json);
	}
	
}