<%@ 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.common.DateUtil" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ 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="java.time.LocalDate" %>
<%@ page import="java.time.format.DateTimeFormatter" %>
<%@ page import="java.time.DayOfWeek" %>
<%@ page import="java.time.temporal.TemporalAdjusters" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%

    String[] workSchedule = {"09:00-11:00","11:00-16:00","16:00-20:00","20:00-21:30"};
    User user = HrmUserVarify.getUser(request, response);
    if(user==null) {
        response.sendRedirect("/login/Login.jsp");
        return;
    }
//    int userid = user.getUID();
    BaseBean bb = new BaseBean();
    RecordSet rs = new RecordSet();
    String cjr = request.getParameter("cjr");
    String pbyf = request.getParameter("pbyf");
    String yjl = request.getParameter("yjl");  //mdyj
    String cjrbm = request.getParameter("cjrbm");


    String activeGroupId = getUserActiveGroupId(cjr+"");
//    List<Map<String,Object>> scheduleList = queryShiftScheduleByUser(pbyf,activeGroupId,cjr);
//    out.println("scheduleList"+ JSON.toJSON(scheduleList));

    List<Map<String,String>> hrmList = new ArrayList<Map<String,String>>();

//    out.println("cjrbm:"+cjrbm+"</br>");
    if(StringUtils.isNotBlank(cjrbm)) {
        String sql = "select id,lastname from hrmresource where departmentid = "+cjrbm +" and status in(0,1,2,3) ";
        hrmList = queryListBySql(sql);
    }

    int daysInMonth = 0;
    Map<String, String> holidayMap = new HashMap<String, String>();
    List<String> daysList = new ArrayList<String>();
    Map<String,String> weekMap = new HashMap<String,String>();

    List<Map<String,String>> weekList = new ArrayList<Map<String,String>>();


    if(StringUtils.isNotBlank(pbyf) && pbyf.length() == 7) {
        LocalDate localDate = LocalDate.parse(pbyf + "-01"); // 获取当前日期
        LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
        LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth()); // 获取本月最后一天

