package com.engine.kq.cmd.shiftschedule;

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.KQGroupComInfo;
import com.engine.kq.biz.KQShiftScheduleComInfo;
import weaver.common.DateUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.DBUtil;
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.*;

public class DelShiftScheduleCmd extends AbstractCommonCommand<Map<String, Object>> {
	private SimpleBizLogger logger;
	public DelShiftScheduleCmd(Map<String, Object> params, User user) {
		this.user = user;
		this.params = params;
		this.logger = new SimpleBizLogger();

		String groupId = Util.null2String(params.get("groupId"));//考勤组ID
		BizLogContext bizLogContext = new BizLogContext();
		bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
		bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_Schedule_Set);//所属大类型
		bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_Schedule_Set);//当前小类型
		bizLogContext.setParams(params);//当前request请求参数
		logger.setUser(user);//当前操作人
		String mainSql = "select * from kq_group where id = " + groupId + "  and (isdelete is null or isdelete <> '1') ";
		logger.setMainSql(mainSql, "id");//主表sql
		logger.setMainPrimarykey("id");//主日志表唯一key
		logger.setMainTargetNameColumn("groupname");
		SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo();
		String subSql1 =  "select * from kq_shiftschedule where groupid = " + groupId + "  and (isdelete is null or isdelete <> '1') ";
		subLogInfo1.setSubSql(subSql1,"id");
		logger.addSubLogInfo(subLogInfo1);
		logger.before(bizLogContext);
	}

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String, Object> retmap = new HashMap<String, Object>();
		RecordSet rs = new RecordSet();
		BatchRecordSet bRs = new BatchRecordSet();
		String sql = "";
		try{			
			//必要的权限判断
			if(!HrmUserVarify.checkUserRight("HrmKQGroup:Add",user)) {
		  	retmap.put("status", "-1");
		  	retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
		  	return retmap;
		  }

			List<List<Object>> lsFormatParams = new ArrayList<>();
			List<Object> formatParams = null;
			String id = Util.null2String(params.get("id"));//考勤组id
			String resourceids = Util.null2String(params.get("resourceids"));//人员id
			String groupId = Util.null2String(params.get("groupId"));//考勤组ID
			String month = Util.null2String(params.get("month"));//考勤组月份
			if(id.length()>0){
				sql = "select * from kq_shiftschedule where id = ? ";
				rs.executeQuery(sql,id);
				if(rs.next()){
					formatParams = new ArrayList<>();
					formatParams.add(rs.getString("resourceid"));
					formatParams.add(rs.getString("kqdate"));
					lsFormatParams.add(formatParams);
				}
				sql = "update kq_shiftschedule set isdelete = 1 where id= ? ";
				rs.executeUpdate(sql,id);
			}else{
				String beginDate = DateUtil.getFirstDayOfMonth(month+"-01");
				String endDate = DateUtil.getLastDayOfMonth(month+"-01");
				List<String> lsDate = new ArrayList<>();
				String today = DateUtil.getCurrentDate();
				Calendar cal = DateUtil.getCalendar();
				boolean isEnd = false;
				for(String date=beginDate; !isEnd;) {
					if(date.equals(endDate)) isEnd = true;
					lsDate.add(date);
					cal.setTime(DateUtil.parseToDate(date));
					date = DateUtil.getDate(cal.getTime(), 1);
				}

				List<String> lsResource = Util.splitString2List(resourceids,",");
				for(int i=0;i<lsResource.size();i++) {
					String resourceid = Util.null2String(lsResource.get(i));
					if(resourceid.length()==0)continue;
					for(int j=0;j<lsDate.size();j++) {
						String date = lsDate.get(j);
						if (DateUtil.timeInterval(date, today) >= 0) {
							formatParams = new ArrayList<>();
							formatParams.add(resourceid);
							formatParams.add(date);
							lsFormatParams.add(formatParams);
						}
					}
				}

				List sqlParams = new ArrayList();
				Object[] objects= DBUtil.transListIn(resourceids,sqlParams);
				sql = "update kq_shiftschedule set isdelete = 1 where  resourceid in("+objects[0]+") and groupid=? and kqdate>=? and kqdate<=? ";
				rs.executeUpdate(sql,sqlParams,groupId, beginDate,endDate);
			}

			new KQShiftScheduleComInfo().removeCache();
			//刷新报表数据
			new KQFormatBiz().format(lsFormatParams);

      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");
			retmap.put("message", SystemEnv.getHtmlLabelName(20461, user.getLanguage()));
		}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;
	}
	@Override
	public List<BizLogContext> getLogContexts() {
		return logger.getBizLogContexts();
	}

}
