package com.zhiwei.manage.dao;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.mongodb.DBCollection;
import com.mongodb.WriteResult;
import com.zhiwei.manage.bean.FieldBean;
import com.zhiwei.manage.handle.DbDepot;

@Component
public class FieldBeanDaoImpl implements FieldBeanDao {

	@Resource(name = "mongoTemplate")
	private MongoTemplate mongo;

	@Override
	public void insert(FieldBean fieldBean) {
		mongo.insert(fieldBean);
	}

	@Override
	public boolean update(FieldBean fieldBean) {
		Update update = new Update();
		Field[] fields = fieldBean.getClass().getDeclaredFields();
		for (int j = 0; j < fields.length; j++) {
			fields[j].setAccessible(true);
			try {
				if (fields[j].getName().equals("id")) {
					continue;
				}
				if (fields[j].get(fieldBean) != null)
					update.set(fields[j].getName(), fields[j].get(fieldBean));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		WriteResult result = mongo.updateFirst(Query.query(Criteria.where("_id").is(fieldBean.getId())), update,
				FieldBean.class);
		return result.getN() == 1 ? true : false;
	}

	@Override
	public boolean delete(List<String> id) {
		WriteResult result = mongo.remove(Query.query(Criteria.where("_id").in(id)), FieldBean.class);
		System.out.println(result.getN());
		return result.getN() > 0 ? true : false;
	}

	@Override
	public FieldBean getFieldsByPt(String pt) {
		return mongo.findOne(Query.query(Criteria.where("pt").is(pt)), FieldBean.class);
	}

	@Override
	public int findFieldCount(String pt) {
		if(pt==null||pt.equals("")){			
			return (int) mongo.count(null, FieldBean.class);
		}else{
			return (int) mongo.count(Query.query(Criteria.where("pt").is(pt)), FieldBean.class);
		}
	}

	@Override
	public List<FieldBean> findAllFields(int pageNo,int pageSize,String pt) {
		if(pt==null||pt.equals("")){	
			return mongo.find(Query.query(Criteria.where("_id").exists(true)).skip((pageNo-1)*pageSize).limit(pageSize),FieldBean.class);
		}else{
			return mongo.find(Query.query(Criteria.where("pt").is(pt)).skip((pageNo-1)*pageSize).limit(pageSize),FieldBean.class);
		}
	}


}
