<%@ 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<>();
        DepartmentComInfo comInfo = new DepartmentComInfo();
        LinkedList<BrowserParam> browser = new LinkedList<>();
        List<Integer> deptList = new ArrayList<>();

        if(StringUtils.isNotEmpty(departmentIds)) {
            deptList = Arrays.stream(departmentIds.split(",")).map(Integer::parseInt).collect(Collectors.toList());

        }else {
//            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 from hrmdepartment where canceled = 0 or canceled is null and subcompanyid1="+subcompanyid1);
            while (rs.next()) {
                deptList.add(Util.getIntValue(rs.getString("id")));
            }

        }

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

        deptList.forEach(dept -> {
            try {
                String departmentName = comInfo.getDepartmentName(String.valueOf(dept));
                legendDataFirst.add(departmentName);
                browser.add(BrowserParam.builder().id(dept).name(departmentName).build());
            } 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 < 3; 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;
                    default:
                        break;

                }
            }

        });

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

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

        OptionVO optionVo = OptionVO.builder().titleText("年度离职率统计")
                .legendDataFirst(legendDataFirst)
                .yMin(0)
                .yMax(roundedMax)
                .yInterval(ceil)
                .barSeriesData(barSeriesData)
                .barSeriesDataTwo(barSeriesDataTwo)
                .barSeriesDataThree(barSeriesDataThree)
                .build();
        jsonObject.put("data",optionVo);
        jsonObject.put("replaceDatas",browser);
        return jsonObject;
    }


%>
<%!
    private Integer calculateLeave(Integer id,String startMonth,String endMonth,String subcompanyid1) {
        RecordSet rs = new RecordSet();

        String where  = " and (s.belongto is null or s.belongto = -1 ) and s.subcompanyid1 = "+subcompanyid1;

        String sql =" select t.departmentname, t.id," +
                    "       case when a.sum IS NULL THEN 0  ELSE a.sum END AS num " +
                    "       from hrmdepartment t \n" +
                    "       left join (select s.departmentid,count(1) as sum from  lizhi_view h left join hrmresource s on h.resourceid = s.id where 1 = 1 "+ where +" and changedate >= ? and changedate <= ? group by s.departmentid ) a on t.id = a.departmentid " +
                    " where t.id = ? and (t.canceled = 0 or t.canceled is null)";

        rs.executeQuery(sql,startMonth,endMonth,id);
        rs.next();
        int countBydeptId = countBydeptId(id, endMonth);
        return countBydeptId == 0 ? 0 : ((Util.getIntValue(rs.getString("num")) * 100) / countBydeptId);
    }
%>
<%!
    /**
     * 根据日期部门人数统计
     * @param  departmentId
     * @return
     */
    private int countBydeptId(Integer 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 = ? and status < 4 and companystartdate <= ? " + where ,departmentId,endMonth);
        rs.next();
        return Util.getIntValue(rs.getString("sum"));
    }
%>


