package com.engine.kq.cmd.shiftschedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.KQShiftScheduleComInfo;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.util.UtilKQ;
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 SaveShiftScheduleCmd extends AbstractCommonCommand<Map<String, Object>> {

  private SimpleBizLogger logger;

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

    String data = Util.null2String(params.get("data"));
    JSONObject jsonObj = JSON.parseObject(data);
    String groupId = Util.null2String(jsonObj.get("groupId"));

    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 today = DateUtil.getCurrentDate();
    String sql = "";
    try{
      //必要的权限判断
      if(!HrmUserVarify.checkUserRight("HrmKQGroup:Add",user)) {
        retmap.put("status", "-1");
        retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
        return retmap;
      }
      String data = Util.null2String(params.get("data"));
      JSONObject jsonObj = JSON.parseObject(data);
      String groupId = Util.null2String(jsonObj.get("groupId"));
      JSONArray datas = jsonObj.getJSONArray("datas");

      List<List<Object>> paramInsert = new ArrayList<List<Object>>();
      List<List<Object>> paramUpdate = new ArrayList<List<Object>>();
      List<Object> params = null;
      String delIds = "";
      List<List<Object>> lsFormatParams = new ArrayList<>();
      List<Object> formatParams = null;
      List<List<Object>> lsDeleteParams = new ArrayList<>();
      List<Object> deleteParams = null;
      List<List<Object>> lscheckSerialParams = new ArrayList<>();
      List<Object> checkSerialParams = null;

      JSONObject resourceDataObj = null;
      JSONArray arrKqDataObj = null;
      JSONObject kqDataObj = null;
      for(int i=0;datas!=null&&i<datas.size();i++){
        resourceDataObj = (JSONObject)datas.get(i);
        String resourceid = Util.null2String(resourceDataObj.get("resourceid"));
        arrKqDataObj = resourceDataObj.getJSONArray("kqdata");
        for(int j=0;arrKqDataObj!=null&&j<arrKqDataObj.size();j++) {
          kqDataObj = (JSONObject) arrKqDataObj.get(j);
          String id = Util.null2String(kqDataObj.get("id"));
          String date = Util.null2String(kqDataObj.get("date"));
          String serialid = Util.null2String(kqDataObj.get("serialid"));
          if(serialid.equals("-999"))serialid="";
          //if(weaver.common.DateUtil.timeInterval(date,today)>0)continue;//今天之前的无需处理
          if(id.length()>0){
            if(serialid.length()==0){
              if(delIds.length()>0)delIds+=",";
              delIds+=id;
            }else {
              params = new ArrayList<Object>();
              params.add(serialid);
              params.add(id);
              paramUpdate.add(params);
            }
          }else{
            if(serialid.length()==0)continue;;
            params = new ArrayList<Object>();
            params.add(date);
            params.add(serialid);
            params.add(resourceid);
            params.add(groupId);
            paramInsert.add(params);
          }
          if(DateUtil.timeInterval(date,today)>=0) {
            formatParams = new ArrayList<>();
            formatParams.add(resourceid);
            formatParams.add(date);
            lsFormatParams.add(formatParams);
          }

          deleteParams = new ArrayList<>();
          deleteParams.add(resourceid);
          deleteParams.add(date);
          lsDeleteParams.add(deleteParams);

          checkSerialParams = new ArrayList<>();
          checkSerialParams.add(resourceid);
          checkSerialParams.add(date);
          checkSerialParams.add(serialid);
          lscheckSerialParams.add(checkSerialParams);
        }
      }

      sql = " update kq_shiftschedule set serialid=?,isDelete=0 where id = ? ";
      for (int i = 0; paramUpdate != null && i < paramUpdate.size(); i++) {
        List<Object> update_params = paramUpdate.get(i);
        String serialid = Util.null2String(update_params.get(0));
        String id = Util.null2String(update_params.get(1));
        rs.executeUpdate(sql, serialid,id);
      }

      sql = "insert into kq_shiftschedule (kqdate,serialid,resourceid,groupid,isDelete) values(?,?,?,?,0)";
      for (int i = 0; paramInsert != null && i < paramInsert.size(); i++) {
        List<Object> insert_params = paramInsert.get(i);
        String kqdate = Util.null2String(insert_params.get(0));
        String serialid = Util.null2String(insert_params.get(1));
        String resourceid = Util.null2String(insert_params.get(2));
        String groupid = Util.null2String(insert_params.get(3));
        rs.executeUpdate(sql, kqdate,serialid,resourceid,groupid);
      }

      if(delIds.length()>0){
        List sqlParams = new ArrayList();
        Object[] objects= DBUtil.transListIn(delIds,sqlParams);
        sql = "update kq_shiftschedule set isdelete =1 where id in("+objects[0]+") ";
        rs.executeUpdate(sql, sqlParams);
      }

      //删除之前的排的班次，一天只能有一个班次
      sql = " update kq_shiftschedule set isdelete =1 where resourceid = ? and kqdate = ? and groupid != "+groupId;
      for (int i = 0; lsDeleteParams != null && i < lsDeleteParams.size(); i++) {
        List<Object> delete_params = lsDeleteParams.get(i);
        String resourceid = Util.null2String(delete_params.get(0));
        String kqdate = Util.null2String(delete_params.get(1));
        rs.executeUpdate(sql, resourceid,kqdate);
      }

      sql = " update kq_shiftschedule set isdelete =1 where resourceid = ? and kqdate = ? and serialid != ? ";
      for (int i = 0; lscheckSerialParams != null && i < lscheckSerialParams.size(); i++) {
        List<Object> check_params = lscheckSerialParams.get(i);
        String resourceid = Util.null2String(check_params.get(0));
        String kqdate = Util.null2String(check_params.get(1));
        String serialid = Util.null2String(check_params.get(2));
        rs.executeUpdate(sql, resourceid,kqdate,serialid);
      }

      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(18758, 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();
  }
}
