package com.engine.kq.cmd.groupmemeber;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.biz.KQFormatData;
import com.engine.kq.biz.KQGroupComInfo;
import com.engine.kq.biz.KQGroupMemberComInfo;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.Reminder.KQAutoCardTask;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SaveGroupMemberCmd extends AbstractCommonCommand<Map<String, Object>> {
	private SimpleBizLogger logger;
	public SaveGroupMemberCmd(Map<String, Object> params, User user) {
		this.user = user;
		this.params = params;
		String groupId = Util.null2String(params.get("groupId"));
		this.boforeLog(groupId);
	}

	@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("HrmKQGroup:Add", user)) {
				retmap.put("status", "-1");
				retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
				return retmap;
			}

			String groupId = Util.null2String(params.get("groupId"));
			String type = Util.null2String(params.get("type"));
			String resourceid = Util.null2String(params.get("resourceid"));
			String subcompanyid = Util.null2String(params.get("subcompanyid"));
			String departmentid = Util.null2String(params.get("departmentid"));
			String alllevel = Util.null2String(params.get("alllevel")).trim();
			String jobtitle = Util.null2String(params.get("jobtitle")).trim();
			String jobtitlelevel = Util.null2String(params.get("jobtitlelevel")).trim();
			String jobtitlesubcompany = Util.null2String(params.get("jobtitlesubcompany")).trim();
			String jobtitledepartment = Util.null2String(params.get("jobtitledepartment")).trim();
			String jobtitlelevelvalue = "";
			if(jobtitlelevel.equals("2")){
				jobtitlelevelvalue = jobtitlesubcompany;
			}else if(jobtitlelevel.equals("3")){
				jobtitlelevelvalue = jobtitledepartment;
			}
			String seclevel = Util.null2String(params.get("seclevel")).trim();
			String seclevelto = Util.null2String(params.get("seclevelto")).trim();

			String objId = "0";
			switch (Util.getIntValue(type)) {
				case 1:
					objId = resourceid;
					break;
				case 2:
					objId = subcompanyid;
					break;
				case 3:
					objId = departmentid;
					break;
				case 5:
					objId = jobtitle;
					break;
				default:
					break;
			}

			String[] arrObjIds = Util.splitString(objId, ",");
			for(int i=0;i<arrObjIds.length;i++){
				//考勤组成员重复判断,单条判断下
				sql = " select count(id) from kq_groupmember where groupid="+groupId +
								" and (isdelete is null or  isdelete <> '1') and typevalue = "+arrObjIds[i]+" and type = "+type;
				if(alllevel.length()>0){
					sql += " and alllevel = "+alllevel;
				}
				if(seclevel.length()>0){
					sql += " and seclevel = "+seclevel;
				}
				if(seclevelto.length()>0){
					sql += " and seclevelto = "+seclevelto;
				}
				if(jobtitlelevelvalue.length()>0){
					sql += " and jobtitlelevelvalue = "+jobtitlelevelvalue;
				}
				if(jobtitlelevel.length()>0){
					sql += " and jobtitlelevel = "+jobtitlelevel;
				}
				rs.executeQuery(sql);
				if (rs.next() && rs.getInt(1) > 0) {
					if(arrObjIds.length==1){
						retmap.put("status", "-1");
						retmap.put("message", SystemEnv.getHtmlLabelName(17567, user.getLanguage()));
						return retmap;
					}else{
						continue;
					}
				}

				//人员类型,后面的需要替换前面的数据
        //TODO 现在有有效期，一个人是可以存在多个考勤组内的
//				if(type.equals("1")){
//					sql = "update kq_groupmember set isdelete=1 where type=1 and typevalue= ? ";
//					rs.executeUpdate(sql,arrObjIds[i]);
//				}

				sql = " INSERT INTO kq_groupmember ( groupid ,typevalue ,type ,alllevel ," +
								" seclevel ,seclevelto ,jobtitlelevelvalue ,jobtitlelevel) " +
								" VALUES  ( "+groupId+", "+arrObjIds[i]+" , '"+type+"', " +
								" "+(alllevel.length()==0?"null":alllevel)+","+(seclevel.length()==0?"null":seclevel)+"," +
								" "+(seclevelto.length()==0?"null":seclevelto)+", "+(jobtitlelevelvalue.length()==0?"null":jobtitlelevelvalue)+","+(jobtitlelevel.length()==0?"null":jobtitlelevel)+")";
				rs.executeUpdate(sql);
			}

			new KQGroupMemberComInfo().removeCache();
			//格式化考勤
			new KQFormatBiz().formatDateByGroupId(groupId, DateUtil.getCurrentDate());

      KQGroupComInfo kQGroupComInfo = new KQGroupComInfo();
      String auto_checkout = kQGroupComInfo.getAuto_checkout(groupId);
      String auto_checkin = kQGroupComInfo.getAuto_checkin(groupId);
      if("1".equalsIgnoreCase(auto_checkin) || "1".equalsIgnoreCase(auto_checkout)){
        //如果开启了自动打卡，保存考勤组成员之后需要格式化下缓存
        KQAutoCardTask kqAutoCardTask = new KQAutoCardTask();
        kqAutoCardTask.initAutoCardTask(groupId);
      }
			retmap.put("status", "1");
		} catch (Exception e) {
			retmap.put("status", "-1");
			retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
			writeLog(e);
		}
		return retmap;
	}

	private void boforeLog(String id){
		this.logger = new SimpleBizLogger();
		BizLogContext logContext = new BizLogContext();
		logContext.setDateObject(new Date());
		logContext.setLogType(BizLogType.HRM_ENGINE);
		logContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQGROUP);
		logContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQGROUP);
		logContext.setParams(params);
		logger.setUser(user);//当前操作人

		String mainSql = " select * from kq_group where id= " + id;
		logger.setMainSql(mainSql);//主表sql
		logger.setMainPrimarykey("id");//主日志表唯一key
		logger.setMainTargetNameColumn("groupname");

		SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo();
		String subSql1 = "select * from kq_groupmember where (isdelete is null or isdelete <> '1') and groupid="+id;
		subLogInfo1.setSubPrimarykey("id");
		subLogInfo1.setSubTargetNameColumn("id");
		subLogInfo1.setGroupId("0");  //所属分组， 按照groupid排序显示在详情中， 不设置默认按照add的顺序。
		subLogInfo1.setSubGroupNameLabel(388736); //在详情中显示的分组名称，不设置默认显示明细x
		subLogInfo1.setSubSql(subSql1);
		logger.addSubLogInfo(subLogInfo1);

		logger.before(logContext);
	}

	@Override
	public BizLogContext getLogContext() {
		return null;
	}

	@Override
	public List<BizLogContext> getLogContexts() {
		return logger.getBizLogContexts();
	}
}
