package com.engine.kq.cmd.schedulecode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.util.PageUidFactory;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.appdetach.AppDetachComInfo;
import weaver.hrm.common.Tools;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.moduledetach.ManageDetachComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.systemright.CheckSubCompanyRight;


public class GetScheduleCodeListCmd extends AbstractCommonCommand<Map<String, Object>>{
	
	public GetScheduleCodeListCmd(Map<String, Object> params, User user) {
		this.user = user;
		this.params = params;
	}

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String, Object> retmap = new HashMap<String, Object>();
		RecordSet rs = new RecordSet();
		String sql = "";
		try {
			if(!HrmUserVarify.checkUserRight("ScheduleCode:Edit",user)) {
				retmap.put("status", "-1");
				retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
				return retmap;
			}
			CheckSubCompanyRight checkSubCompanyRight = new CheckSubCompanyRight();
			ManageDetachComInfo manageDetachComInfo = new ManageDetachComInfo();
			boolean hrmdetachable = manageDetachComInfo.isUseHrmManageDetach();//是否开启了人力资源模块的管理分权
			int operatelevel = -1;

			String lastname = Util.null2String(params.get("lastname"));
			String subcompanyid = Util.null2String(params.get("subcompanyid"));
			String departmentid = Util.null2String(params.get("departmentid"));
			String jobtitle = Util.null2String(params.get("jobtitle"));
			String schedulecode = Util.null2String(params.get("schedulecode"));
			String isNoAccount = Util.null2String(params.get("isNoAccount"));
			String showAllLevel = Util.null2String(params.get("showAllLevel"));

			boolean isOneDevice = true;
			sql = " select count(1) from kq_schedule_device ";
			rs.executeQuery(sql);
			if(rs.next()){
				if(rs.getInt(1)>1){
					isOneDevice = false;
				}
			}

			String backfields = " id,lastname,subcompanyid1,departmentid,jobtitle, id as id1 , id as id2";
			String fromSql  = " HrmResource ";
			String sqlWhere = " 1=1 ";
			String orderby = " dsporder,lastname " ;

			if(hrmdetachable){
				int[] arrSubcompanyids = checkSubCompanyRight.getSubComByUserRightId(user.getUID(),"ScheduleCode:Edit");
				operatelevel=checkSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(),"ScheduleCode:Edit",Util.getIntValue(subcompanyid,-1));
				String subcompanyids = "";
				if(user.getUID() != 1){
					for(int i=0;arrSubcompanyids!=null&&i<arrSubcompanyids.length;i++){
						if(subcompanyids.length()>0)subcompanyids+=",";
						subcompanyids += arrSubcompanyids[i];
					}
					if(subcompanyids.length() > 0 ){
						sqlWhere += " and subcompanyid1 in("+subcompanyids+")";
					}else{
						sqlWhere += " and 1=2 ";
					}
				}
			}else{
				operatelevel = 2;
			}

			if(user.getUID() == 1){
				operatelevel = 2;
			}

			if(lastname.length()>0){
				String mysqlEscope = "/" ;
				if(DialectUtil.isMySql()){
					sqlWhere += " and (lastname like '%"+ Util.StringReplace(lastname, "_", mysqlEscope+"_") +"%' escape '"+mysqlEscope+"' or pinyinlastname like '%"+Util.StringReplace(lastname.toLowerCase(), "_", mysqlEscope+"_")+"%' escape '"+mysqlEscope+"'  )";
				}else{
					sqlWhere += " and (lastname like '%"+ Util.StringReplace(lastname, "_", "\\_") +"%' escape '\\' or pinyinlastname like '%"+Util.StringReplace(lastname.toLowerCase(), "_", "\\_")+"%' escape '\\'  )";
				}
			}

			if(subcompanyid.length() > 0){
				String subcompanyAll = "";
				String[] sub = subcompanyid.split(",");
				if (sub != null) {
					for (int cx = 0; cx < sub.length; cx++) {
						String subid_ = sub[cx];
						if (subid_ != null && !"".equals(subid_) && showAllLevel.equals("1")) {
							subcompanyAll = SubCompanyComInfo.getAllChildSubcompanyId(subid_, subcompanyAll);
						}
					}
				}
				if (!"".equals(subcompanyAll)) {
					subcompanyAll = subcompanyid + subcompanyAll.trim();
				} else {
					subcompanyAll = subcompanyid;
				}
				sqlWhere += " and "+Tools.getOracleSQLIn(subcompanyAll, "subcompanyid1");
			}
			if(departmentid.length() > 0){
				String departmentAll = "";
				String[] dep = departmentid.split(",");
				if (dep != null) {
					for (int cx = 0; cx < dep.length; cx++) {
						String depid_ = dep[cx];
						if (depid_ != null && !"".equals(depid_) && showAllLevel.equals("1")) {
							departmentAll = DepartmentComInfo.getAllChildDepartId(depid_, departmentAll);
						}
					}
				}
				if (!"".equals(departmentAll)) {
					departmentAll = departmentid + departmentAll.trim();
				} else {
					departmentAll = departmentid;
				}
				sqlWhere += " and "+Tools.getOracleSQLIn(departmentAll, "departmentid");
			}
			if(jobtitle.length() >0){
				sqlWhere += " and jobtitle in("+jobtitle+")";
			}

