package com.zhiwei.manage.service;

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

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

import com.zhiwei.manage.bean.Message;
import com.zhiwei.manage.bean.PageEty;
import com.zhiwei.manage.dao.MessageDao;

@Service
public class MessageServiceImpl implements MessageService {

	@Autowired
	private MessageDao messageDao;

	@Override
	public void insert(Message message) {
		messageDao.insert(message);
	}

	@Override
	public String update(Message message, String pt) {
		try {
			String str = messageDao.update(message, pt);
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	@Override
	public PageEty findAll(int pageNo, int pageSize, String pt) {
		PageEty page = new PageEty();
		List<Message> data = messageDao.findAll(pageNo, pageSize, pt);
		int count = messageDao.allCount(pt);
		if (count % pageSize == 0 && count != 0) {
			page.setPageCount(count / pageSize);
		} else
			page.setPageCount(count / pageSize + 1);
		page.setData(data);
		page.setDataCount(count);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		return page;
	}

	@Override
	public PageEty findByTmpName(String templateName, int pageNo, int pageSize, String pt) {
		PageEty page = new PageEty();
		List<Message> data = messageDao.findByTmpName(templateName, pageNo, pageSize, pt);
		int count = messageDao.findByTmpCount(templateName, pt);
		if (data.size() == 0) {
			page.setData(new ArrayList<>());
			page.setDataCount(1);
		} else {
			page.setData(data);
			page.setDataCount(count);
		}
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		if (count % pageSize == 0) {
			page.setPageCount(count / pageSize);
		} else
			page.setPageCount(count / pageSize + 1);
		return page;
	}

	@Override
	public boolean delete(List<String> MessageId) {
		return messageDao.delete(MessageId);
	}

	@Override
	public boolean delete(String id) {
		return messageDao.delete(id);
	}

	@Override
	public PageEty findByHandle(int pageNo, int pageSize, boolean handle, String tempName, String pt) {
		PageEty page = new PageEty();
		int count = messageDao.findByHandleCount(pageNo, pageSize, handle, tempName, pt);
		List<Message> list = messageDao.findByHandle(pageNo, pageSize, handle, tempName, pt);
		page.setData(list);
		page.setDataCount(count);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		if (count % pageSize == 0) {
			page.setPageCount(count / pageSize);
		} else
			page.setPageCount(count / pageSize + 1);
		return page;
	}

	@Override
	public Message findMsg(String tempName, String errorType) {
		return messageDao.findMsg(tempName, errorType);
	}

}
