<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.time.LocalDate" %>
<%@ page import="java.time.temporal.TemporalAdjusters" %>
<%@ page import="java.time.DayOfWeek" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="com.engine.kq.biz.KQGroupMemberComInfo" %>
<%@ page import="com.engine.kq.biz.KQGroupComInfo" %>
<%@ page import="com.engine.kq.biz.KQGroupBiz" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%

    User user = HrmUserVarify.getUser(request, response);
    if(user==null) {
        response.sendRedirect("/login/Login.jsp");
        return;
    }
    RecordSet rs = new RecordSet();
    String serialids = request.getParameter("serialids");

    String userid = request.getParameter("userid");
    String pbyf = request.getParameter("pbyf");
    String serdata = request.getParameter("serdata");
    List<String> restList = getSchedulingRestData();

    String worktime = "0";
    String totalworktime = "0";
    if(StringUtils.isNotBlank(serialids)){
        String sql = "";
        String[] serialidArray = serialids.split(",");
        for(int i=0;i<serialidArray.length;i++){
            String serialid = serialidArray[i];
            if(StringUtils.isNotBlank(serialid)){
                if(!restList.contains(serialid)){
                    String sql2 = " select try_convert(int,worktime) as worktime from kq_ShiftManagement where id ="+serialid+" and (isdelete = 0 or isdelete is null) " ;
                    sql += StringUtils.isBlank(sql) ?  sql2 : " union all \n"+sql2 ;
                }
            }
        }

        if(StringUtils.isNotBlank(sql)){
            sql = " select round(sum(worktime)/60.0,2) as worktime,sum(worktime) as totalworktime from ("+sql+") w ";
            rs.executeQuery(sql);
            if(rs.next()){
                worktime = Util.null2String(rs.getString("worktime"));
                totalworktime = Util.null2String(rs.getString("totalworktime"));
            }
        }
    }

    int restcount = 0;
    int weekrestcount = 0;

    Map<String,String> weekMap = queryWeekTypeByMonth(userid,pbyf);
    if(StringUtils.isNotBlank(serdata)){
        JSONArray jsonArray = JSONArray.parseArray(serdata);
        for(int i=0;i<jsonArray.size();i++){
            JSONObject dataJSON = jsonArray.getJSONObject(i);
            String date = dataJSON.getString("date");
            String serialid = dataJSON.getString("serialid");
            if(StringUtils.isNotBlank(serialid)){
                if(restList.contains(serialid)){
                    restcount++;
                }
            }

            if(weekMap.containsKey(date)){
                String value = weekMap.get(date);
                //6 = 周六 7 = 周日 11 = 公众假日、调配休息日
                if("6".equals(value) || "7".equals(value) || "11".equals(value)){
                    if(restList.contains(serialid)){
                        weekrestcount++;
                    }
                }
            }
        }
    }

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("data",worktime);
    jsonObject.put("total",totalworktime);
    jsonObject.put("restcount",restcount+"");
    jsonObject.put("weekrestcount",weekrestcount+"");
%>

<%=jsonObject.toJSONString() %>


