package com.engine.kq.wfset.util;

import com.engine.kq.bean.KQHrmScheduleSign;
import com.engine.kq.biz.KQScheduleSignBiz;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.engine.kq.log.KQLog;
import com.engine.kq.util.KQDurationCalculatorUtil;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.report.manager.HrmReportManager.SignType;
import weaver.hrm.resource.ResourceComInfo;
import weaver.hrm.schedule.domain.HrmSchedule;
import weaver.systeminfo.SystemEnv;

public class KQSignUtil extends BaseBean {
  public static KQLog kqLog = new KQLog();

  private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  private static DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  private static DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

  /**
   * 根据考勤范围生成要查询的考勤表
   * @param onSignSectionTime
   * @param offSignSectionTime
   * @return
   */
  public static String buildSignSql(String onSignSectionTime, String offSignSectionTime) {
    RecordSet rs = new RecordSet();
    StringBuffer sql = new StringBuffer();
    if(rs.getDBType().equals("oracle")){
      sql.append(" signDate||' '||signTime>='").append(onSignSectionTime).append("' ");
      sql.append(" AND signDate||' '||signTime<='").append(offSignSectionTime).append("' ");
    }
    else if(rs.getDBType().equals("postgresql")){
      sql.append(" signDate||' '||signTime>='").append(onSignSectionTime).append("' ");
      sql.append(" AND signDate||' '||signTime<='").append(offSignSectionTime).append("' ");
    }
    else if(rs.getDBType().equals("mysql")){
      sql.append(" concat(signDate,' ',signTime)>='").append(onSignSectionTime).append("' ");
      sql.append(" AND concat(signDate,' ',signTime)<='").append(offSignSectionTime).append("' ");
    }else{
      sql.append(" signDate+' '+signTime>='").append(onSignSectionTime).append("' ");
      sql.append(" AND signDate+' '+signTime<='").append(offSignSectionTime).append("' ");
    }
    return sql.toString();
  }

  /**
   *
   * @param resourceid 人员id
   * @param curDate 查询日期
   * @param showCard 是否显示补卡数据 true表示显示，默认显示
   * @return
   */
  public static List<Object> getSignInfo4MyAttendance(String resourceid,String curDate,boolean showCard){
    List<Object> signInfos = new ArrayList<>();
    Map<String, Object> todayLineMap = KQDurationCalculatorUtil.getWorkButton(resourceid, curDate,false);
    if(todayLineMap.get("signTime") != null){
      List<Map<String, String>> todaySignTime = (List<Map<String, String>>)todayLineMap.get("signTime");
      if(todaySignTime != null && !todaySignTime.isEmpty()){
        getTodaySignInfo(todaySignTime,signInfos,resourceid,curDate,showCard);
      }else{
        getNonWorkDaySignInfo(signInfos,resourceid,curDate,showCard);
      }
    }else{
      getNonWorkDaySignInfo(signInfos,resourceid,curDate,showCard);
    }
    return signInfos;
  }

  /**
   * 获取非工作时段的打卡记录
   * @param signInfos
   * @param resourceid
   * @param curDate
   * @param showCard
   */
  public static void getNonWorkDaySignInfo(List<Object> signInfos,String resourceid, String curDate, boolean showCard) {
    String signDateTimeSql = "";
    String signInDateTime = curDate + " 00:00:00";
    String signOutDateTime = curDate + " 23:59:59";
    String buildSql = buildSignSql(signInDateTime, signOutDateTime);
    kqLog.info("resourceid:"+resourceid+":curDate:"+curDate+":signInDateTime:"+signInDateTime+":signOutDateTime:"+signOutDateTime);
    if(buildSql.length() > 0){
      signDateTimeSql += buildSql;
    }
    if(!showCard){
      RecordSet rs = new RecordSet();
      if(rs.getDBType().equalsIgnoreCase("oracle")) {
        signDateTimeSql += " and nvl(signfrom,'') not like 'card%' ";
      }else if((rs.getDBType()).equalsIgnoreCase("mysql")){
        signDateTimeSql += " and ifnull(signfrom,'') not like 'card%' ";
      }else {
        signDateTimeSql += " and isnull(signfrom,'') not like 'card%' ";
      }
    }
    KQScheduleSignBiz kqScheduleSignBiz = new KQScheduleSignBiz.KQScheduleSignParamBuilder().resourceidParam(resourceid).
        signDateTimeSqlParam(signDateTimeSql).build();
    fillSignInfos(kqScheduleSignBiz, signInfos);
  }

