package com.engine.kq.wfset.attendance.framework;

import com.engine.kq.log.KQLog;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.hrm.company.CompanyComInfo;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.moduledetach.ManageDetachComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.hrm.roles.RolesComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.workflow.WorkflowComInfo;


/**
 * 
 * @author wcd
 * @version 1.0 2014-06-19
 */
public abstract class BaseManager<T> extends BaseBean {
  public KQLog kqLog = new KQLog();
	
	private BaseDao<T> dao;
	
	protected HttpServletRequest request;
	
	protected HttpServletResponse response;
	
	protected User user;
	
	protected User processUser;
	
	protected boolean isDebug;
	
	protected boolean isWriteLog;
	
	protected final String FIELD = "field";
	
	public BaseManager() {}
	
	public BaseManager(HttpServletRequest request, HttpServletResponse response) {
		this.set(request, response);
		this.isDebug = false;
		this.isWriteLog = true;
	}

	public void setDao(BaseDao<T> dao) {
		this.dao = dao;
	}
	
	public BaseDao<T> getDao() {
		return this.dao;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void set(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.user = request != null ? ((User)request.getSession(true).getAttribute("weaver_user@bean")) : user;
		this.processUser = this.user;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getProcessUser() {
		return processUser;
	}

	public void setProcessUser(User processUser) {
		this.processUser = processUser;
	}

	public Comparable insert(T bean) {
		return dao.insert(bean);
	}

	public void update(T bean) {
		dao.update(bean);
	}

	public void delete(Comparable id) {
		dao.delete(id);
	}

	public T get(Comparable id) {
		String sid = StringUtil.vString(id);
		return sid.startsWith("[map]") ? get(getMapParam(sid.substring("[map]".length()))) : dao.get(id);
	}

	public T get(Map<String, Comparable> map) {
		List<T> l = find(map);
		return (l == null || l.size() == 0) ? null : (T)l.get(0);
	}

	public List<T> find() {
		return find(new HashMap<String, Comparable>());
	}

	public List<T> find(Map<String, Comparable> map) {
		return dao.find(map);
	}
	
	public List<T> find(String params) {
		if(params == null || !params.startsWith("[map]")) return find();
		else return find(getMapParam(params.substring("[map]".length())));
	}
	
	public Map<String, Comparable> getMapParam(String params){
		params = StringUtil.vString(params);
		if(params.startsWith("[map]")) {
			params = params.substring("[map]".length());
		}
		return StringUtil.getMapParam(params, ";", "\\:");
	}
	
	public String getLabelName(Comparable indexid) {
		return user == null ? String.valueOf(indexid) : SystemEnv.getHtmlLabelNames(String.valueOf(indexid), user.getLanguage());
	}
	
	public String getLabelName(Comparable indexid, Comparable languageId) {
		return SystemEnv.getHtmlLabelNames(String.valueOf(indexid), StringUtil.parseToInt(String.valueOf(languageId)));
	}
	
	public String getParam(String param) {
		param = StringUtil.vString(param);
		return param.length() == 0 || request == null ? "" : StringUtil.vString(request.getParameter(param));
	}
	
	public String getDecodeParam(String param) {
		return StringUtil.getURLDecode(getParam(param));
	}
	
	public int getUID() {
		return user == null ? 0 : user.getUID();
	}
	
	public int getLanguageId() {
		return user == null ? 7 : user.getLanguage();
	}
	
	public String getCountryId() {
		return StringUtil.vString(user == null ? "" : user.getCountryid(), "1");
	}
	
	public String getResourceName(String id) {
		return getMultiResourceName(id);
	}
	
	public String getMultiResourceName(String id) {
		return getMultiResourceNameHtml(id, ", ", false);
	}
	
	public String getMultiResourceNameHtml(String id) {
		return getMultiResourceNameHtml(id, "&nbsp;&nbsp;", true);
	}
    
    private String getMultiResourceNameHtml(String id, String splitFlag, boolean isShowHtml) {
    	StringBuffer name = new StringBuffer();
		try{
			String[] ids = StringUtil.replace(id, ";", ",").split(",");
			ResourceComInfo comInfo = new ResourceComInfo();
			for(String _id : ids) {
				name.append(name.length() == 0 ? "" : splitFlag);
				if(isShowHtml) {
					name.append("<a href=\"javascript:openhrm('"+_id+"');\" onclick='pointerXY(event);'>"+comInfo.getResourcename(_id)+"</a>");
				} else {
					name.append(comInfo.getResourcename(_id));	
				}
			}
		}catch(Exception e){}
		return name.toString();
    }
	
	public String getDepartmentName(String id) {
		return getMultiDepartmentName(id);
	}
	
	public String getMultiDepartmentName(String id) {
		return getMultiDepartmentNameHtml(id, ", ");
	}
	
	public String getMultiDepartmentNameHtml(String id) {
		return getMultiDepartmentNameHtml(id, "&nbsp;&nbsp;");
	}
    
    private String getMultiDepartmentNameHtml(String id, String splitFlag) {
    	StringBuffer name = new StringBuffer();
		try{
			String[] ids = StringUtil.replace(id, ";", ",").split(",");
			DepartmentComInfo comInfo = new DepartmentComInfo();
			for(String _id : ids) {
				name.append(name.length() == 0 ? "" : splitFlag).append(comInfo.getDepartmentname(_id));
			}
		}catch(Exception e){}
		return name.toString();
    }
	
	public String getRolesName(String id) {
		return getMultiRolesName(id);
	}
	
	public String getMultiRolesName(String id) {
		return getMultiRolesNameHtml(id, ", ");
	}
	
	public String getMultiRolesNameHtml(String id) {
		return getMultiRolesNameHtml(id, "&nbsp;&nbsp;");
	}
    
    private String getMultiRolesNameHtml(String id, String splitFlag) {
    	StringBuffer name = new StringBuffer();
		try{
			String[] ids = StringUtil.replace(id, ";", ",").split(",");
			RolesComInfo comInfo = new RolesComInfo();
			for(String _id : ids) {
				name.append(name.length() == 0 ? "" : splitFlag).append(comInfo.getRolesRemark(_id));
			}
		}catch(Exception e){}
		return name.toString();
    }
	
	public String getWorkflowName(String id) {
		return getMultiWorkflowName(id);
	}
	
	public String getMultiWorkflowName(String id) {
		return getMultiWorkflowNameHtml(id, ", ");
	}
	
	public String getMultiWorkflowNameHtml(String id) {
		return getMultiWorkflowNameHtml(id, "&nbsp;&nbsp;");
	}
    
    private String getMultiWorkflowNameHtml(String id, String splitFlag) {
    	StringBuffer name = new StringBuffer();
		try{
			String[] ids = StringUtil.replace(id, ";", ",").split(",");
			WorkflowComInfo comInfo = new WorkflowComInfo();
			for(String _id : ids) {
				name.append(name.length() == 0 ? "" : splitFlag).append(comInfo.getWorkflowname(_id));
			}
		}catch(Exception e){}
		return name.toString();
    }
	
	public String getSubcompanyName(String id) {
		return getMultiSubcompanyName(id);
	}
	
	public String getMultiSubcompanyName(String id) {
		return getMultiSubcompanyNameHtml(id, ", ");
	}
	
	public String getMultiSubcompanyNameHtml(String id) {
		return getMultiSubcompanyNameHtml(id, "&nbsp;&nbsp;");
	}
    
    private String getMultiSubcompanyNameHtml(String id, String splitFlag) {
    	StringBuffer name = new StringBuffer();
		try{
			String[] ids = StringUtil.replace(id, ";", ",").split(",");
			SubCompanyComInfo comInfo = new SubCompanyComInfo();
			for(String _id : ids) {
				name.append(name.length() == 0 ? "" : splitFlag).append(comInfo.getSubCompanyname(_id));
			}
		}catch(Exception e){}
		return name.toString();
    }
	
	public String getCompanyName() {
		return getMultiCompanyName("1");
	}
	
	public String getMultiCompanyName(String id) {
		return getMultiCompanyNameHtml(id, ", ");
	}
	
	public String getMultiCompanyNameHtml(String id) {
		return getMultiCompanyNameHtml(id, "&nbsp;&nbsp;");
	}
    
    private String getMultiCompanyNameHtml(String id, String splitFlag) {
    	StringBuffer name = new StringBuffer();
		try{
			String[] ids = StringUtil.replace(id, ";", ",").split(",");
			CompanyComInfo comInfo = new CompanyComInfo();
			for(String _id : ids) {
				name.append(name.length() == 0 ? "" : splitFlag).append(comInfo.getCompanyname(_id));
			}
		}catch(Exception e){}
		return name.toString();
    }
	
	public String getShowName(int subcompanyid, int departmentid) {
		return getShowName(subcompanyid, departmentid, null, true);
	}
	
	public String getShowName(int subcompanyid, int departmentid, String title) {
		return getShowName(subcompanyid, departmentid, title, isDetachable());
	}
	
	private String getShowName(int subcompanyid, int departmentid, String title, boolean isDetachable) {
		String name = StringUtil.vString(title);
		if(isDetachable) {
			if(departmentid > 0) {
				name = getDepartmentName(String.valueOf(departmentid));
			} else if(subcompanyid > 0) {
				name = getSubcompanyName(String.valueOf(subcompanyid));
			} else {
				name = getCompanyName();
			}
		}
		return name;
	}
	
	public String getColorSpan(String color) {
		return getColorSpan(color, "24", "16");
	}
	
	public String getColorSpan(String color, String width, String height) {
		return "<span style='width:"+StringUtil.parseToInt(width, 24)+"px;height:"+StringUtil.parseToInt(height, 16)+"px;vertical-align:middle;display:inline-block;background:"+color+"'></span>";
	}
	
	public Map<String, Comparable> getQueryMap(String params) {
		return StringUtil.getMapParam(params, "&", "\\=");
	}
	
	public String getAppendStr() {
		return getAppendStr(this.getLanguageId());
	}
	
	public String getAppendStr(Comparable languageId) {
		return StringUtil.vString(languageId).equals("8") ? "," : "，";
	}
	
	public String bracket(String str) {
		return bracket(str, String.valueOf(getLanguageId()));
	}
	
	public String bracket(String str, String languageId) {
		return getLabelName(81913, languageId) + str + getLabelName(81914, languageId);
	}
	
	public boolean exist(String str, String[] array) {
		return exist(str, Arrays.asList(array));
	}
	
	public boolean exist(String str, List<String> list) {
		return list == null || StringUtil.isNull(str) ? false : list.contains(str);
	}
	
	public List<String> getDateList(String fromDate, String toDate) {
	    List<String> list = new ArrayList<String>();
		if(StringUtil.isNull(fromDate, toDate) || fromDate.compareTo(toDate) > 0) return list;
		
	    boolean hasReachToDate = false;
		for(String currentDate = fromDate; !hasReachToDate;){
			if(currentDate.length() != "2018-01-01".length()) break;
			if(currentDate.equals(toDate)) hasReachToDate = true;
			list.add(currentDate);
			if(StringUtil.isNull(currentDate = DateUtil.addDate(currentDate, 1))) break;
		}
		return list;
	}
	
	public String getMobileBrowserShowContent(String method, String isedit, String showvalue, String fieldformname, String fieldname, String fieldvalue, String dataChangeString, String disIsmand, String ismandfieldval) {
		return getMobileBrowserShowContent(method, isedit, showvalue, fieldformname, fieldname, fieldvalue, dataChangeString, disIsmand, ismandfieldval, 0);
	}
	
	public String getMobileBrowserShowContent(String method, String isedit, String showvalue, String fieldformname, String fieldname, String fieldvalue, String dataChangeString, String disIsmand, String ismandfieldval, int isMuti) {
		StringBuffer content = new StringBuffer();
		showvalue = StringUtil.vString(showvalue);
		fieldformname = StringUtil.vString(fieldformname);
		if("1".equals(StringUtil.vString(isedit))) { 
    		content.append("<table style=\"width:100%;\"><tr><td style=\"width:10%;\" onclick=\"javascript:showDialog('/browser/dialog.do','&returnIdField="+fieldformname+"&returnShowField="+fieldformname+"_span&method="+StringUtil.vString(method)+"&isMuti="+isMuti+"')\">"+
				"<a href=\"#\" data-rel=\"dialog\" data-transition=\"pop\">"+
				"<div style=\"background-image:url('/images/search_icon_wev8.png');height:30px;width:30px;\"></div></a>"+
				"<input fieldtype=\"browse\" type=\"hidden\" name=\""+fieldformname+"\" id=\""+fieldformname+"\" nameBak=\""+StringUtil.vString(fieldname)+"\" value=\""+StringUtil.vString(fieldvalue)+"\" ");
    		content.append(StringUtil.isNotNull(dataChangeString) ? dataChangeString : "onchange=\"try{maindetailfieldchange(this);}catch(e){}\"");
			content.append("/></td><td id=\""+fieldformname+"_span\" style=\"width:90%;white-space:normal;\" align=\"left\">"+showvalue+"</td>");
			content.append("<td><span id=\"" + fieldformname + "_ismandspan\" " + StringUtil.vString(disIsmand) + ">" + "!" + "</span>");
			content.append("<input type=\"hidden\" id=\"" + fieldformname + "_ismandfield\" name=\"ismandfield\" value=\"" + StringUtil.vString(ismandfieldval) + "\"/></td>");
			content.append("</tr></table>");
    	} else {
    		content.append(showvalue);
    	}
    	return content.toString();
	}
	
	protected Map initMap(Map map) {
		if(map == null) map = new HashMap();
		return map;
	}
	
	protected long totalTime(String fromDate, String fromTime, String toDate, String toTime) {
		long time = 0;
		if(StringUtil.isNotNull(fromDate, fromTime, toDate, toTime)) {
			if(fromTime.length() > 5) fromTime = fromTime.substring(0, 5);
			if(toTime.length() > 5) toTime = toTime.substring(0, 5);
			time += DateUtil.timeInterval(fromDate + " " + fromTime + ":00", toDate + " " + toTime + ":00");
		}
		return time;
	}
	
	protected void println(String str) {
		if(isDebug) {
			if(isWriteLog) {
				writeLog(str);
			} else {
				System.out.println(str);
			}
		}
	}
	
	public String getRemoteAddr() {
		String ip = "";
		if(request != null) {
        	ip = request.getHeader("x-forwarded-for");      
	        if(StringUtil.isNull(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("Proxy-Client-IP");   
	        if(StringUtil.isNull(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("WL-Proxy-Client-IP");   
	        if(StringUtil.isNull(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getRemoteAddr();
	        if (ip.indexOf(",") >= 0) ip = ip.substring(0 , ip.indexOf(","));
		}
        return ip;      
    }
	
	public boolean isDetachable() {
		return StringUtil.vString(new ManageDetachComInfo().getDetachable()).equals("1");
	}
	
	public String getDetachSubCompanyIds(String auth) {
		return getDetachSubCompanyIds(user, auth);
	}
	
	public String getDetachSubCompanyIds(User user, String auth) {
		String result = "";
		try {
			if(user != null && user.getUID() != 1 && isDetachable()) {
				StringBuffer allIds = new StringBuffer();
				ArrayList sList = new SubCompanyComInfo().getRightSubCompany(user.getUID(), auth);
				for(int i=0;i<sList.size();i++)
					allIds.append(allIds.length() == 0 ? "" : ",").append(StringUtil.vString(sList.get(i)));
				result = StringUtil.vString(allIds.toString(), "-1");
			}
		} catch (Exception e) {
		}
		return result;
	}

	public T getBean(String params) {
		params = StringUtil.vString(params);
		return get(this.getMapParam(params.startsWith("[map]") ? params.substring("[map]".length()) : params));
	}
	
	public String getId(T bean) {
		return StringUtil.EMPTY;
	}

	public Long save(T bean) {
		return save(bean, false);
	}

	public Long save(T bean, boolean isNew) {
		String id = getId(bean);
		if(isNew || id.equals("0") || id.equals("-1")) id = String.valueOf(this.insert(bean));
		else this.update(bean);
		return Long.valueOf(id);
	}
}