package com.yeejoin.amos.maintenance.business.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import com.yeejoin.amos.maintenance.business.dao.repository.IMsgDao;
import com.yeejoin.amos.maintenance.business.dao.repository.IMsgSubscribeDao;
import com.yeejoin.amos.maintenance.business.service.intfc.IMsgSubscribeService;
import com.yeejoin.amos.maintenance.business.util.DaoCriteria;
import com.yeejoin.amos.maintenance.core.util.query.BaseQuerySpecification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.maintenance.core.common.request.CommonPageable;
import com.yeejoin.amos.maintenance.dao.entity.Msg;
import com.yeejoin.amos.maintenance.dao.entity.MsgSubscribe;

@Service("msgSubscribeService")
public class MsgSubscribeServiceImpl implements IMsgSubscribeService {

	@Autowired
	private IMsgSubscribeDao msgSubscribeDao;

	@Autowired
	private IMsgDao iMsgDao;

	@Override
	public List<MsgSubscribe> queryMsgSubscribes(String orgCode, String userId) {
		return msgSubscribeDao.findMsgSubscribes(orgCode, userId);
	}

	@Override
	public List<MsgSubscribe> queryMsgSubscribes(String userId) {
		return msgSubscribeDao.findMsgSubscribes(userId);
	}


	@Override
	@Transactional
	public void saveSubscribe(List<MsgSubscribe> subscribe) {
		msgSubscribeDao.saveAll(subscribe);
	}

	@Override
	public int getUnreadCount(AgencyUserModel user) {
		// TODO Auto-generated method stub
		return iMsgDao.countByUserId(user.getUserId());
	}

	@Override
	public Page<Msg> queryMsgList(List<DaoCriteria> criterias, CommonPageable commonPageable) {
		// TODO Auto-generated method stub
		BaseQuerySpecification<Msg> specification = new BaseQuerySpecification<>(criterias);
		Order createTime = new Order(Direction.DESC, "createDate");
		List<Order> orders = new ArrayList<Order>();
		orders.add(createTime);
		Sort sort = Sort.by(orders);
		int page = commonPageable.getPageNumber();
		int size = commonPageable.getPageSize();
		Page<Msg> msgs = iMsgDao.findAll(specification, PageRequest.of(page, size, sort));
		return msgs;
	}

	@Override
	public Msg isRead(long msgId) {
		// TODO Auto-generated method stub
		if(iMsgDao.existsById(msgId)){
			Msg msg = iMsgDao.findById(msgId).get();
			msg.setIsRead(true);
			iMsgDao.save(msg);
		}
		return null;
	}

}