  /**
   * 获取工作时段的打卡记录
   * @param todaySignTime
   * @param signInfos
   * @param resourceid
   * @param curDate
   * @param showCard
   */
  public static void getTodaySignInfo(List<Map<String, String>> todaySignTime,List<Object> signInfos, String resourceid,String curDate,boolean showCard) {

    String signDateTimeSql = "";
    if(!showCard){
      RecordSet rs = new RecordSet();
      if(rs.getDBType().equalsIgnoreCase("oracle")) {
        signDateTimeSql += " and nvl(signfrom,'') not like 'card%' ";
      }else if((rs.getDBType()).equalsIgnoreCase("mysql")){
        signDateTimeSql += " and ifnull(signfrom,'') not like 'card%' ";
      }else {
        signDateTimeSql += " and isnull(signfrom,'') not like 'card%' ";
      }
    }

    String yesterday = LocalDate.parse(curDate).minusDays(1).format(dateFormatter);
    String nextday = LocalDate.parse(curDate).plusDays(1).format(dateFormatter);
    for(int i = 0 ; i < todaySignTime.size() ; i++) {
      Map<String, String> todaySignMap = todaySignTime.get(i);
      String bengintime = Util.null2s(todaySignMap.get("bengintime"),"");
      String bengintime_across = Util.null2s(todaySignMap.get("bengintime_across"),"");
      String bengintime_end = Util.null2s(todaySignMap.get("bengintime_end"),"");
      String bengintime_end_across = Util.null2s(todaySignMap.get("bengintime_end_across"),"");

      String endtime = Util.null2s(todaySignMap.get("endtime"),"");
      String endtime_across = Util.null2s(todaySignMap.get("endtime_across"),"");
      String endtime_start = Util.null2s(todaySignMap.get("endtime_start"),"");
      String endtime_start_across = Util.null2s(todaySignMap.get("endtime_start_across"),"");

      String signInDateTime = curDate + " " +bengintime+":00";
      if("1".equalsIgnoreCase(bengintime_across)) {
        signInDateTime = yesterday + " " +bengintime+":00";
      }
      String  signInEndDateTime = "";
      if(bengintime_end.length() > 0){
        signInEndDateTime = curDate + " " +bengintime_end+":00";
        if("1".equalsIgnoreCase(bengintime_end_across)) {
          signInEndDateTime = nextday + " " +bengintime_end+":00";
        }
      }
      String signOutDateTime = curDate + " " +endtime+":59";
      if("1".equalsIgnoreCase(endtime_across)) {
        signOutDateTime = nextday + " " +endtime+":59";
      }
      String signOutBeginDateTime = "";
      if(endtime_start.length() > 0){
        signOutBeginDateTime = curDate + " " +endtime_start+":59";
        if("1".equalsIgnoreCase(endtime_start_across)) {
          signOutBeginDateTime = nextday + " " +endtime_start+":59";
        }
      }

      String sign_signSectionTime = "";
      String sign_signSectionEndTime = "";
      String sign_signSectionBeginTime = "";
      String sign_offSignSectionTime = "";
      if(signInEndDateTime.length() == 0 && signOutBeginDateTime.length() == 0){
        //如果没设置上班后，下班前打卡
        sign_signSectionTime = signInDateTime;
        sign_offSignSectionTime = signOutDateTime;
      }else{
        if(signInEndDateTime.length() > 0){
          if(signOutBeginDateTime.length() > 0){
            //如果上班后，下班前打卡范围都做了控制
            sign_signSectionTime = signInDateTime;
            sign_signSectionEndTime = signInEndDateTime;
            sign_signSectionBeginTime = signOutBeginDateTime;
            sign_offSignSectionTime = signOutDateTime;

          }else{
            LocalDateTime onLocalDateEndTime = LocalDateTime.parse(signInEndDateTime,fullFormatter);
            //如果只是上班后打卡范围做了控制
            LocalDateTime tmp = LocalDateTime.parse(onLocalDateEndTime.plusMinutes(1).format(datetimeFormatter)+":00",fullFormatter);
            String tmp_datetime = tmp.format(fullFormatter);
            sign_signSectionTime = signInDateTime;
            sign_signSectionEndTime = signInEndDateTime;
            sign_signSectionBeginTime = tmp_datetime;
            sign_offSignSectionTime = signOutDateTime;

          }
        }else if(signOutBeginDateTime.length() > 0){
          //如果只是下班前打卡范围做了控制
          LocalDateTime offLocalDateBeginTime = LocalDateTime.parse(signOutBeginDateTime,fullFormatter);
          LocalDateTime tmp = LocalDateTime.parse(offLocalDateBeginTime.minusMinutes(1).format(datetimeFormatter)+":59",fullFormatter);
          String tmp_datetime = tmp.format(fullFormatter);
          sign_signSectionTime = signInDateTime;
          sign_signSectionEndTime = tmp_datetime;
          sign_signSectionBeginTime = signOutBeginDateTime;
          sign_offSignSectionTime = signOutDateTime;
        }
      }

      KQScheduleSignBiz kqScheduleSignBiz = new KQScheduleSignBiz.KQScheduleSignParamBuilder().resourceidParam(resourceid)
          .signSectionTimeParam(sign_signSectionTime).signSectionEndTimeParam(sign_signSectionEndTime)
          .signSectionBeginTimeParam(sign_signSectionBeginTime).offSignSectionTimeParam(sign_offSignSectionTime).
              signDateTimeSqlParam(signDateTimeSql).build();
      fillSignInfos(kqScheduleSignBiz, signInfos);
    }
  }

