package com.zhiwei.manage.dao;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
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.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.zhiwei.manage.bean.Template;
import com.zhiwei.manage.handle.DbDepot;
import com.zhiwei.manage.util.Change;

@Service
public class TemplateDaoImpl implements TemplateDao {
	@Resource(name = "mongoTemplate")
	private MongoTemplate mongo;
	@Autowired
	private DbDepot dbDepot;

	@Override
	public boolean insert(Template template) {
		DBCollection con = null;
		if (DbDepot.dbCons.get(template.getPt()+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(template.getPt()+"temp");
		} else {
			con = dbDepot.getDBCollection("msg",template.getPt());
		}
		if (con == null) {
			return false;
		}
		DBObject obj = new BasicDBObject();
		Field[] fields = template.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(template) != null)
					// 字段名，字段值
					obj.put(fields[j].getName(), fields[j].get(template));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		con.insert(obj);
		return true;
	}

	@Override
	public boolean update(Template template) {
		DBCollection con = null;
		if (DbDepot.dbCons.get(template.getPt()+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(template.getPt()+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",template.getPt());
		}
		if (con == null) {
			return false;
		}
		DBObject update = new BasicDBObject();
		DBObject obj = new BasicDBObject();
		Field[] fields = template.getClass().getDeclaredFields();
		for (int j = 0; j < fields.length; j++) {
			fields[j].setAccessible(true);
			try {
				if (fields[j].getName().equals("templateId")) {
					continue;
				}
				if (fields[j].get(template) != null)
					// 字段名，字段值
					obj.put(fields[j].getName(), fields[j].get(template));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		update.put("$set", obj);
		DBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(template.getTemplateId()));
		WriteResult result = con.update(query, update, false, false);
		System.out.println(result.getN());
		return result.getN() == 1 ? true : false;
	}

	@Override
	public Template findById(String templateId,String pt) {
		DBCollection con = null;
		if (DbDepot.dbCons.get(pt+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(pt+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",pt);
		}
		if (con == null) {
			return null;
		}
		Map<String,Object> map=(Map<String, Object>) con.findOne(new BasicDBObject("_id",new ObjectId(templateId)).append("pt", pt));
		Template temp=new Template();
		temp=Change.toBean(Template.class, map);
		temp.setTemplateId(String.valueOf(map.get("_id")));
		return temp;
//		return mongo.findOne(Query.query(Criteria.where("_id").is(templateId)
//				.andOperator(Criteria.where("pt").is(DbDepot.nowPt)))
//				.with(new Sort(new Order(Direction.DESC, "createDate"))), Template.class);
	}

	@Override
	public List<Template> findByTmpName(String templateName, int pageNo, int pageSize,String pt) {
		List<Template> list=new ArrayList<Template>();
		DBCollection con = null;
		if (DbDepot.dbCons.get(pt+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(pt+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",pt);
		}
		if (con == null) {
			return null;
		}
		DBObject query=new BasicDBObject();
		query.put("templateName", new BasicDBObject("$regex",templateName));
		query.put("pt", pt);
		DBCursor cursor=con.find(query).sort(new BasicDBObject("createDate",-1)).skip((pageNo-1)*pageSize).limit(pageSize);
		while(cursor.hasNext()){
			Map<String,Object> map=(Map<String, Object>) cursor.next();
			Template temp=new Template();
			temp=Change.toBean(Template.class, map);
			temp.setTemplateId(String.valueOf(map.get("_id")));
			list.add(temp);
		}
		return list;
	}

	@Override
	public boolean delete(String templateId,String pt) {
		DBCollection con = null;
		if (DbDepot.dbCons.get(pt+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(pt+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",pt);
		}
		if (con == null) {
			return false;
		}
		WriteResult result=con.remove(new BasicDBObject("_id",new ObjectId(templateId)));
		return result.getN() == 0 ? true : false;
	}

	@Override
	public List<Template> findAll(int pageNo, int pageSize,String pt) {
		List<Template> list=new ArrayList<Template>();
		DBCollection con = null;
		if (DbDepot.dbCons.get(pt+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(pt+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",pt);
		}
		if (con == null) {
			return null;
		}
		DBObject obj=new BasicDBObject();
		obj.put("pt", pt);
		DBCursor currsor=con.find(obj).sort(new BasicDBObject("createDate",-1)).skip((pageNo - 1) * 10).limit(pageSize);
		while(currsor.hasNext()){
			Map<String,Object> map=(Map<String, Object>) currsor.next();
			Template temp=new Template();
			temp=Change.toBean(Template.class, map);
			temp.setTemplateId(String.valueOf(map.get("_id")));
			list.add(temp);
		}
		return list;
	}

	@Override
	public int allCount(String pt) {
		DBCollection con = null;
		if (DbDepot.dbCons.get(pt+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(pt+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",pt);
		}
		if (con == null) {
			return 0;
		}
		return (int) con.count(new BasicDBObject("pt",pt));
	}

	@Override
	public int findByUserCount(String templateName,String pt) {
		DBCollection con = null;
		if (DbDepot.dbCons.get(pt+"temp") != null) {
			con = (DBCollection) DbDepot.dbCons.get(pt+"temp");
		} else {
			con = dbDepot.getDBCollection("temp",pt);
		}
		if (con == null) {
			return 0;
		}
		return (int) con.count(new BasicDBObject("templateName",new BasicDBObject("$regex",templateName))
				.append("pt", pt));
	}

}