<%!
    public Map<String,String> queryWeekTypeByMonth(String userid,String pbyf){

        Map<String,String> weekMap = new HashMap<String,String>();
        if(StringUtils.isNotBlank(pbyf) && pbyf.length() == 7) {
            LocalDate date = LocalDate.parse(pbyf + "-01"); // 获取当前日期
            LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
            LocalDate startDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth()); // 获取本月最后一天
            String monthStartDate = startDayOfMonth.toString();
            String monthEndDate = lastDayOfMonth.toString();
            Map<String,String> holidayMap = getHolidayByGroupId(userid,monthStartDate,monthEndDate);

            int thisMonth = date.getMonthValue(); // 获取当前是哪月
            int daysInMonth = date.lengthOfMonth(); // 获取本月有多少天

            for (int i = 1; i <= daysInMonth; i++) {
                LocalDate currentDate = LocalDate.of(date.getYear(), thisMonth, i);
                System.out.println("currentDate:" + currentDate.toString());
                DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
                System.out.println(i + "号是周 " + dayOfWeek.getValue());
                int weekValue = dayOfWeek.getValue();

                String changeType = "" ;
                if(holidayMap.containsKey(currentDate.toString())){
                    changeType = holidayMap.get(currentDate.toString());
                }

                if("1".equals(changeType) || "3".equals(changeType)){
                    weekValue = 11;
                }

                if(StringUtils.isNotBlank(changeType)){
                    weekMap.put(currentDate.toString(), weekValue+"");
                }else{
                    weekMap.put(currentDate.toString(), weekValue+"");
                }
            }
        }
        return weekMap;
    }

    public Map<String,String> getHolidayByGroupId(String userid,String monthStartDate,String monthEndDate){

        Map<String,String> holidayMap = new HashMap<String,String>();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();

        try {
            if(StringUtils.isNotBlank(userid) && StringUtils.isNotBlank(monthStartDate) && StringUtils.isNotBlank(monthEndDate)){
//                String activeGroupId = getUserActiveGroupId(userid);

                String fixedScheduleGroupId = "5";
                bb.writeLog("activeGroupId:"+fixedScheduleGroupId);
                if(StringUtils.isNotBlank(fixedScheduleGroupId)){
                    String sql =" select holidayDate,changeType from KQ_HolidaySet\n" +
                            " where groupid = " + fixedScheduleGroupId+
                            " and holidayDate >='"+monthStartDate+"'\n" +
                            " and holidayDate <='"+monthEndDate+"' " ;
                    rs.execute(sql);
                    while (rs.next()){
                        String holidayDate = Util.null2String(rs.getString("holidayDate"));
                        String changeType = Util.null2String(rs.getString("changeType"));
                        holidayMap.put(holidayDate,changeType);
                    }
                }
            }
        }catch (Exception e){

        }
        return holidayMap;
    }

    /***
     *
     * @param userid
     * @return
     */
    public String getUserActiveGroupId(String userid){
        BaseBean bb = new BaseBean();

        KQGroupMemberComInfo kqGroupMemberComInfo = null;
        KQGroupComInfo kqGroupComInfo = null ;
        String activeGroupId = "";
        try{
            kqGroupMemberComInfo = new KQGroupMemberComInfo();
            kqGroupComInfo = new KQGroupComInfo();

            Map<String, List<String>> groupMemberMap = getUserGroup();

            String activeGroup = "";
            if(groupMemberMap.containsKey(userid)){
                List<String> groupIds = groupMemberMap.get(userid);
                bb.writeLog("groupIds:"+groupIds.size());

                for(String i : groupIds){
                    String isDelete = kqGroupComInfo.getIsdelete(i);
                    if(!"1".equals(isDelete)) {
                        String currentGroupId = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userid, DateUtil.getCurrentDate()));
                        if (i.equals(currentGroupId)) {
                            activeGroupId =  i;
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog(e);
        }
        return activeGroupId;
    }


    /***
     *
     * @return
     */
    public Map<String, List<String>> getUserGroup(){
        BaseBean bb = new BaseBean();
        Map<String, List<String>> groupMemberMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        String viewScope = "3";
        try {
            KQGroupBiz kqGroupBiz = new KQGroupBiz();
            Map<String, Object> groupParams = new HashMap<String, Object>();
            if("3".equals(viewScope)){
                groupParams.put("isNoAccount", "1");
            }
            rs.executeQuery(kqGroupBiz.getGroupMemberSql(groupParams));
            while (rs.next()) {
                String id = rs.getString("resourceid");
                String gid = rs.getString("groupid");
                if (!groupMemberMap.containsKey(id))
                    groupMemberMap.put(id, new ArrayList<>());
                groupMemberMap.get(id).add(gid);
            }
        } catch (Exception e) {
        }
        return groupMemberMap;
    }

    public List<String> getSchedulingRestData(){

        List<String> list = new ArrayList<String>();
        RecordSet rs = new RecordSet();
        try{
            String sql =" select id " +
                        " from kq_ShiftManagement \n" +
                        " where is_rest = 1 \n" +
                        " and (isdelete is null or isdelete = 0) ";

            rs.executeQuery(sql);
            while (rs.next()){
                String id = Util.null2String(rs.getString("id"));
                list.add(id);
            }
        }catch (Exception e){

        }
        return list;
    }

%>



