<%@ 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.alibaba.fastjson.JSONArray" %>
<%@ 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 ry = request.getParameter("ry");
    String pbyf = request.getParameter("pbyf");
    String bp = request.getParameter("bp");
    String activeGroupId = getUserActiveGroupId(userid+"");
    List<Map<String,String>> scheduleList = queryShiftScheduleByUser(pbyf,activeGroupId,ry);


    String pbdata = request.getParameter("pbdata");
    String pbrq = request.getParameter("pbrq");
    String yjl = request.getParameter("yjl");

    String dateType = "0";
    if(StringUtils.isNotBlank(pbrq)){
        dateType = getWeekTypeByDate(pbrq,userid+"");
    }

    Map<String,Integer> defaultScheduleMap = new HashMap<String,Integer>();
    if(StringUtils.isNotBlank(yjl)){
        String sql = " select dysjd,pzrs from uf_pbjcsj where bp = ? and pblx = ?" ;
        rs.executeQuery(sql,new Object[]{bp,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>> workScheduleList = new ArrayList<Map<String,String>>();
    Map<String,String> workScheduleMap = null;
    for(int k=0;k<workSchedule.length;k++){
        if(k==0){
            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","");
                    workScheduleMap.put("end",scheduleEndTime);
                    workScheduleList.add(workScheduleMap);
                }
            }
        }else if(k==(workSchedule.length-1)){
            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","");
                    workScheduleList.add(workScheduleMap);
                }
            }
        }else{
            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);
                }
            }
        }
    }

    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>();
    if(StringUtils.isNotBlank(pbdata)) {
        JSONArray jsonArray = JSONArray.parseArray(pbdata);

        String yxrys = "" ;
        for(int i = 0;i<jsonArray.size();i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String pbry = jsonObject.getString("userid");
            yxrys+= StringUtils.isBlank(yxrys) ? pbry : ","+pbry ;
        }
        out.println("yxrys:"+yxrys+"</br>");
        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+") ";

        out.println("sql:"+sql+"</br>");
        rs.executeQuery(sql);
        while (rs.next()){
            String id = Util.null2String(rs.getString("id"));
            out.println("id:"+id+"</br>");
            userList.add(id);
        }

        for(int i = 0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String pbry = jsonObject.getString("userid");

            String serialid = jsonObject.getString("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);
                            }
                        }
                    }else{
                        if(StringUtils.isNotBlank(scheduleStartTime)){

                            if(endTime.compareTo(scheduleStartTime) >=0 ){
                                String define_scheduleEndTime = "21:30";
                                String defWorkSchedule = scheduleStartTime+"-"+define_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);
                                }
                            }
                        }else if(StringUtils.isNotBlank(scheduleEndTime)){

                            if(startTime.compareTo(scheduleEndTime) <=0){
                                String define_scheduleStartTime = "09:00";
                                String defWorkSchedule = define_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++;
    }

    out.println("necessaryMap:"+necessaryMap.size());

    JSONObject jsonObject = new JSONObject();
    if(defaultcount >0 && datacount == 0){
        if(necessaryMap.size() == 4){
            jsonObject.put("pbcode","1");
        }else{
            jsonObject.put("pbcode","2");
        }
    }else{
        jsonObject.put("pbcode","0");
    }

    jsonObject.put("pbinfo",userScheduleDayMap);
%>

<%=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 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(userid,monthStartDate,monthEndDate);

        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 userid
     * @param monthStartDate
     * @param monthEndDate
     * @return
     */
    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);
//                bb.writeLog("activeGroupId:"+activeGroupId);

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


    /***
     *
     * @param pbyf
     * @param groupid
     * @param resourceid
     * @return
     */
    public List<Map<String,String>> queryShiftScheduleByUser(String pbyf,String groupid,String resourceid){
        BaseBean bb = new BaseBean();
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        try{
            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);
                list = queryListBySql(sql);
            }

            List<Map<String,Object>> scheduleList = new ArrayList<Map<String,Object>>();
            for(int i=0;i<list.size();i++){
                Map<String,String> map = list.get(i);

                String id = 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)){

                }


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

                List<Map<String,String>> specialobjList = new ArrayList<Map<String,String>>();
                Map<String,String> specialobjMap = new HashMap<String,String>();
                specialobjMap.put("id",id);
                specialobjMap.put("name",name);
                specialobjList.add(specialobjMap);

                Map<String,Object> valueMap2 = new HashMap<String,Object>();
                valueMap2.put("value",id);
                valueMap2.put("specialobj",specialobjList);
                scheduleMap.put("value",valueMap2);
                scheduleList.add(scheduleMap);
            }

        }catch (Exception e){

        }
        return list;
    }




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

%>


