<%@ page import="weaver.general.*" %>
<%@page import="weaver.conn.RecordSet"%>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.*" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%
    BaseBean bb = new BaseBean();
    User user = HrmUserVarify.getUser(request , response) ;
    int userid = user.getUID();

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

    List<Map<String,Object>> riskHomeList = new ArrayList<Map<String,Object>>();
    try{
        riskHomeList = getRiskHomeWarning(user,request);
        bb.writeLog("riskHomeList:"+riskHomeList.size());
        dataList.addAll(riskHomeList);
    }catch (Exception e){

    }

    List<Map<String,Object>> contractList = grtContractWarning(userid);
    bb.writeLog("contractList:"+contractList.size());
    dataList.addAll(contractList);
    bb.writeLog("dataList:"+dataList.size());

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("data",dataList);
    jsonObject.put("status", "1");
    jsonObject.put("total", dataList.size());
%>
<%=jsonObject.toString()  %>

<%!
    /**
     *
     * @return
     */
    public List<Map<String,Object>> grtContractWarning(int userid){
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();

        Map<String,Object> dataMap = null;
        String timestrformart = "MM-dd" ;
        SimpleDateFormat sdf = new SimpleDateFormat(timestrformart) ;
        Calendar calendar = Calendar.getInstance() ;
        String currentDay = sdf.format(calendar.getTime()) ;
        bb.writeLog("currentDay:"+currentDay);

        String sql =" with cte as\n" +
                " (\n" +
                "    select d.id,d.managerid from hrmresource d\n" +
                "    where d.managerid=?\n" +
                "    union all\n" +
                "    select a.id,a.managerid from hrmresource a\n" +
                "    inner join cte b on a.managerid = b.id\n" +
                " )\n" +
                "  select h.id,h.lastname,datediff(Day,CONVERT(varchar(10),GETDATE(),120),enddate) as ts from hrmresource h " +
                "  where h.id in( \n" +
                "     select id from hrmresource where id= ?\n" +
                "     union all\n" +
                "     select id from cte\n" +
                "  )\n" +
                "  and datediff(Day,CONVERT(varchar(10),GETDATE(),120),enddate)<30\n" +
                "  and datediff(Day,startdate,CONVERT(varchar(10),GETDATE(),120))>0\n" +
                "  and h.startdate is not null\n" +
                "  and h.enddate is not null and len(h.startdate) > 0 and len(h.enddate) > 0 \n" +
                "  and h.status in(1,2,3,4) ";

        bb.writeLog("sql:"+sql);
        rs.executeQuery(sql,new Object[]{userid,userid});
        while (rs.next()){
            String id = Util.null2String(rs.getString("id"));
            String lastname = Util.null2String(rs.getString("lastname"));
            String ts = Util.null2String(rs.getString("ts"));
            bb.writeLog("lastname:"+lastname);
            bb.writeLog("ts:"+ts);

            dataMap = new HashMap<String, Object>();
            dataMap.put("userid",id);
            dataMap.put("fxmc","合同到期天数");
            dataMap.put("fxry",lastname);
            dataMap.put("fxlx","人事风险");
            dataMap.put("zbnum",ts);
            dataMap.put("unit","天");
            //{"fxmc":"下属工作微博连续不查看天数","fxry":"石磊","fxzb":"9","zbnum":"5","fxlx":"当责风险"},{"fxmc":"文档连续不查看天数","fxry":"王帆（南
            dataList.add(dataMap);
        }

        return dataList;
    }
    /***
     *
     * @param userid
     * @param itemid
     * @return
     */
    /**
     * 风险主页滚动部分调用方法
     * @param user
     * @param request
     * @return
     */
    public List<Map<String,Object>> getRiskHomeWarning(User user, HttpServletRequest request) {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try {
            RecordSet rs = new RecordSet();
            int pageSize = Util.getIntValue(request.getParameter("pageSize"),180);
            Map<String,Object> map = null ;
            StringBuffer sbf = new StringBuffer();
            Map<String,String> riskMap = getRiskIndexId();
            sbf.append(" t.fxlx,t.fxzb,t.fxry,t.fxx,t.fxfl,SUM(CASE WHEN ISNULL(ckbz, 0) = 0 THEN zbnum when t.fxzb='"+riskMap.get("xmcql")+"' then 1 ELSE FLOOR(zbnum / ckbz) END) zbnum from (	");
            sbf.append(getRiskSql(request,user,""));
            sbf.append(") t WHERE ckbz < = zbnum GROUP BY fxlx,t.fxry,t.fxzb,t.fxx,t.fxfl ");

            String sql = "SELECT  uf.fxlx,zbnum,fxzb, t1.fxmc,                                             "+
                    " CASE WHEN fxfl =0 THEN (SELECT  name FROM CRM_CustomerInfo t5 WHERE fxx = t5.id) "+
                    " WHEN fxfl =1 THEN (SELECT  projName FROM proj_CardBaseInfo t4 WHERE fxx = t4.id ) "+
                    " WHEN fxfl =2 THEN (SELECT csc.subject FROM  CRM_SellChance csc WHERE fxx = csc.id) end relaname,"+
                    " hrm.lastname,hrm.id as userid	   "+
                    "	  FROM      ( SELECT TOP "+pageSize+"						   "+
                    sbf.toString()+
                    " ORDER BY zbnum desc,fxry "+
                    "	        ) tt,uf_risktype uf,hrmresource hrm,uf_risk t1 WHERE tt.fxlx = uf.id AND tt.fxry = hrm.id AND tt.fxzb = t1.id													   "+
                    "	ORDER BY zbnum desc,fxry												   ";
            rs.execute(sql);
            //System.out.println(sql);
            while(rs.next()){
                map  = new HashMap<String,Object>();
                String userid = Util.null2String(rs.getString("userid"));
                String name = Util.null2String(rs.getString("lastname"));
//                if(!"".equals(Util.null2String(rs.getString("relaname")))){
//                    name += "("+Util.null2String(rs.getString("relaname"))+")";
//                }

                map.put("userid", userid);
                map.put("fxry", name);
                map.put("fxlx", Util.null2String(rs.getString("fxlx")));
                map.put("fxmc", Util.null2String(rs.getString("fxmc")));
                map.put("fxzb", Util.null2String(rs.getString("fxzb")));
                map.put("zbnum", Util.null2String(rs.getString("zbnum")));
                map.put("unit","次");
                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /***
     *
     * @param request
     * @param user
     * @param groupsql
     * @return
     */
    public String getRiskSql(HttpServletRequest request,User user,String groupsql){
        StringBuffer sql = new StringBuffer();
        String cdate = TimeUtil.getCurrentDateString();//当前时间
        String cyear = cdate.substring(0,4);//当前年
        String startDate = Util.null2String(request.getParameter("startDate")); //开始时间
        String endDate = Util.null2String(request.getParameter("endDate")); //结束时间
        if("".equals(startDate) && "".equals(endDate)){
            startDate = cyear +"-01-01";
            endDate = cdate;
        }
        String fxzb = Util.null2String(request.getParameter("fxzb")); //风险指标id
        if(fxzb.startsWith(",")) fxzb = fxzb.substring(1);
        if(fxzb.endsWith(",")) fxzb = fxzb.substring(0, fxzb.length()-1);
        sql.append("SELECT ");
        if(!"".equals(groupsql)){
            sql.append(groupsql);
        }else{
            sql.append(" t.fxry,t.fxzb,t.fxx,t.fxfl,t1.ckbz,t1.fxlx ");
        }
        Map<String,String> map = getRiskIndexId();

        sql.append(",(CASE WHEN t.fxzb='"+map.get("xmcql")+"' THEN sum(t.fxz) ELSE COUNT(t.id) end ) zbnum ");
        //sql.append("SELECT  t.fxry,t.fxzb,t.fxkh,t.fxxm,t1.ckbz,t1.fxlx,COUNT(t.id) zbnum ");
        sql.append(" FROM  uf_riskdetail t ");
        if (!HrmUserVarify.checkUserRight("OrgHrmTree:View", user) || (!"".equals(groupsql) && groupsql.indexOf("jobactivitydesc")!=-1)){
            sql.append(" inner JOIN hrmresource hrm ON t.fxry = hrm.id");
        }
        sql.append(" inner JOIN uf_risk2 t1 ON t.fxzb = t1.pid and t1.userid = "+user.getUID()+" and t1.isused = 1 ");
        //sql.append(" where hrm.status IN (0,1,2,3) ");
        sql.append(" where t.fxrq >= '"+startDate+"' and t.fxrq <= '"+endDate+"' ");
        if (!HrmUserVarify.checkUserRight("OrgHrmTree:View", user)){
            sql.append(" and (hrm.managerstr like '%,"+user.getUID()+",%' or hrm.id = "+user.getUID()+" )");
        }
        if(!"".equals(fxzb)){
            sql.append(" and t1.pid in ("+fxzb+")");
        }
        if(!"".equals(groupsql) && groupsql.indexOf("jobactivitydesc")!=-1){
            sql.append(" and hrm.jobactivitydesc IN('销售','技术','项目','运营','咨询','客服') ");
        }
        if(!"".equals(groupsql)){
            sql.append(" GROUP BY "+groupsql);
        }else{
            sql.append(" GROUP BY t.fxry,t.fxzb,t.fxx,t.fxfl,t1.ckbz,t1.fxlx ");
        }
        return sql.toString();
    }


    public static Map<String, String> getRiskIndexId() {

        String sql = "select id,bs from uf_risk ";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql);
        Map<String, String> map = new HashMap<String, String>();
        while (rs.next()) {
            if (!"".equals(Util.null2String(rs.getString("bs")))) {
                map.put(Util.null2String(rs.getString("bs")), Util.null2String(rs.getString("id")));
            }
        }
        return map;
    }


%>



