<%@ page import="weaver.general.*" %>
<%@page import="weaver.conn.RecordSet"%>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="java.util.*" %>
<%@ page import="com.engine.matfron.entity.OptionVO" %>
<%@ page import="com.engine.matfron.util.CommonUtils" %>
<%@ page import="com.engine.matfron.util.CommonDateUtil" %>
<%@ page import="java.time.YearMonth" %>
<%@ page import="com.engine.matfron.entity.BrowserParam" %>
<%@ page import="org.apache.commons.lang.StringUtils" %>
<%@ page import="weaver.hrm.company.DepartmentComInfo" %>
<%@ page import="java.util.stream.Collectors" %>
<%@ page import="com.engine.matfron.exception.CustomizeRunTimeException" %>
<%@ page import="java.time.LocalDate" %>
<jsp:useBean id="ResourceComInfo" class="weaver.hrm.resource.ResourceComInfo" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean" scope="page" />
<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<%
    String subcompanyid1 = "62";
    JSONObject jsonObject = new JSONObject();
    String departmentIds = Util.null2String(request.getParameter("departmentIds"));

    jsonObject = getLeaveYear(departmentIds,subcompanyid1);

%>
<%=jsonObject.toString()  %>

<%!

    public JSONObject getLeaveYear(String departmentIds,String subcompanyid1) {
        JSONObject jsonObject = new JSONObject();
        RecordSet rs = new RecordSet();
        LinkedList<String> legendDataFirst = new LinkedList<>();
        LinkedList<Integer> barSeriesData = new LinkedList<>();
        LinkedList<Integer> barSeriesDataTwo = new LinkedList<>();
        LinkedList<Integer> barSeriesDataThree = new LinkedList<>();
        LinkedList<Integer> barSeriesDataFour = new LinkedList<>();
        LinkedList<Integer> barSeriesDataFire = new LinkedList<>();
        LinkedList<Integer> barSeriesDataSix= new LinkedList<>();
        LinkedList<Integer> barSeriesDataSev= new LinkedList<>();
        LinkedList<Integer> barSeriesDataElt= new LinkedList<>();
        LinkedList<Integer> barSeriesDataNi= new LinkedList<>();
        LinkedList<Integer> barSeriesDataTe= new LinkedList<>();
        LinkedList<Integer> barSeriesDataEl= new LinkedList<>();
        DepartmentComInfo comInfo = new DepartmentComInfo();
        LinkedList<BrowserParam> browser = new LinkedList<>();
        List<Map> browserList = new ArrayList<>();

        List<Integer> deptList = new ArrayList<>();

        Map browserMap = null;
//            rs.executeQuery("select distinct t.id from hrmdepartment t \n" +
//                    " left join hrmresource h on t.id = h.departmentid\n" +
//                    " left join hrmstatushistory s on h.id = s.resourceid where s.type_n = 5 ");
            rs.executeQuery("select id,departmentName from hrmdepartment where supdepid=0 and id!=441 and (canceled = 0 or canceled is null) and subcompanyid1="+subcompanyid1);
            while (rs.next()) {
                browserMap = new HashMap();
                String deptname = Util.null2String(rs.getString("departmentName"));
                deptList.add(Util.getIntValue(rs.getString("id")));
                browserMap.put("id",Util.getIntValue(rs.getString("id")));
                browserMap.put("name",deptname);
                browserList.add(browserMap);
            }

        deptList = deptList.stream().limit(11).collect(Collectors.toList());

        deptList.forEach(dept -> {
            try {
                String departmentName = comInfo.getDepartmentName(String.valueOf(dept));
                legendDataFirst.add(departmentName);

            } catch (Exception e) {
                throw new CustomizeRunTimeException("所选部门不存在");
            }
        });

        List<YearMonth> yearMonths = CommonDateUtil.getYearMonths(LocalDate.now());
        List<Integer> finalDeptList = deptList;
        yearMonths.forEach(yearMonth -> {
            String startMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateStartOfMonth(yearMonth));
            String endMonth = CommonDateUtil.getFormatYear(CommonDateUtil.toDateEndOfMonth(yearMonth));
            for (int i = 0; i < 11; i++) {
                Integer value = calculateLeave(finalDeptList.get(i), startMonth, endMonth,subcompanyid1);
                switch (i) {
                    case 0:
                        barSeriesData.add(value);
                        break;
                    case 1:
                        barSeriesDataTwo.add(value);
                        break;
                    case 2:
                        barSeriesDataThree.add(value);
                        break;
                    case 3:
                        barSeriesDataFour.add(value);
                        break;
                    case 4:
                        barSeriesDataFire.add(value);
                        break;
                    case 5:
                        barSeriesDataSix.add(value);
                        break;
                    case 6:
                        barSeriesDataSev.add(value);
                        break;
                    case 7:
                        barSeriesDataElt.add(value);
                        break;
                    case 8:
                        barSeriesDataNi.add(value);
                        break;
                    case 9:
                        barSeriesDataTe.add(value);
                        break;
                    case 10:
                        barSeriesDataEl.add(value);
                        break;

                }
            }

        });

        LinkedList<Integer> sumData = new LinkedList<>();
        sumData.addAll(barSeriesData);
        sumData.addAll(barSeriesDataTwo);
        sumData.addAll(barSeriesDataThree);

        int max = Collections.max(sumData);
//        max = max < 100 ? max + 20 : 100;
        max = 20;
        int ceil =(int) Math.ceil((double) max / 4);
        int roundedMax = CommonUtils.roundedMax(ceil, 4);