			if (!"1".equals(isNoAccount)) {
				sqlWhere += " and loginid is not null "+(rs.getDBType().equals("oracle")?"":" and loginid<>'' ");
			}

			if(schedulecode.length() >0){
				sqlWhere += " and id in(SELECT DISTINCT resourceid FROM kq_schedule_code WHERE schedulecode LIKE '%"+schedulecode+"%')";
			}

			AppDetachComInfo adci = new AppDetachComInfo();
			String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID()+"");
			sqlWhere += (appdetawhere!=null&&!"".equals(appdetawhere)?(" and " + appdetawhere):"");

			String pageUid = PageUidFactory.getHrmPageUid("ScheduleCodeList");

			String operateString= "<operates width=\"20%\">";
			operateString+=" <popedom></popedom> ";
			if(!isOneDevice){
				operateString+="     <operate href=\"javascript:doEditOperate();\" text=\""+SystemEnv.getHtmlLabelName(	511334,user.getLanguage())+"\" index=\"0\"/>";
			}
			operateString+="     <operate href=\"javascript:showLog();\" text=\""+SystemEnv.getHtmlLabelName(83,user.getLanguage())+"\" index=\"1\"/>";
			operateString+="</operates>";
			String tableString =" <table  pageUid=\""+pageUid+"\" pagesize=\"10\" tabletype=\"checkbox\">"+
							" <sql backfields=\""+backfields+"\" sqlform=\""+fromSql+"\" sqlwhere=\""+Util.toHtmlForSplitPage(sqlWhere)+"\"  sqlorderby=\""+orderby+"\"  sqlprimarykey=\"id\" sqlsortway=\"Asc\" sqlisdistinct=\"false\"/>"+
							operateString+
							"	<head>"+
							"		<col width=\"0%\"  hide=\"true\"  text=\"\" column=\"id\"/>"+
							"		<col width=\"25%\" text=\""+SystemEnv.getHtmlLabelName(413,user.getLanguage())+"\" column=\"lastname\" orderkey=\"lastname\"/>"+
							"  <col width=\"25%\" text=\"" + SystemEnv.getHtmlLabelName(141, user.getLanguage()) + "\" column=\"subcompanyid1\" orderkey=\"subcompanyid1\" transmethod=\"weaver.hrm.company.SubCompanyComInfo.getSubCompanyname\"/>"+
							"  <col width=\"25%\" text=\"" + SystemEnv.getHtmlLabelName(124, user.getLanguage()) + "\" column=\"departmentid\" orderkey=\"departmentid\" transmethod=\"weaver.hrm.company.DepartmentComInfo.getDepartmentmark\"/>";
							if(isOneDevice){
								tableString+="	 <col width=\"25%\" text=\""+SystemEnv.getHtmlLabelName(27960,user.getLanguage())+"\" column=\"id1\" transmethod=\"com.engine.kq.util.TransMethod.getSchedulecode\"/>";
							}else{
								tableString+="	 <col width=\"25%\" text=\""+SystemEnv.getHtmlLabelName(27960,user.getLanguage())+"\" column=\"id2\" transmethod=\"com.engine.kq.util.TransMethod.getSchedulecode\"/>";
							}
							tableString+="	</head>"+
							" </table>";

			//主要用于 显示定制列以及 表格 每页展示记录数选择
			String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom());
			Util_TableMap.setVal(sessionkey, tableString);
			retmap.put("sessionkey", sessionkey);
			retmap.put("isOneDevice", isOneDevice);
			retmap.put("status", "1");
			if(operatelevel > 0){
				retmap.put("canAdd", true);
			}else{
				retmap.put("canAdd", false);
			}
			if(operatelevel > 1){
				retmap.put("canDel", true);
			}else{
				retmap.put("canDel", false);
			}
		} catch (Exception e) {
			retmap.put("status", "-1");
			retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
			writeLog(e);
		}
		return retmap;
	}
	
	
	@Override
	public BizLogContext getLogContext() {
		return null;
	}

}