  public static void fillSignInfos(KQScheduleSignBiz kqScheduleSignBiz,List<Object> signInfos){

    Map<String,KQHrmScheduleSign> signMap = kqScheduleSignBiz.getScheduleSignInfoWithCardRange();
    if(signMap != null && !signMap.isEmpty()) {
      Map<String,Object> signInfo = new HashMap<>();
      KQHrmScheduleSign signInTimeBean = signMap.get("signin");
      KQHrmScheduleSign signOutTimeBean = signMap.get("signout");
      if(signInTimeBean != null){
        String signdate = Util.null2String(signInTimeBean.getSigndate());
        String signtime= Util.null2String(signInTimeBean.getSigntime());
        String clientaddress = Util.null2String(signInTimeBean.getClientaddress());
        String addr = Util.null2String(signInTimeBean.getAddr());
        signInfo.put("on_signdate", signdate);
        signInfo.put("on_signtime", signtime);
        signInfo.put("on_clientaddress", clientaddress);
        signInfo.put("on_position", addr);
      }
      if(signOutTimeBean != null){
        String signdate = Util.null2String(signOutTimeBean.getSigndate());
        String signtime= Util.null2String(signOutTimeBean.getSigntime());
        String clientaddress = Util.null2String(signOutTimeBean.getClientaddress());
        String addr = Util.null2String(signOutTimeBean.getAddr());
        signInfo.put("off_signdate", signdate);
        signInfo.put("off_signtime", signtime);
        signInfo.put("off_clientaddress", clientaddress);
        signInfo.put("off_position", addr);
      }
      if(!signInfo.isEmpty()){
        signInfos.add(signInfo);
      }
    }
  }