//        {"replaceDatas":[{"id":442,"name":"人力资源部"},{"id":448,"name":"财务部"},{"id":452,"name":"信息技术部"},{"id":453,"name":"商务运营部"},{"id":461,"name":"市场部"},{"id":465,"name":"半导体销售中心"},{"id":478,"name":"自动化销售中心"},{"id":502,"name":"半导体研发工程"},{"id":508,"name":"自动化研发工程"},{"id":520,"name":"制造中心"},{"id":557,"name":"质量部"}],"data":{"barSeriesData":[0,0,0,0,0,0,0,0,0,0,0,0],"barSeriesDataThree":[28,0,0,0,0,0,0,0,0,0,0,0],"barSeriesDataTwo":[0,11,0,0,0,0,0,0,0,0,0,0],"legendDataFirst":["人力资源部","财务部","信息技术部","商务运营部","市场部","半导体销售中心","自动化销售中心","半导体研发工程","自动化研发工程","制造中心","质量部"],"titleText":"年度离职率统计","yInterval":5,"yMax":20,"yMin":0}}
//

//        OptionVO optionVo = OptionVO.builder().titleText("年度离职率统计")
//                .legendDataFirst(legendDataFirst)
//                .yMin(0)
//                .yMax(roundedMax)
//                .yInterval(ceil)
//                .barSeriesData(barSeriesData)
//                .barSeriesDataTwo(barSeriesDataTwo)
//                .barSeriesDataThree(barSeriesDataThree)
////                .barSeriesDataFour(barSeriesDataFour)
////                .barSeriesDataFire(barSeriesDataFire)
////                .barSeriesDataSix(barSeriesDataSix)
////                .barSeriesDataSev(barSeriesDataSev)
////                .barSeriesDataElt(barSeriesDataElt)
////                .barSeriesDataNi(barSeriesDataNi)
////                .barSeriesDataTe(barSeriesDataTe)
////                .barSeriesDataEl(barSeriesDataEl)
//                .build();

        Map data = new HashMap();
        data.put("barSeriesData",barSeriesData);
        data.put("barSeriesDataTwo",barSeriesDataTwo);
        data.put("barSeriesDataThree",barSeriesDataThree);
        data.put("barSeriesDataFour",barSeriesDataFour);
        data.put("barSeriesDataFire",barSeriesDataFire);
        data.put("barSeriesDataSix",barSeriesDataSix);
        data.put("barSeriesDataSev",barSeriesDataSev);
        data.put("barSeriesDataElt",barSeriesDataElt);
        data.put("barSeriesDataNi",barSeriesDataNi);
        data.put("barSeriesDataTe",barSeriesDataTe);
        data.put("barSeriesDataEl",barSeriesDataEl);

        data.put("legendDataFirst",legendDataFirst);
        data.put("titleText","年度离职率统计");
        data.put("yInterval",ceil);
        data.put("yMax",roundedMax);
        data.put("yMin",0);

        Map all = new HashMap();
        all.put("data",data);
        all.put("replaceDatas",browserList);

        jsonObject = (JSONObject)JSONObject.toJSON(all);

        return jsonObject;
    }


%>
<%!
    private Integer calculateLeave(Integer id,String startMonth,String endMonth,String subcompanyid1) {
        RecordSet rs = new RecordSet();
        String departmentIds = getAllDeptIds(id+"");
        String where  = "   (s.belongto is null or s.belongto = -1 ) and s.subcompanyid1 = "+subcompanyid1;

        String sql =  "select count(1) as sum from lizhi_view h  ,hrmresource s where h.resourceid = s.id  and  "+where+" and  h.changedate >= '"+startMonth+"' and h.changedate <= '"+endMonth+"' ";
        if(StringUtils.isNotEmpty(departmentIds)) {
            sql=sql+(" and s.departmentid in ("+departmentIds+")");
        }

        rs.executeQuery(sql);
        rs.next();
        int num = Util.getIntValue(rs.getString("sum"));
        int countBydeptId = countBydeptId(departmentIds, endMonth)+num;
        if(num==0){
            return 0;
        }else{
            if(countBydeptId==0){
                return 0;
            }else {
                return(num * 100 / countBydeptId);
            }
        }
    }


    public String getAllDeptIds(String departmentid){
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        String ids = "" ;
        if(StringUtils.isNotBlank(departmentid)){
            String sql = "   WITH tmp_dept AS (" +
                    "    SELECT id, supdepid, departmentname FROM HrmDepartment WHERE id =" +departmentid+
                    "    UNION ALL " +
                    "    SELECT t.id, t.supdepid, t.departmentname FROM HrmDepartment t INNER JOIN tmp_dept r ON t.supdepid = r.id\n" +
                    "    )" +
                    "    SELECT * FROM tmp_dept";

            bb.writeLog("sql:"+sql);
            rs.executeQuery(sql);
            while (rs.next()){
                ids = ids+Util.null2String(rs.getString("id")) +",";
            }
        }
        if(ids.length()>0){
            ids = ids.substring(0,ids.length()-1);
        }
        bb.writeLog("ids:"+ids);
        return ids;
    }
%>
<%!
    /**
     * 根据日期部门人数统计
     * @param  departmentId
     * @return
     */
    private int countBydeptId(String departmentId,String endMonth) {
        RecordSet rs = new RecordSet();

        String where  = " and (belongto is null or belongto = -1 ) ";

        rs.executeQuery("select count(1) as sum from hrmresource where departmentId in ("+departmentId+") and status < 4 and companystartdate <= '"+endMonth+"'");
        rs.next();
        return Util.getIntValue(rs.getString("sum"));
    }
%>

