package cn.myapps.runtime.rest.user.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.myapps.authtime.common.dao.ConnectionManager;
import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.domain.model.DomainVO;
import cn.myapps.authtime.domain.service.DomainProcess;
import cn.myapps.runtime.rest.user.model.User;
import cn.myapps.util.sequence.Sequence;

public abstract class AbstractUserDAO {

	Logger log = LoggerFactory.getLogger(AbstractUserDAO.class);

	protected String dbType = "Oracle: ";

	protected String schema = "";

	protected Connection connection;

	public AbstractUserDAO() throws Exception {
		this.connection = ConnectionManager.getConnection();
		dbType = ConnectionManager.dbType;
	}

	public String add(User user) throws Exception {
		String domainId = null;
		DomainProcess dp = AuthTimeServiceManager.domainRuntimeService();
		Collection<DomainVO> domainList = dp.getAllDomain();
		for(DomainVO domain : domainList){
			domainId = domain.getId();
		}
		PreparedStatement stmt = null;
		String userName = user.getUserName();
		String account = user.getAccount();
		String gender = user.getGender();
		String mobileNumber = user.getMobileNumber();
		String email = user.getEmail();
		String certificateTypeId = user.getCertificateTypeId();
		String certificateNumber = user.getCertificateNumber();
		String departmentId = user.getDepartmentId();
		String order = user.getOrder();
		String isTop = user.getIsTop();
		String isLeader = user.getIsLeader();
		String entryDate = user.getEntryDate();
		String extend = user.getExtend();
		String sql = "INSERT INTO t_user (ID,NAME,LOGINNO,DOMAINID,FIELD1,TELEPHONE,EMAIL,FIELD2,FIELD3,DEFAULTDEPARTMENT,FIELD4,FIELD5,FIELD6,FIELD7,FIELD8,LEVELS,STATUS,TELEPHONEPUBLIC,TELEPHONEPUBLIC2,EMAILPUBLIC,USERINFOPUBLIC) "
				   + "VALUES ('" + Sequence.getSequence() +"','" + userName + "','" + account + "','" + domainId + "','" + gender + "','" + mobileNumber + "','" + email + "','" + certificateTypeId + "','"
				    + certificateNumber + "','" + departmentId + "','" + order + "','" + isTop + "','" + isLeader + "','" + entryDate + "','" + extend + "',0,1,1,1,1,1)";
		try{
			stmt = connection.prepareStatement(sql);
			int num = stmt.executeUpdate();
			if(num!=1) {
				return "失败";
			}else{
				return "成功";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			ConnectionManager.closeStatement(stmt);
		}
		return null;
	}
	
	public User find(String account) throws Exception {
		PreparedStatement stmt = null;
		String sql = "SELECT * FROM t_user WHERE LOGINNO = '" + account + "'";
		stmt = connection.prepareStatement(sql);
		ResultSet rs = stmt.executeQuery();
		rs.next();
		User user = new User();
		user.setUserName(rs.getString("NAME"));
		user.setAccount(rs.getString("LOGINNO"));
		user.setGender(rs.getString("FIELD1"));
		user.setMobileNumber(rs.getString("TELEPHONE"));
		user.setEmail(rs.getString("EMAIL"));
		user.setCertificateTypeId(rs.getString("FIELD2"));
		user.setCertificateNumber(rs.getString("FIELD3"));
		user.setDepartmentId(rs.getString("DEFAULTDEPARTMENT"));
		user.setOrder(rs.getString("FIELD4"));
		user.setIsTop(rs.getString("FIELD5"));
		user.setIsLeader(rs.getString("FIELD6"));
		user.setEntryDate(rs.getString("FIELD7"));
		user.setExtend(rs.getString("FIELD8"));
		return user;
	}
	
	public String update(JSONObject jsonObject) throws Exception {
		String account = null;
		Map<String,String> map = new HashMap<String,String>();
		Set<Entry<String,Object>> set = jsonObject.entrySet();
		for(Entry<String,Object> entry : set){
			String key = (String)entry.getKey();
			if(key.equals("account")){
				account = (String)entry.getValue();
			}else{
				if(key.equals("username")){
					map.put("NAME", (String)entry.getValue());
				}
				if(key.equals("gender")){
					map.put("FIELD1", (String)entry.getValue());
				}
				if(key.equals("mobilenumber")){
					map.put("TELEPHONE", (String)entry.getValue());
				}
				if(key.equals("email")){
					map.put("EMAIL", (String)entry.getValue());
				}
				if(key.equals("certificatetypeid")){
					map.put("FIELD2", (String)entry.getValue());
				}
				if(key.equals("certificatenumber")){
					map.put("FIELD3", (String)entry.getValue());
				}
				if(key.equals("departmentid")){
					map.put("DEFAULTDEPARTMENT", (String)entry.getValue());
				}
				if(key.equals("order")){
					map.put("FIELD4", (String)entry.getValue());
				}
				if(key.equals("istop")){
					map.put("FIELD5", (String)entry.getValue());
				}
				if(key.equals("isleader")){
					map.put("FIELD6", (String)entry.getValue());
				}
				if(key.equals("entrydate")){
					map.put("FIELD7", (String)entry.getValue());
				}
				if(key.equals("extend")){
					map.put("FIELD8", (String)entry.getValue());
				}
			}
		}
		StringBuffer sql = new StringBuffer();
		sql.append("UPDATE t_user SET ");
		for (Entry<String, String> entryUpdate : map.entrySet()) {
			sql.append(entryUpdate.getKey() + " = '" + entryUpdate.getValue() + "'");
			sql.append(" , ");
		}
		String sqlStr = sql.toString();
		sqlStr = sqlStr.substring(0, sqlStr.length()-3) + " WHERE LOGINNO = '" + account + "'";
		PreparedStatement stmt = null;
		stmt = connection.prepareStatement(sqlStr);
		int num = stmt.executeUpdate();
		if(num!=1) {
			return "失败";
		}else{
			return "成功";
		}
	}
	
	public String delete(String account) throws Exception {
		PreparedStatement stmt = null;
		String sql = "DELETE FROM t_user WHERE LOGINNO = '" + account + "'";
		stmt = connection.prepareStatement(sql);
		int num = stmt.executeUpdate();
		if(num!=1) {
			return "失败";
		}else{
			return "成功";
		}
	}
}
