package com.zhiwei.manage.service;

import java.util.List;

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

import com.zhiwei.manage.bean.PageEty;
import com.zhiwei.manage.bean.Person;
import com.zhiwei.manage.dao.PersonDao;
@Service
public class PersonServiceImpl implements PersonService {

	@Autowired
	private PersonDao personDao;
	
	@Override
	public boolean insert(Person person) {
		if(person==null||person.getUsername().trim()==null||person.getPassword().trim()==null){
			return false;
		}
		Person p=personDao.findByUsername(person.getUsername());
		if(p!=null){
			return false;
		}
		personDao.insert(person);
		return true;
	}

	@Override
	public boolean update(Person person) {
		if(person==null||person.getUsername().trim()==null||person.getPassword().trim()==null){
			return false;
		}
		return personDao.update(person);//false 找不到该id或者id没传进来
	}

	@Override
	public PageEty findAll(int pageNo,int pageSize,int lv) {
		PageEty page=new PageEty();
		int count=personDao.findAllCount();
		List<Person> data=personDao.findAll(pageNo, pageSize);
		for(Person p:data){
			if(lv!=3){
				p.setPassword("********");
			}
		}
		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 Person findById(String personId) {
		return personDao.findById(personId);
	}


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

	@Override
	public Person login(String username, String password) {
		if(username.trim()!=null&&password.trim()!=null){
			Person p=personDao.findByUsername(username);
			if(p!=null){
				if(p.getPassword().equals(password)){
					return p;
				}
			}
		}
		return null;
	}

	@Override
	public PageEty findByUserName(String username,int pageNo,int pageSize,int lv) {
		PageEty page=new PageEty();
		int count=personDao.findUserCount(username);
		List<Person> data=personDao.findAllByUsername(username, pageNo, pageSize);
		for(Person p:data){
			if(lv!=3){
				p.setPassword("********");
			}
		}
		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;
	}

}
