package com.engine.kq.cmd.schedulecode;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.hrm.util.ServiceUtil;
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.hrm.util.face.HrmFaceCheckManager;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;


public class SaveScheduleCodeCmd extends AbstractCommonCommand<Map<String, Object>>{

	private SimpleBizLogger logger;
	public SaveScheduleCodeCmd(Map<String, Object> params, User user) {
		this.user = user;
		this.params = params;

		this.logger = new SimpleBizLogger();
		BizLogContext bizLogContext = new BizLogContext();
		bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
		bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_SCHEDULECODE);
		bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_SCHEDULECODE);//当前小类型
		bizLogContext.setParams(params);//当前request请求参数
		logger.setUser(user);//当前操作人
		String cmd = Util.null2String(params.get("cmd")).trim();
		String resourceids = "";
		if(cmd.equals("batch")) {
			resourceids = Util.null2String(params.get("resourceids")).trim().replace(";",",");
		}else{
			String data = Util.null2String(params.get("data"));
			JSONObject jsonObj = JSON.parseObject(data);
			resourceids = Util.null2String(jsonObj.get("resourceid")).replace(";",",");
		}
		String mainSql = "select * from hrmresource where id in ("+resourceids+") ";
		logger.setMainSql(mainSql, "id");//主表sql
		logger.setMainPrimarykey("id");//主日志表唯一key
		logger.setMainTargetNameColumn("lastname");
		SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo();
		String subSql = "select * from kq_schedule_code where resourceid in ("+resourceids+")";
		subLogInfo.setSubSql(subSql,"id");
		logger.addSubLogInfo(subLogInfo);
		logger.before(bizLogContext);
	}

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String, Object> retmap = new HashMap<String, Object>();
		RecordSetTrans rst = new RecordSetTrans();
		String sql = "";
		try {
			ResourceComInfo resourceComInfo = new ResourceComInfo();
//			retmap = this.check();
//			if(!retmap.isEmpty()){
//				return retmap;
//			}
			rst.setAutoCommit(false);
			String cmd = Util.null2String(params.get("cmd")).trim();
			if(cmd.equals("batch")){
				String deviceid = "";
				sql = " select id from kq_schedule_device ";
				rst.executeQuery(sql);
				if(rst.next()){
					deviceid = rst.getString("id");
				}

				String resourceids = Util.null2String(params.get("resourceids")).trim();
				String schedulecodes = Util.null2String(params.get("schedulecodes")).trim();
				String[] arrResourceIds = Util.splitString(resourceids, ";");
				String[] arrScheduleCodes = Util.splitString(schedulecodes, ";");
				for(int i=0;i<arrResourceIds.length;i++){
					if(arrResourceIds[i].length()==0)continue;
					sql = "delete from kq_schedule_code where resourceid = "+arrResourceIds[i];
					rst.executeUpdate(sql);
					List<String> tmpArrScheduleCodes = Util.splitString2List(arrScheduleCodes[i], ",");
					for(int j=0;j<tmpArrScheduleCodes.size();j++){
						if(Util.null2String(tmpArrScheduleCodes.get(j)).length()==0)continue;
						if(deviceid.length()==0)deviceid="null";
						sql = "INSERT INTO kq_schedule_code( resourceid ,schedulecode ,deviceid) VALUES  ( "+arrResourceIds[i]+" ,'"+Util.null2String(tmpArrScheduleCodes.get(j))+"' ,"+deviceid+")";
						rst.executeUpdate(sql);
					}
				}
			}else{
				String data = Util.null2String(params.get("data"));
				JSONObject jsonObj = JSON.parseObject(data);
				String resourceid = Util.null2String(jsonObj.get("resourceid"));

				sql = "delete from kq_schedule_code where resourceid = "+resourceid;
				rst.executeUpdate(sql);

				JSONArray datas = jsonObj.getJSONArray("datas");
				List<String> check = new ArrayList<>();
				for(int i=0;i<datas.size();i++){
					JSONObject jsonObject = datas.getJSONObject(i);
					String deviceid = Util.null2String(jsonObject.get("deviceid"));
					String schedulecode = Util.null2String(jsonObject.get("schedulecode"));
					if(deviceid.length()==0||schedulecode.length()==0)continue;

					List<String> tmpArrScheduleCodes = Util.splitString2List(schedulecode, ",");
					check.add(deviceid+"_"+schedulecode);
					for(int j=0;j<tmpArrScheduleCodes.size();j++){
						if(Util.null2String(tmpArrScheduleCodes.get(j)).length()==0)continue;
						sql = "INSERT INTO kq_schedule_code( resourceid ,schedulecode ,deviceid) VALUES  ( "+resourceid+" ,'"+Util.null2String(tmpArrScheduleCodes.get(j))+"' ,'"+deviceid+"')";
						rst.executeUpdate(sql);
					}
				}
			}
			sql = "  SELECT deviceid,schedulecode,COUNT(1) AS num from kq_schedule_code group BY deviceid,schedulecode HAVING COUNT(1)>1  ";
			rst.executeQuery(sql);
			if(rst.next()){
				retmap.put("status", "-1");
				retmap.put("message",  SystemEnv.getHtmlLabelName(10000836,weaver.general.Util.getIntValue(user.getLanguage()))+"("+rst.getString("schedulecode")+")");
				rst.rollback();
			}else{
				rst.commit();
			}
		} catch (Exception e) {
			rst.rollback();
			writeLog(e);
			retmap.put("status", "-1");
			retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
		}
		if(retmap.isEmpty()) {
			retmap.put("status", "1");
		}
		return retmap;
	}

	private Map<String, Object> check() {
		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;
			}

			String cmd = Util.null2String(params.get("cmd")).trim();
			if(cmd.equals("batch")){
				String resourceids = Util.null2String(params.get("resourceids")).trim();
				String schedulecodes = Util.null2String(params.get("schedulecodes")).trim();
				String[] arrResourceIds = Util.splitString(resourceids, ";");
				String[] arrScheduleCodes = Util.splitString(schedulecodes, ";");
				List<String> lsScheduleCodes = new ArrayList<>();
				for(int i=0;i<arrResourceIds.length;i++){
					if(arrResourceIds[i].length()==0)continue;
					List<String> tmpArrScheduleCodes = Util.splitString2List(arrScheduleCodes[i], ",");
					lsScheduleCodes.addAll(tmpArrScheduleCodes);
					for(int j=0;j<tmpArrScheduleCodes.size();j++){
						if(Util.null2String(tmpArrScheduleCodes.get(j)).length()==0)continue;
						sql = "select count(1) from kq_schedule_code where schedulecode = '"+Util.null2String(tmpArrScheduleCodes.get(j))+"' and resourceid != "+arrResourceIds[i];
						rs.executeQuery(sql);
						if(rs.next()){
							if(rs.getInt(1)>0){
								retmap.put("status", "-1");
								retmap.put("message",  SystemEnv.getHtmlLabelName(10000836,weaver.general.Util.getIntValue(user.getLanguage()))+"("+Util.null2String(tmpArrScheduleCodes.get(j))+")");
								break;
							}
						}
					}
				}
				lsScheduleCodes.removeIf(showColumn->showColumn.trim().equals(""));
				if(lsScheduleCodes.size() != new HashSet<String>(lsScheduleCodes).size()){
					retmap.put("status", "-1");
					retmap.put("message", SystemEnv.getHtmlLabelName(10000836,weaver.general.Util.getIntValue(user.getLanguage())));
				}
			}else{
				String data = Util.null2String(params.get("data"));
				JSONObject jsonObj = JSON.parseObject(data);
				String resourceid = Util.null2String(jsonObj.get("resourceid"));
				JSONArray datas = jsonObj.getJSONArray("datas");
				List<String> check = new ArrayList<>();
				for(int i=0;i<datas.size();i++){
					JSONObject jsonObject = datas.getJSONObject(i);
					String deviceid = Util.null2String(jsonObject.get("deviceid"));
					String schedulecode = Util.null2String(jsonObject.get("schedulecode"));
					if(deviceid.length()==0||schedulecode.length()==0)continue;

					List<String> tmpArrScheduleCodes = Util.splitString2List(schedulecode, ",");
					if(tmpArrScheduleCodes.size() != new HashSet<String>(tmpArrScheduleCodes).size()||check.contains(deviceid+"_"+schedulecode)){
						retmap.put("status", "-1");
						retmap.put("message", SystemEnv.getHtmlLabelName(10000836,weaver.general.Util.getIntValue(user.getLanguage())));
						break;
					}
					check.add(deviceid+"_"+schedulecode);
					for(int j=0;j<tmpArrScheduleCodes.size();j++){
						if(Util.null2String(tmpArrScheduleCodes.get(j)).length()==0)continue;
						sql = "select count(1) from kq_schedule_code where schedulecode = '"+Util.null2String(tmpArrScheduleCodes.get(j))+"' and deviceid='"+deviceid+"'  and resourceid != "+resourceid;
						rs.executeQuery(sql);
						if(rs.next()){
							if(rs.getInt(1)>0){
								retmap.put("status", "-1");
								retmap.put("message",  SystemEnv.getHtmlLabelName(10000836,weaver.general.Util.getIntValue(user.getLanguage()))+"("+Util.null2String(tmpArrScheduleCodes.get(j))+")");
								break;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			writeLog(e);
			retmap.put("status", "-1");
			retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
		}
		return retmap;
	}

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

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