package com.goafanti.admin.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.admin.bo.NoticeBo;
import com.goafanti.admin.service.NoticeService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.model.Notice;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;

@Service
public class NoticeServiceImpl extends BaseMybatisDao<NoticeMapper> implements NoticeService {
	@Autowired
	private NoticeMapper noticeMapper;

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<NoticeBo> updateListUnreadNoticeByAid(Integer pageNo, Integer pageSize, String aid) {
		Map<String, Object> params = new HashMap<>();

		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			params.put("aid", aid);
		}

		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}

		if (pageSize == null || pageSize < 0) {
			pageSize = 10;
		}
		Pagination<NoticeBo> notice = (Pagination<NoticeBo>) findPage("findUnreadNoticeListByPage", "findUnreadNoticeCount",
				params, pageNo, pageSize);

		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && null != notice.getList() && notice.getList().size()>0) {
			List<Notice> list = (List<Notice>) notice.getList();
			List<String> dl = new ArrayList<String>();
			for (Notice n : list) {
				dl.add(n.getId());
			}
			noticeMapper.batchUpdateUnreaded(dl);
		}
		return notice;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<NoticeBo> ListReadedNoticeByAid(Integer pageNo, Integer pageSize, String aid) {
		Map<String, Object> params = new HashMap<>();

		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			params.put("aid", aid);
		}

		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}

		if (pageSize == null || pageSize < 0) {
			pageSize = 10;
		}
		return (Pagination<NoticeBo>) findPage("findReadedNoticeListByPage", "findReadedNoticeCount", params, pageNo,
				pageSize);
	}

	@Override
	public int findUnreadNoticeCount() {
		String aid = null;
		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			aid = TokenManager.getAdminId();
		}

		return noticeMapper.selectUnreadedCount(aid);
	}
}
