package com.zhiwei.chendong;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.zhiwei.util.Config;
import com.zw.entity.ExcelFile;

public class MongoForChenDong {

	private final static Log log = LogFactory.getLog(MongoForChenDong.class);

	private MongoClient mongoClient = null;
	private static MongoForChenDong mongoDBPool = new MongoForChenDong(); // 饿汉式
																			// 单例模式

	public MongoForChenDong() {
		if (mongoClient == null) {
			MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
			optionsBuilder.connectionsPerHost(100); // 与目标数据库可创建的最大连接数
			optionsBuilder.connectTimeout(1000 * 60 * 40); // 与数据库建立连接的超时时间
			optionsBuilder.maxWaitTime(1000 * 60 * 5); // 一个线程成功获取到一个可用数据库连接之前的最大等待时间
			optionsBuilder.threadsAllowedToBlockForConnectionMultiplier(100);// 等待一个连接
																				// //
																				// 允许阻塞的线程数
			optionsBuilder.maxConnectionIdleTime(0);
			optionsBuilder.maxConnectionLifeTime(0);
			optionsBuilder.socketKeepAlive(true);
			optionsBuilder.socketTimeout(1000 * 20);
			MongoClientOptions options = optionsBuilder.build();
			// char[] passwords = Config.getVal("password").toCharArray();
			List<MongoCredential> credentials = new ArrayList<>();
			// MongoCredential credential =
			// MongoCredential.createCredential(Config.getVal("user"),
			// Config.getVal("dbName"), passwords);
			// credentials.add(credential);
			List<ServerAddress> serverAddresses = new ArrayList<>();
			serverAddresses.add(new ServerAddress(Config.getVal("host"), Integer.valueOf(Config.getVal("port"))));
			mongoClient = new MongoClient(serverAddresses, credentials, options);
		}
	}

	public DB getDB(String dbName) {
		return mongoClient.getDB(dbName);
	}

	/**
	 * 添加mongo名称和集合名称
	 * 
	 * @param dbName
	 * @param collectionName
	 * @return
	 */
	public DBCollection getCollection(String dbName, String collectionName) {
		DB db = mongoClient.getDB(dbName);
		return db.getCollection(collectionName);
	}

	public List<Map<String, Object>> find() {
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("Result");
		DBObject obj = new BasicDBObject();
		DBCursor dbCursor = dbCollection.find();
		List<Map<String, Object>> list = new ArrayList<>();
		while (dbCursor.hasNext()) {
			list.add((Map<String, Object>) dbCursor.next());
		}
		return list;
	}

	/**
	 * 微信转链接的插入
	 * 
	 * @param list
	 */
	public void insert(List<String> list) {
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("RawUrl");
		for (String l : list) {
			DBObject obj = new BasicDBObject();
			obj.put("_id", l);
			obj.put("url", l);
			try {
				dbCollection.insert(obj);
			} catch (Exception e) {
				log.info(l);
			}
		}
	}

	public int getNum() {
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("RawUrl");
		DBCursor dbCursor = dbCollection.find();
		List<Map<String, Object>> list = new ArrayList<>();
		while (dbCursor.hasNext()) {
			list.add((Map<String, Object>) dbCursor.next());
		}
		return list.size();
	}

	public void remove() {
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("Result");
		dbCollection.drop();
	}

	/**
	 * 微信转链接的文件地址入库
	 */
	public void insertFile(ExcelFile excel) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("changeUrlFile");
		DBObject obj = new BasicDBObject();
		obj.put("url", excel.getUrl());
		obj.put("mail", excel.getMail());
		obj.put("date", sdf.format(new Date()));
		dbCollection.insert(obj);
	}

	/**
	 * 获取信息
	 * 
	 * @return
	 */
	public List<ExcelFile> findFile() {
		List<ExcelFile> list = new ArrayList<ExcelFile>();
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("changeUrlFile");
		DBCursor dbCursor = dbCollection.find().sort(new BasicDBObject("date", -1));
		System.out.println("size" + dbCursor.size());
		while (dbCursor.hasNext()) {
			Map<String, Object> map = (Map<String, Object>) dbCursor.next();
			ExcelFile ef = new ExcelFile();
			ef.setId(String.valueOf(map.get("_id")));
			ef.setUrl(String.valueOf(map.get("url")));
			ef.setMail(String.valueOf(map.get("mail")));
			ef.setDate(String.valueOf(map.get("date")));
			list.add(ef);
		}
		System.out.println(list.size());
		return list;
	}

	public void delete(String id) {
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("changeUrlFile");
		dbCollection.remove(new BasicDBObject("_id", new ObjectId(id)));
	}

	public String findByid(String id) {
		DB db = mongoClient.getDB(Config.getVal("dbName"));
		DBCollection dbCollection = db.getCollection("changeUrlFile");
		DBObject obj = dbCollection.findOne(new BasicDBObject("_id", new ObjectId(id)));
		return String.valueOf(obj.get("url"));
	}
}