//        for (LocalDate date = firstDayOfMonth; !date.isAfter(lastDayOfMonth); date = date.plusDays(1)) {
//            daysList.add(date.toString());
//        }

        String monthStartDate = firstDayOfMonth.toString();
        String monthEndDate = lastDayOfMonth.toString();
        holidayMap = getHolidayByGroupId(monthStartDate, monthEndDate,activeGroupId);

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

        for (int i = 1; i <= daysInMonth; i++) {
            LocalDate currentDate = LocalDate.of(localDate.getYear(), thisMonth, i);

            daysList.add(currentDate.toString());

//            System.out.println("currentDate:" + currentDate.toString());
            DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
//            System.out.println(i + "号是周 " + dayOfWeek.getValue());
            int weekValue = dayOfWeek.getValue();

            String weekDayName = "";
            switch (weekValue) {
                case 1:
                    weekDayName = "周一";
                    break;
                case 2:
                    weekDayName = "周二";
                    break;
                case 3:
                    weekDayName = "周三";
                    break;
                case 4:
                    weekDayName = "周四";
                    break;
                case 5:
                    weekDayName = "周五";
                    break;
                case 6:
                    weekDayName = "周六";
                    break;
                case 7:
                    weekDayName = "周日";
                    break;
            }


            String changeType = "" ;
            if(holidayMap.containsKey(currentDate.toString())){
                changeType = holidayMap.get(currentDate.toString());
            }
            Map<String,String> weekMap2 = new HashMap<String,String>();
            weekMap2.put("weekname", weekDayName);
            String changeTypename= "" ;
            if("1".equals(changeType)){ //1-公众假日 2-调配工作日 3-调配休息日
                changeTypename += "[公众假日]";
            }else if("2".equals(changeType)){
                changeTypename += "[调配工作日]";
            }else if("3".equals(changeType)){
                changeTypename += "[调配休息日]";
            }
            weekMap2.put("changeType", changeTypename);
            weekMap2.put("weekday", i+"");
            weekMap2.put("weekdate", currentDate.toString());
            weekList.add(weekMap2);


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

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

    List<Map<String,Object>> dt1DataList = new ArrayList<Map<String,Object>>();
    for(int i=0;i<hrmList.size();i++){
        Map<String,String> hrmMap = hrmList.get(i);
        String ry = hrmMap.get("id");
        String lastname = hrmMap.get("lastname");

        Map<String,Object> dt1DataMap = new HashMap<String,Object>();
        Map<String,Object> ryMap = getDt1UserMap(ry,lastname);
        dt1DataMap.put("ry",ryMap);

        List<Map<String,Object>> scheduleList = queryShiftScheduleByUser(pbyf,activeGroupId,ry);

        dt1DataMap.put("schedule",scheduleList);

        List<String> restList = getSchedulingRestData();
        Map<String,String> countMap = queryCountWorkTime(restList,daysList,weekMap,scheduleList);
        dt1DataMap.put("count",countMap);

        dt1DataList.add(dt1DataMap);
    }
//    out.println("dt1DataList"+ JSON.toJSON(dt1DataList)+"</br>");


    List<Map<String,String>> resultList = queryScheduleStatusByDay(daysList,holidayMap,yjl,workSchedule,hrmList,activeGroupId);

//    out.println("resultList"+ JSON.toJSON(resultList)+"</br>");

    Map<String,Object> valueMap = getMainUserDate(hrmList);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("data",valueMap);
    jsonObject.put("dt1day",resultList);
    jsonObject.put("dt1user",dt1DataList);
    jsonObject.put("days",daysInMonth);
    jsonObject.put("head",weekList);
%>

<%=jsonObject.toJSONString() %>

<%!
    /***
     *
     * @param hrmList
     * @return
     */
    public Map<String,Object> getMainUserDate(List<Map<String,String>> hrmList){
        String userids = "";
        List<Map<String,String>> specialobjList = new ArrayList<Map<String,String>>();
        for(int i=0;i<hrmList.size();i++){
            Map<String,String> hrmMap = hrmList.get(i);
            String userid = Util.null2String(hrmMap.get("id"));
            String lastname = Util.null2String(hrmMap.get("lastname"));
            userids += StringUtils.isBlank(userids) ? userid : ","+userid ;

            Map<String,String> specialobjMap = new HashMap<String,String>();
            specialobjMap.put("id",userid);
            specialobjMap.put("name",lastname);
            specialobjList.add(specialobjMap);
        }

        Map<String,Object> valueMap = new HashMap<String,Object>();
        valueMap.put("value",userids);
        valueMap.put("specialobj",specialobjList);
        return valueMap;
    }

    /***
     *
     * @param hrmList
     * @return
     */
    public List<Map<String,Object>> getDt1UserDate(List<Map<String,String>> hrmList){
        List<Map<String,Object>> dt1List = new ArrayList<Map<String,Object>>();
        for(int i=0;i<hrmList.size();i++){
            Map<String,String> hrmMap = hrmList.get(i);

            String userid = Util.null2String(hrmMap.get("id"));
            String lastname = Util.null2String(hrmMap.get("lastname"));

            Map<String,Object> dt1Map = new HashMap<String,Object>();
            dt1Map.put("id",userid);
            dt1Map.put("name",lastname);

            List<Map<String,String>> specialobjList2 = new ArrayList<Map<String,String>>();
            Map<String,String> specialobjMap2 = new HashMap<String,String>();
            specialobjMap2.put("id",userid);
            specialobjMap2.put("name",lastname);
            specialobjList2.add(specialobjMap2);

            Map<String,Object> valueMap2 = new HashMap<String,Object>();
            valueMap2.put("value",userid);
            valueMap2.put("specialobj",specialobjList2);
            dt1Map.put("value",valueMap2);

            dt1List.add(dt1Map);
        }
        return dt1List;
    }





    public String getWeekTypeByDate(String pbrq,String userid,String activeGroupId){

        String dateType = "0";
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate currentDate = LocalDate.parse(pbrq, df);

        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        int weekValue = dayOfWeek.getValue();

        LocalDate lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
        LocalDate startDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth()); // 获取本月最后一天
        String monthStartDate = startDayOfMonth.toString();
        String monthEndDate = lastDayOfMonth.toString();

        Map<String,String> holidayMap = getHolidayByGroupId(monthStartDate,monthEndDate,activeGroupId);

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

        if("1".equals(changeType) || "3".equals(changeType)){
            dateType = "1";
        }else if(weekValue == 6 || weekValue  == 7){
            dateType = "1";
        }
        return dateType;
    }

    /***
     *
     * @param monthStartDate
     * @param monthEndDate
     * @return
     */
    public Map<String,String> getHolidayByGroupId(String monthStartDate,String monthEndDate,String activeGroupId){

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

        try {
            if(StringUtils.isNotBlank(monthStartDate) && StringUtils.isNotBlank(monthEndDate)){

                String fixedScheduleGroupId = "5";

                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"));
//                        String changeTypename = "" ;
//                        if("1".equals(changeType)){ //1-公众假日 2-调配工作日 3-调配休息日
//                            changeTypename += "公众假日";
//                        }else if("2".equals(changeType)){
//                            changeTypename += "调配工作日";
//                        }else if("3".equals(changeType)){
//                            changeTypename += "调配休息日";
//                        }
                        holidayMap.put(holidayDate,changeType);

//                        if(weekMap.containsKey(holidayDate)){
//                            String holidayDate_new = weekMap.get(holidayDate);
//                            if("1".equals(changeType)){ //1-公众假日 2-调配工作日 3-调配休息日
//                                holidayDate_new += "[公众假日]";
//                            }else if("1".equals(changeType)){
//                                holidayDate_new += "[调配工作日]";
//                            }else if("2".equals(changeType)){
//                                holidayDate_new += "[调配休息日]";
//                            }
//                            weekMap.put(holidayDate,holidayDate_new);
//                        }
                    }
                }
            }
        }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 static List<Map<String,String>> queryListBySql(String sql){
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        try{
            if(StringUtils.isNotBlank(sql)){
                Map<String,String> map = new HashMap<String,String>();
                rs.executeQuery(sql);
                String[] column = rs.getColumnName();
                while (rs.next()){
                    map = new HashMap<String,String>();
                    for(int i=0;i<column.length;i++){
                        String value = rs.getString(column[i]);
                        map.put(column[i],value);
                    }
                    if(!map.isEmpty() && map.size()>0){
                        list.add(map);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("queryListBySql-e:"+e);
        }
        return list;
    }

    /***
     *
     * @return
     */
    public Map<String,Object> getDt1UserMap(String ry,String lastname){
        Map<String,Object> valueMap = new HashMap<String,Object>();
        if(StringUtils.isNotBlank(ry)){
            List<Map<String,String>> specialobjList = new ArrayList<Map<String,String>>();
            Map<String,String> specialobjMap = new HashMap<String,String>();
            specialobjMap.put("id",ry);
            specialobjMap.put("name",lastname);
            specialobjList.add(specialobjMap);
            valueMap.put("id",ry);
            valueMap.put("name",lastname);
            valueMap.put("specialobj",specialobjList);
        }

        return valueMap;
    }


    /***
     *
     * @param pbyf
     * @param groupid
     * @param resourceid
     * @return
     */
    public List<Map<String,Object>> queryShiftScheduleByUser(String pbyf,String groupid,String resourceid){
        BaseBean bb = new BaseBean();
        List<Map<String,Object>> scheduleList = new ArrayList<Map<String,Object>>();
        try{
            List<Map<String,String>> sqlList = new ArrayList<Map<String,String>>();
            if(StringUtils.isNotBlank(pbyf) && StringUtils.isNotBlank(resourceid)){
                String sql =" select t.serialid,k.serial,t.resourceid,t.kqdate\n" +
                            " from kq_shiftschedule t\n" +
                            " inner join kq_ShiftManagement k on k.id = t.serialid\n" +
                            " where left(t.kqdate,7)='"+pbyf+"' \n" +
                            " and t.groupid="+groupid+" and (t.isDelete is null or t.isDelete = 0)\n" +
                            " and resourceid = " + resourceid +
                            " order by kqdate ";
                bb.writeLog("sql:"+sql);
                sqlList = queryListBySql(sql);
            }

            for(int i=0;i<sqlList.size();i++){
                Map<String,String> map = sqlList.get(i);

                String serialid = Util.null2String(map.get("serialid"));
                String name = Util.null2String(map.get("serial"));
                String kqdate = Util.null2String(map.get("kqdate"));

                String xh = "";
                if(StringUtils.isNotBlank(kqdate) && kqdate.length() == 10){
                    xh = kqdate.substring(8);
                    if(StringUtils.isNotBlank(xh)){
                        if(xh.startsWith("0")){
                            xh = xh.substring(1);
                        }
                    }
                }

                if(StringUtils.isNotBlank(xh)){
                    List<Map<String,String>> specialobjList = new ArrayList<Map<String,String>>();
                    Map<String,String> specialobjMap = new HashMap<String,String>();
                    specialobjMap.put("id",serialid);
                    specialobjMap.put("name",name);
                    specialobjList.add(specialobjMap);

                    Map<String,Object> valueMap = new HashMap<String,Object>();
                    valueMap.put("serialid",serialid);
                    valueMap.put("kqdate",kqdate);
                    valueMap.put("xh",xh);



                    valueMap.put("specialobj",specialobjList);

                    scheduleList.add(valueMap);
                }
            }

        }catch (Exception e){

        }
        return scheduleList;
    }


    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;
    }

    /***
     *
     * @param restList
     * @param daysList
     * @param weekMap
     * @param serialList
     */
    public Map<String,String> queryCountWorkTime(List<String> restList,List<String> daysList,Map<String,String> weekMap,List<Map<String,Object>> serialList ){

        BaseBean bb = new BaseBean();
        Map<String,String> countMap = new HashMap<>();
        String worktime = "0";
        String totalworktime = "0";
        int restcount = 0;
        int weekrestcount = 0;

        RecordSet rs = new RecordSet();
        try{
            String sql = "";
            for (int i = 0; i < serialList.size(); i++) {
                Map<String,Object> serialMap = serialList.get(i);
                String kqdate = Util.null2String(serialMap.get("kqdate"));
                String serialid = Util.null2String(serialMap.get("serialid"));
                if (daysList.contains(kqdate)) {
                    if (StringUtils.isNotBlank(serialid)) {
                        if (restList.contains(serialid)) {
                            restcount++;
                        }

                        if(!restList.contains(serialid)){
                            String sql2 = " select try_convert(int,worktime) as worktime from kq_ShiftManagement where id ="+serialid+" and (is_rest is null or is_rest = 0) " ;
                            sql += StringUtils.isBlank(sql) ?  sql2 : " union all \n"+sql2 ;
                        }
                    }

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

            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"));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("e："+e);
        }

        countMap.put("worktime",worktime);
        countMap.put("totalworktime",totalworktime);
        countMap.put("restcount",restcount+"");
        countMap.put("weekrestcount",weekrestcount+"");

        return countMap;
    }

    /***
     *
     * @param daysList
     * @param holidayMap
     * @param yjl
     * @param workSchedule
     * @param hrmList
     * @param groupid
     * @return
     */
    public List<Map<String,String>> queryScheduleStatusByDay(List<String> daysList,Map<String,String> holidayMap,String yjl,String[] workSchedule,List<Map<String,String>> hrmList,String groupid){

        BaseBean bb = new BaseBean();
        List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        RecordSet rs = new RecordSet();

        try{
            List<Map<String,String>> workScheduleList = new ArrayList<Map<String,String>>();
            Map<String,String> workScheduleMap = null;
            for(int k=0;k<workSchedule.length;k++){
                if(workSchedule[k].indexOf("-")>0){
                    String[] schedule = workSchedule[k].split("-");
                    String scheduleStartTime = schedule[0];
                    String scheduleEndTime = schedule[1];
                    if(StringUtils.isNotBlank(scheduleStartTime) && StringUtils.isNotBlank(scheduleEndTime)){
                        workScheduleMap = new HashMap<String,String>();
                        workScheduleMap.put("start",scheduleStartTime);
                        workScheduleMap.put("end",scheduleEndTime);
                        workScheduleList.add(workScheduleMap);
                    }
                }
            }

            String resourceids = "";
            for(int i=0;i<hrmList.size();i++) {
                Map<String, String> hrmMap = hrmList.get(i);
                String userid = Util.null2String(hrmMap.get("id"));
                resourceids += StringUtils.isBlank(resourceids) ? userid : ","+userid ;
            }

            for(String pbrq:daysList){
                String dateType = "0";
                if(StringUtils.isNotBlank(pbrq)){
                    LocalDate currentDate = LocalDate.parse(pbrq, df);
                    DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
                    int weekValue = dayOfWeek.getValue();

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

                    if("1".equals(changeType) || "3".equals(changeType)){
                        dateType = "1";
                    }else if(weekValue == 6 || weekValue  == 7){
                        dateType = "1";
                    }
                }

                Map<String,Integer> defaultScheduleMap = new HashMap<String,Integer>();
                if(StringUtils.isNotBlank(yjl)){
                    String sql = " select dysjd,pzrs from uf_pbjcsj where yjl = ? and pblx = ?" ;
                    rs.executeQuery(sql,new Object[]{yjl,dateType});
                    while (rs.next()){
                        int dysd = Util.getIntValue(Util.null2String(rs.getString("dysjd")));
                        int pzrs = Util.getIntValue(Util.null2String(rs.getString("pzrs")));

                        String sjd = "";
                        if(dysd < workSchedule.length){
                            sjd = workSchedule[dysd];
                            if(StringUtils.isNotBlank(sjd)){
                                defaultScheduleMap.put(sjd,pzrs);
                            }
                        }
                    }
                }

                List<Map<String,String>> sqlList = new ArrayList<Map<String,String>>();
                if(StringUtils.isNotBlank(resourceids) && StringUtils.isNotBlank(pbrq)){

                    String sql =" select t.serialid,t.resourceid,t.kqdate \n" +
                            " from kq_shiftschedule t\n" +
                            " where t.kqdate='"+pbrq+"' \n" +
                            " and t.groupid="+groupid+" and (t.isDelete is null or t.isDelete = 0)\n" +
                            " and resourceid in( " + resourceids + ") "+
                            " order by kqdate ";
                    sqlList = queryListBySql(sql);
                }

                Map<String,String> resultMap = queryScheduleStatusByUser(sqlList,workScheduleList,defaultScheduleMap,pbrq);
                resultList.add(resultMap);
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("e:"+e);
        }

        return resultList;
    }

    /***
     *
     * @param sqlList
     * @param workScheduleList
     * @param defaultScheduleMap
     * @param kqdate
     * @return
     */
    public Map<String,String> queryScheduleStatusByUser(List<Map<String,String>> sqlList,List<Map<String,String>> workScheduleList,Map<String,Integer> defaultScheduleMap,String kqdate){

        RecordSet rs = new RecordSet();

        Map<String,Map<String,String>> userScheduleDayMap = new HashMap<String,Map<String,String>>();
        Map<String,Integer> userScheduleMap = new HashMap<String,Integer>();
        Map<String,Integer> necessaryMap = new HashMap<String,Integer>();
        String yxrys = "" ;
        for(int i=0;i<sqlList.size();i++){
            Map<String,String> sqlMap = sqlList.get(i);
            String resourceid = Util.null2String(sqlMap.get("resourceid"));
            yxrys += StringUtils.isBlank(yxrys) ? resourceid :","+resourceid ;
        }
        if(StringUtils.isNotBlank(yxrys)) {
            List<String> userList = new ArrayList<String>();
            String sql =" select h.id \n" +
                        " from hrmresource h \n" +
                        " inner join hrmjobtitles k on k.id = h.jobtitle\n" +
                        " where h.id in("+yxrys+")\n" +
                        " and k.jobtitlename in('店长','验光师')\n" +
                        " and h.status in(0,1,2,3,4)\n" +
                        " union \n" +
                        " select h.id \n" +
                        " from hrmresource h \n" +
                        " inner join cus_fielddata k on k.id = h.id\n" +
                        " where k.field39 = 2 \n" +
                        " and k.scopeid=3 \n" +
                        " and k.scope='HrmCustomFieldByInfoType' " +
                        " and h.id in("+yxrys+") and h.status in(0,1,2,3,4) " +
                        " union " +
                        " select h.id\n" +
                        " from hrmresource h \n" +
                        " inner join cus_fielddata k on k.id = h.id \n" +
                        " where k.scopeid=-1 " +
                        " and k.scope='HrmCustomFieldByInfoType'\n" +
                        " and substring(k.field1,charindex('_',k.field1)+1,len(k.field1)) in(select id from uf_gwjbsjb where jbmc in('配镜一级','配镜二级','配镜三级','配镜四级','配镜五级')) and charindex('_', k.field1) > 0 \n" +
                        " and h.status in(0,1,2,3,4) "+
                        " and h.id in("+yxrys+") ";

            rs.executeQuery(sql);
            while (rs.next()){
                String id = Util.null2String(rs.getString("id"));
                userList.add(id);
            }

            for(int i = 0;i<sqlList.size();i++){
                Map<String,String> sqlMap =  sqlList.get(i);
                String pbry = sqlMap.get("resourceid");
                String serialid = sqlMap.get("serialid");
                String startTime = "";
                String endTime = "";

                sql = " select times,onoffworktype from kq_ShiftOnOffWorkSections where serialid = ? and (isdelete = 0 or isdelete is null) ";
                rs.executeQuery(sql,new Object[]{serialid});
                while(rs.next()){
                    String onoffworktype = Util.null2String(rs.getString("onoffworktype"));
                    if("start".equals(onoffworktype)){
                        startTime = Util.null2String(rs.getString("times"));
                    }else if("end".equals(onoffworktype)){
                        endTime = Util.null2String(rs.getString("times"));
                    }
                }

                Map<String,String> userSchedule_Map = new HashMap<String,String>();
                if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
                    userSchedule_Map.put("startTime",startTime);
                    userSchedule_Map.put("endTime",endTime);

                    for(int k=0;k<workScheduleList.size();k++){
                        Map<String,String> workSchedule_Map = workScheduleList.get(k);
                        String scheduleStartTime = workSchedule_Map.get("start");
                        String scheduleEndTime = workSchedule_Map.get("end");
                        if(StringUtils.isNotBlank(scheduleStartTime) && StringUtils.isNotBlank(scheduleEndTime)){
                            if(startTime.compareTo(scheduleStartTime) <=0 && endTime.compareTo(scheduleEndTime) >=0){

                                String defWorkSchedule = scheduleStartTime+"-"+scheduleEndTime ;
                                if(userScheduleMap.containsKey(defWorkSchedule)){
                                    int count = userScheduleMap.get(defWorkSchedule);
                                    count++;
                                    userScheduleMap.put(defWorkSchedule,count);
                                }else{
                                    userScheduleMap.put(defWorkSchedule,1);
                                }

                                if(userList.contains(pbry)){
                                    necessaryMap.put(defWorkSchedule,1);
                                }
                            }
                        }
                    }
                }
                userScheduleDayMap.put(pbry,userSchedule_Map);
            }
        }

        int defaultcount = 0;
        int datacount = 0;
        Iterator<Map.Entry<String, Integer>> iterator = defaultScheduleMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            int value =entry.getValue();
            String key = entry.getKey();
            if(userScheduleMap.containsKey(key)){
                int useValue = userScheduleMap.get(key);
                if(useValue < value){
                    datacount++;
                }
            }else{
                datacount++;
            }
            defaultcount++;
        }


        String xh = "";
        if(StringUtils.isNotBlank(kqdate) && kqdate.length() == 10){
            xh = kqdate.substring(8);
            if(StringUtils.isNotBlank(xh)){
                if(xh.startsWith("0")){
                    xh = xh.substring(1);
                }
            }
        }
        Map<String,String> resultMap = new HashMap<>();
        String status = "";
        if(defaultcount >0 && datacount == 0){
            if(necessaryMap.size() == 4){
                status = "0";
            }else{
                status = "1";
            }
        }
        resultMap.put("kqdate",kqdate);
        resultMap.put("status",status);
        resultMap.put("xh",xh);

        return resultMap;
    }

%>