  /**
   * 兼容E8的 HrmScheduleDiffDetSignInManager 和 HrmScheduleDiffDetSignOutManager
   * @param signtype
   * @param resourceId
   * @param fromdate
   * @param todate
   * @param user
   */
  public static List<Map<String, Object>> getKQSignData(SignType signtype,String resourceId,String fromdate,String todate){
    List<Map<String, Object>> scheduleList = new ArrayList<Map<String, Object>>();
    try{
      ResourceComInfo resourceComInfo = new ResourceComInfo();
      DepartmentComInfo departmentComInfo = new DepartmentComInfo();
      RecordSet rs = new RecordSet();
      RecordSet rs1 = new RecordSet();
      String sql = "select * from kq_format_detail where resourceid = ? and kqdate >= ? and kqdate <= ? ";
      rs.executeQuery(sql, resourceId,fromdate,todate);
      while (rs.next()){
        String signindate = rs.getString("signindate");
        String signintime = rs.getString("signintime");
        String signoutdate = rs.getString("signoutdate");
        String signouttime = rs.getString("signouttime");
        String signinid = rs.getString("signinid");
        String signoutid = rs.getString("signoutid");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("subCompanyId", resourceComInfo.getSubCompanyID(resourceId));
        map.put("departmentId", resourceComInfo.getDepartmentID(resourceId));
        map.put("departmentName", departmentComInfo.getDepartmentName(resourceComInfo.getDepartmentID(resourceId)));
        map.put("resourceId", resourceId);
        map.put("resourceName", resourceComInfo.getLastname(resourceId));
        map.put("statusName", getStatusName(resourceComInfo.getStatus(resourceId),resourceId));
        map.put("status", resourceComInfo.getStatus(resourceId));
        map.put("workcode", resourceComInfo.getWorkcode(resourceId));
        map.put("currentDate", DateUtil.getCurrentDate());
        String get_sign_info_sql = "select * from hrmschedulesign where id = ? ";
        if(signtype == SignType.SIGN_IN){
          map.put("signId", signinid);
          map.put("signDate", signindate);
          map.put("signTime", signintime);
        }else if(signtype == SignType.SIGN_OUT){
          map.put("signId", signoutid);
          map.put("signDate", signoutdate);
          map.put("signTime", signouttime);
        }
        map.put("mfer", signtype.getName());
        rs1.executeQuery(get_sign_info_sql, signinid);
        if(rs1.next()){
          map.put("clientAddress", Util.null2String(rs1.getString("clientaddress")));
          map.put("_addr", Util.null2String(rs1.getString("addr")));
          map.put("longitude", Util.null2String(rs1.getString("longitude")));
          map.put("latitude", Util.null2String(rs1.getString("latitude")));
        }
        scheduleList.add(map);
      }

    }catch (Exception e){
      e.printStackTrace();
    }
    return scheduleList;
  }

  /**
   * 获取人员状态
   * @param status
   * @param resourceId
   * @return
   */
  private static String getStatusName(String status, String resourceId) {
    String statusName = "";
    int lanId = new User(Util.getIntValue(resourceId)).getLanguage();
    if (StringUtil.isNotNull(status)) {
      if (status.equals("0")) {
        statusName = SystemEnv.getHtmlLabelName(15710, lanId);
      } else if (status.equals("1")) {
        statusName = SystemEnv.getHtmlLabelName(15711, lanId);
      } else if (status.equals("2")) {
        statusName = SystemEnv.getHtmlLabelName(480, lanId);
      } else if (status.equals("3")) {
        statusName = SystemEnv.getHtmlLabelName(15844, lanId);
      } else if (status.equals("4")) {
        statusName = SystemEnv.getHtmlLabelName(6094, lanId);
      } else if (status.equals("5")) {
        statusName = SystemEnv.getHtmlLabelName(6091, lanId);
      } else if (status.equals("6")) {
        statusName = SystemEnv.getHtmlLabelName(6092, lanId);
      } else if (status.equals("7")) {
        statusName = SystemEnv.getHtmlLabelName(2245, lanId);
      } else if (status.equals("10")) {
        statusName = SystemEnv.getHtmlLabelName(1831, lanId);
      }
    }
    return statusName;
  }

}
