package com.engine.kq.cmd.reportdetial;

import com.alibaba.fastjson.JSON;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.KQTransMethod;
import com.engine.kq.util.TransMethod;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 考勤报表日明细
 */
public class GetDailyDetialInfoCmd extends AbstractCommonCommand<Map<String, Object>> {

  public GetDailyDetialInfoCmd(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 {
      KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
      ResourceComInfo resourceComInfo = new ResourceComInfo();
      KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
      TransMethod transMethod = new TransMethod();
      String dialogTitle = "";
      Map<String, Object> userInfo = new HashMap<>();
      Map<String, Object> signInfo = new HashMap<>();
      Map<String, Object> table = new HashMap<>();
      List<Object> columns = new ArrayList();
      Map<String, Object> column = null;
      List<Object> datas = new ArrayList();
      Map<String, Object> data = null;
      Map<String,Object> signStatusInfo = null;
      List<String> logList = null;

      String resourceId = Util.null2String(params.get("resourceId"));
      String kqDate = Util.null2String(params.get("kqDate"));
      String lastname = resourceComInfo.getLastname(resourceId);

      dialogTitle = lastname + " " + kqDate + " " + new KQTransMethod().getRelatedDayName(kqDate, "" + user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(25988, user.getLanguage());

      userInfo.put("lastname", lastname);
      userInfo.put("shortname", User.getLastname(Util.null2String(Util.formatMultiLang(lastname, "" + user.getLanguage()))));
      userInfo.put("messagerurl", resourceComInfo.getMessagerUrls(resourceId));

      String groupId ="";
      String kqType = "";
      int attendanceMins = 0;
      sql = "select groupid, attendanceMins from kq_format_total where resourceid=? and kqdate=? ";
      rs.executeQuery(sql,resourceId,kqDate);
      if(rs.next()){
        groupId = Util.null2String(rs.getString("groupid"));
        kqType = kqGroupComInfo.getKqtype(groupId);
        attendanceMins += rs.getInt("attendanceMins");
        if(attendanceMins<0)attendanceMins=0;
      }

      if(kqType.equals("3")){
        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(	413, user.getLanguage()));
        column.put("dataIndex", "lastname");
        column.put("key", "lastname");
        columns.add(column);

        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(18949, user.getLanguage()));
        column.put("dataIndex", "signtime");
        column.put("key", "signtime");
        columns.add(column);

        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(390501, user.getLanguage()));
        column.put("dataIndex", "addr");
        column.put("key", "addr");
        columns.add(column);

        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(	32531, user.getLanguage()));
        column.put("dataIndex", "clientaddress");
        column.put("key", "clientaddress");
        columns.add(column);

        String serailName = SystemEnv.getHtmlLabelName(	16039, user.getLanguage())+kqGroupComInfo.getSignstart(groupId)+","+
                           SystemEnv.getHtmlLabelName(	390053, user.getLanguage())+kqGroupComInfo.getWorkhour(groupId)+SystemEnv.getHtmlLabelName(	391, user.getLanguage());

//      弹性工作制是否可以跨天
        boolean isFreezeAcross = KQSettingsBiz.is_freeAcross();

