<%@ 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="weaver.general.BaseBean" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="weaver.hrm.resource.ResourceComInfo" %>
<%@ page import="com.engine.kq.service.KQShiftScheduleService" %>
<%@ page import="com.engine.common.util.ServiceUtil" %>
<%@ page import="com.engine.kq.service.impl.KQShiftScheduleServiceImpl" %>
<%@ page import="com.engine.common.util.ParamUtil" %>
<%@ 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" %>
<%
    ResourceComInfo resourceComInfo = new ResourceComInfo();
    User user = HrmUserVarify.getUser(request, response);
    if(user==null) {
        response.sendRedirect("/login/Login.jsp");
        return;
    }
    out.println("333333</br>");

    String requestid = request.getParameter("requestid");
    out.println("requestid:"+requestid+"</br>");
    String workflowid = request.getParameter("workflowid");
    out.println("workflowid:"+workflowid+"</br>");
    String billtable = getFormtableByRequestId(requestid);

    out.println("billtable:"+billtable+"</br>");

    RecordSet rs = new RecordSet();
        String mainid = "";
        String cjr = "";
        String pbyf = "";
        String cjrbm = "";
        String sql = " select id,cjr,pbyf,cjrbm from " + billtable + " where requestid=" + requestid;
    out.println("sql:"+sql+"</br>");
        rs.execute(sql);
        if (rs.next()) {
            mainid = Util.null2String(rs.getString("id"));
            cjr = Util.null2String(rs.getString("cjr"));
            pbyf = Util.null2String(rs.getString("pbyf"));
            cjrbm = Util.null2String(rs.getString("cjrbm"));
        }
    out.println("mainid:"+mainid+"</br>");
    out.println("pbyf:"+pbyf+"</br>");
    out.println("cjrbm:"+cjrbm+"</br>");

        sql = " select t.requestid,r.currentnodetype,r.requestname " +
                " from " + billtable + " t " +
                " inner join workflow_requestbase r on r.requestid = t.requestid " +
                " where t.pbyf ='" + pbyf + "' " +
                " and t.cjrbm ='" + cjrbm + "' " +
                " and r.currentnodetype in(1,2,3) " +
                " and r.workflowid = " + workflowid +
                " and t.requestid <> " + requestid;

    out.println("sql:"+sql+"</br>");

        List<Map<String, String>> requestList = queryListBySql(sql);
    out.println("requestList:"+requestList.size()+"</br>");
        if (!requestList.isEmpty() && requestList.size() > 0) {
            Map<String, String> requestMap = requestList.get(0);
            String requestname = requestMap.get("requestname");
            String currentnodetype = requestMap.get("currentnodetype");
            String requesttypename = "";
            if ("1".equals(currentnodetype) || "2".equals(currentnodetype)) {
                requesttypename = "正在审批";
            } else if ("3".equals(currentnodetype)) {
                requesttypename = "已归档";
            }
            out.println("已存在" + requesttypename + "流程:" + requestname + "");
        } else {
            List<Map<String, String>> scheduleList = new ArrayList<Map<String, String>>();
            String userids = "";
            sql = " select yg from " + billtable + "_dt1 where mainid=" + mainid;
            out.println("sql:"+sql+"</br>");

            List<Map<String, String>> dt1List2 = queryListBySql(sql);
            for (int i = 0; i < dt1List2.size(); i++) {
                Map<String, String> dt1Map = dt1List2.get(i);
                String resourceid = Util.null2String(dt1Map.get("yg"));
                userids += StringUtils.isBlank(userids) ? resourceid : "," + resourceid;
            }
            if (StringUtils.isNotBlank(userids)) {
                sql = " select kqdate,resourceid,serialid,groupid from kq_shiftschedule where left(kqdate,7) = '" + pbyf + "' and resourceid in(" + userids + ") and (isdelete is null or isdelete = 0)";
                out.println("sql:"+sql+"</br>");
                scheduleList = queryListBySql(sql);
            }
            if (!scheduleList.isEmpty() && scheduleList.size() > 0) {
                String lastnames = "";
                for(int i=0;i<scheduleList.size();i++){
                    Map<String, String> scheduleMap = scheduleList.get(i);
                    if(i<2){
                        String resourceid = scheduleMap.get("resourceid");
                        if(StringUtils.isNotBlank(resourceid)){
                            String lastname = resourceComInfo.getLastname(resourceid);
                            lastnames += StringUtils.isBlank(lastnames) ? lastname : ","+lastname;
                        }
                    }
                }
                out.println(lastnames+"等已存在"+pbyf+"的排班数据,无法新增排班");
            } else {
                int daysInMonth = 0;
                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();
                    daysInMonth = date.lengthOfMonth(); // 获取本月有多少天
                }

                if (StringUtils.isNotBlank(mainid)) {

                    String groupid = getUserActiveGroupId(user.getUID()+"");
                    JSONObject datasJSON = new JSONObject();
                    JSONArray datasArray = new JSONArray();
                    sql = " select * from " + billtable + "_dt1 where mainid=" + mainid;
                    List<Map<String, String>> dt1List = queryListBySql(sql);
                    for (int i = 0; i < dt1List.size(); i++) {
                        Map<String, String> dt1Map = dt1List.get(i);
                        String resourceid = Util.null2String(dt1Map.get("yg"));
                        if(StringUtils.isNotBlank(resourceid)){

                            JSONArray kqdata = new JSONArray();
                            JSONObject userJSON = new JSONObject();
                            userJSON.put("id","");
                            String loginid = resourceComInfo.getLoginID(resourceid);
                            userJSON.put("serialid",loginid);
                            userJSON.put("oldValue",loginid);
                            userJSON.put("date","workcode");
                            kqdata.add(userJSON);
                            for (int k = 1; k <= daysInMonth; k++) {
                                String bc = Util.null2String(dt1Map.get("bc" + k));
                                if(StringUtils.isNotBlank(bc)){
                                    JSONObject bcJSON = new JSONObject();
                                    bcJSON.put("id", "");
                                    bcJSON.put("serialid", bc);
                                    if (k < 10) {
                                        bcJSON.put("date", pbyf + "-0" + k);
                                    } else {
                                        bcJSON.put("date", pbyf + "-" + k);
                                    }
                                    kqdata.add(bcJSON);
                                }
                            }
                            JSONObject dataJSON = new JSONObject();
                            dataJSON.put("resourceid", resourceid);
                            dataJSON.put("kqdata", kqdata);
                            datasArray.add(dataJSON);
                        }
                    }
                    datasJSON.put("datas", datasArray);
                    datasJSON.put("groupId", groupid);
                    out.println("datasJSON:" + datasJSON.toJSONString() + "</br>");

                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("data",datasJSON.toJSONString());
                    Map<String, Object> apidatas = getService(user).save(params, user);

                    out.println("apidatas:" + JSONObject.toJSONString(apidatas)+ "</br>");
                }
            }
        }

%>

<%!
    /**
     *
     * @param requestid
     * @return
     */
    public String getFormtableByRequestId(String requestid){
        String formtable = "" ;
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        try{
            if(StringUtils.isNotBlank(requestid)){
                String sql =" select abs(formid) as formid from workflow_base t \n" +
                            " inner join workflow_requestbase h on h.workflowid = t.id \n" +
                            " where h.requestid=  "+requestid ;
                bb.writeLog("sql2:"+sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    String formid = Util.null2String(rs.getString("formid"));
                    if(StringUtils.isNotBlank(formid)){
                        formtable = "formtable_main_"+formid ;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("getFormtableByRequestId:"+e);
        }
        return formtable;
    }


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

<%!

    private KQShiftScheduleService getService(User user) {
        return (KQShiftScheduleService) ServiceUtil.getService(KQShiftScheduleServiceImpl.class, user);
    }


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

%>