        String signBeginDateTime = kqDate + " "+kqGroupComInfo.getSignstart(groupId)+":00";
        String signEndDateTime = kqDate + " "+"23:59:59";
        if(isFreezeAcross){
          signBeginDateTime = kqDate + " "+ kqGroupComInfo.getSignstart(groupId)+":00";
          signEndDateTime = DateUtil.addDate(kqDate, 1) + " "+ kqGroupComInfo.getSignstart(groupId)+":00";
        }
        String sqlwhere = " where userid = ? and signdate= ? ";
        if(rs.getDBType().equals("oracle")){
          sqlwhere = " where userid = ? and signdate||' '||signtime >= ? and signdate||' '||signtime <= ? ";
        }else if("sqlserver".equals(rs.getDBType())){
          sqlwhere = " where userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ?  ";
        }else{
          sqlwhere = " where userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ?  ";
        }
        String groupName = "";
        int signCount = 0;
        sql = " select * from hrmschedulesign " +sqlwhere+
                " order by signdate asc, signtime asc ";
        rs.executeQuery(sql,resourceId,signBeginDateTime,signEndDateTime);
        signCount = rs.getCounts();
        while (rs.next()) {
          data = new HashMap<>();
          data.put("lastname", lastname);
          data.put("signtime", Util.null2String(rs.getString("signtime")));
          data.put("addr", Util.null2String(rs.getString("addr")));
          data.put("clientaddress", Util.null2String(rs.getString("clientaddress")));
          datas.add(data);

        }
        groupName = kqGroupComInfo.getGroupname(groupId);
        userInfo.put("schedual", SystemEnv.getHtmlLabelName(390221, user.getLanguage())+":"+groupName);
        signInfo.put("signInfo", SystemEnv.getHtmlLabelName(519601, user.getLanguage()).
                replace("$signCount$", "" + signCount).replace("$workHour$", transMethod.getReportDetialMinToHour(""+attendanceMins)).replace("\"",""));
        userInfo.put("shiftInfo", SystemEnv.getHtmlLabelName(24803, user.getLanguage())+":"+serailName);
      }else{
        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(27961, user.getLanguage()));
        column.put("dataIndex", "workTime");
        column.put("key", "workTime");
        columns.add(column);

        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(18949, user.getLanguage()));
        column.put("dataIndex", "signTime");
        column.put("key", "signTime");
        columns.add(column);

        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(525243, user.getLanguage()));
        column.put("dataIndex", "signStatus");
        column.put("key", "signStatus");
        columns.add(column);

        column = new HashMap<>();
        column.put("title", SystemEnv.getHtmlLabelName(390501, user.getLanguage()));
        column.put("dataIndex", "addr");
        column.put("key", "addr");
        columns.add(column);

        String serailName = "";
        String workSections = "";
        String groupName = "";
        int signCount = 0;
        sql = " select kqdate, resourceid,groupid,serialid,serialnumber,workbegindate,workbegintime, " +
                " workenddate,workendtime,workmins,signindate,signintime,signinid,signoutdate,signouttime,signoutid, " +
                " attendanceMins,belatemins,graveBeLateMins,leaveearlymins,graveLeaveEarlyMins,absenteeismmins," +
                " forgotcheckmins,forgotBeginWorkCheckMins,leaveMins,leaveInfo,evectionMins,outMins,otherinfo " +
                " from kq_format_detail b " +
                " where resourceid = " + resourceId + " and kqdate ='" + kqDate + "' " +
                " order by serialnumber ";
        rs.execute(sql);
        while (rs.next()) {
          KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo();
          String resourceid = Util.null2String(rs.getString("resourceid"));
          String kqdate = Util.null2String(rs.getString("kqdate"));
          String groupid = Util.null2String(rs.getString("groupid"));
          String serialid = Util.null2String(rs.getString("serialid"));
          String workbegindate = Util.null2String(rs.getString("workbegindate")).trim();
          String workbegintime = Util.null2String(rs.getString("workbegintime")).trim();
          String workenddate = Util.null2String(rs.getString("workenddate")).trim();
          String workendtime = Util.null2String(rs.getString("workendtime")).trim();
          int workMins = rs.getInt("workMins");
          String signinid = Util.null2String(rs.getString("signinid")).trim();
          String signintime = Util.null2String(rs.getString("signintime")).trim();
          String signoutid = Util.null2String(rs.getString("signoutid")).trim();
          String signouttime = Util.null2String(rs.getString("signouttime")).trim();
          //attendanceMins += rs.getInt("attendanceMins");
          String beLateMins = Util.null2String(rs.getString("beLateMins")).trim();
          String graveBeLateMins = Util.null2String(rs.getString("graveBeLateMins")).trim();
          String leaveEarlyMins= Util.null2String(rs.getString("leaveEarlyMins")).trim();
          String graveLeaveEarlyMins= Util.null2String(rs.getString("graveLeaveEarlyMins")).trim();
          String absenteeismMins= Util.null2String(rs.getString("absenteeismMins")).trim();
          String forgotCheckMins = Util.null2String(rs.getString("forgotCheckMins")).trim();
          String forgotBeginWorkCheckMins = Util.null2String(rs.getString("forgotBeginWorkCheckMins")).trim();
          int leaveMins = rs.getInt("leaveMins");
          String leaveInfo = Util.null2String(rs.getString("leaveInfo"));
          String otherinfo = Util.null2String(rs.getString("otherinfo"));
          if(otherinfo.length() > 0){
            Map<String,Object> jsonObject = JSON.parseObject(otherinfo);
            if(jsonObject.containsKey("logList")){
              logList = (List<String>) jsonObject.get("logList");
            }
          }
          int evectionMins = rs.getInt("evectionMins");
          int outMins = rs.getInt("outMins");

          serailName = kqShiftManagementComInfo.getSerial(serialid);
          if (workbegintime.length() > 0 && workendtime.length() > 0) {
            workSections += workbegintime + "-" + workendtime;
          }
          groupName = kqGroupComInfo.getGroupname(groupid);
          userInfo.put("schedual", SystemEnv.getHtmlLabelName(390221, user.getLanguage())+":"+groupName);


          if (signintime.length() > 0) signCount++;
          if (signouttime.length() > 0) signCount++;

          if(serialid.length()>0){
            if (workbegintime.length() > 0) {
              signStatusInfo = new HashMap();
              signStatusInfo.put("workdate",workbegindate);
              signStatusInfo.put("worktime",workbegintime);
              signStatusInfo.put("signtime",signintime);
              signStatusInfo.put("beLateMins",beLateMins);
              signStatusInfo.put("forgotBeginWorkCheckMins",forgotBeginWorkCheckMins);
              signStatusInfo.put("graveBeLateMins",graveBeLateMins);
              signStatusInfo.put("absenteeismMins",absenteeismMins);
              signStatusInfo.put("leaveMins",leaveMins);
              signStatusInfo.put("leaveInfo",leaveInfo);
              signStatusInfo.put("evectionMins",evectionMins);
              signStatusInfo.put("outMins",outMins);

              data = new HashMap<>();
              data.put("workTime", workbegintime);
              data.put("signTime", signintime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signintime);
              data.put("signStatus", KQReportBiz.getSignStatus(signStatusInfo,user,"on"));
              Map<String,Object> signDetailInfo = getSignDetailInfo(signinid);
              data.put("addr", Util.null2String(signDetailInfo.get("addr")));
              datas.add(data);
            }

            if (workendtime.length() > 0) {
              signStatusInfo = new HashMap();
              signStatusInfo.put("workdate",workenddate);
              signStatusInfo.put("worktime",kqTimesArrayComInfo.turn48to24Time(workendtime));
              signStatusInfo.put("signtime",signouttime);
              signStatusInfo.put("leaveEarlyMins",leaveEarlyMins);
              signStatusInfo.put("graveLeaveEarlyMins",graveLeaveEarlyMins);
              signStatusInfo.put("forgotCheckMins",forgotCheckMins);
              signStatusInfo.put("absenteeismMins",absenteeismMins);
              signStatusInfo.put("leaveMins",leaveMins);
              signStatusInfo.put("leaveInfo",leaveInfo);
              signStatusInfo.put("evectionMins",evectionMins);
              signStatusInfo.put("outMins",outMins);

              data = new HashMap<>();
              data.put("workTime", kqTimesArrayComInfo.turn48to24Time(workendtime));
              data.put("signTime", signouttime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signouttime);
              data.put("signStatus", KQReportBiz.getSignStatus(signStatusInfo,user,"off"));
              Map<String,Object> signDetailInfo = getSignDetailInfo(signoutid);
              data.put("addr", Util.null2String(signDetailInfo.get("addr")));
              datas.add(data);
            }
          }else {
            signStatusInfo = new HashMap();
            signStatusInfo.put("leaveMins",leaveMins);
            signStatusInfo.put("leaveInfo",leaveInfo);
            signStatusInfo.put("evectionMins",evectionMins);
            signStatusInfo.put("outMins",outMins);

            if(signinid.length() > 0){
              data = new HashMap<>();
              data.put("signStatus", KQReportBiz.getSignStatus(signStatusInfo,user,""));
              data.put("signTime", signintime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signintime);
              Map<String,Object> signDetailInfo = getSignDetailInfo(signinid);
              data.put("addr", Util.null2String(signDetailInfo.get("addr")));
              datas.add(data);
              if(signoutid.length() > 0){
                data = new HashMap<>();
                data.put("signStatus", KQReportBiz.getSignStatus(signStatusInfo,user,""));
                data.put("signTime", signouttime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signouttime);
                signDetailInfo = getSignDetailInfo(signoutid);
                data.put("addr", Util.null2String(signDetailInfo.get("addr")));
                datas.add(data);
              }
            }else{
              data = new HashMap<>();
              data.put("signStatus", KQReportBiz.getSignStatus(signStatusInfo,user,""));
              datas.add(data);
            }
          }
        }
        if (workSections.length() > 0) {
          serailName += "(" + workSections + ")";
        }
        String minToHour = transMethod.getReportDetialMinToHour(""+attendanceMins);
        signInfo.put("signInfo", SystemEnv.getHtmlLabelName(519601, user.getLanguage()).toLowerCase().
                replace("$signcount$", "" + signCount).
                replace("$signcount $", "" + signCount).
                replace("$workhour$", minToHour).replace("$workhour $", minToHour).replace("\"",""));
        userInfo.put("shiftInfo", SystemEnv.getHtmlLabelName(24803, user.getLanguage())+":"+serailName);
      }

      table.put("columns",columns);
      table.put("datas",datas);

      retmap.put("dialogTitle", dialogTitle);
      retmap.put("userInfo", userInfo);
      retmap.put("signInfo", signInfo);
      retmap.put("table", table);
      if(logList != null){
        retmap.put("logList", logList);
      }
      retmap.put("status", "1");
    } catch (Exception e) {
      retmap.put("status", "-1");
      retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
      writeLog(e);
    }
    return retmap;
  }

  private Map<String,Object> getSignDetailInfo(String id){
    Map<String,Object> resultMap = new HashMap<>();
    RecordSet rs = new RecordSet();
    String sql = "";
    try{
      sql = " select addr from hrmschedulesign where id = ? ";
      rs.executeQuery(sql,id);
      if(rs.next()){
        resultMap.put("addr",Util.null2String(rs.getString("addr")));
      }
    }catch (Exception e){
      writeLog(e);
    }
    return resultMap;
  }
  @Override
  public BizLogContext getLogContext() {
    return null;
  }

}
