<%@ page import="weaver.general.*" %>
<%@ page import="weaver.conn.RecordSet"%>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="org.apache.commons.lang.StringUtils" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.text.ParseException" %>
<%@ page import="weaver.gp.cominfo.AccessItemComInfo" %>
<%@ page import="weaver.systeminfo.SystemEnv" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<%
    BaseBean bb = new BaseBean();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String type = Util.null2String(request.getParameter("type"));
    Map<String,String> lastscop = new HashMap<String,String>();

    String startdate = "";
    String enddate = "";
    int currentYear = 0 ;
    int currentMonth = 0;
    int lastYear = 0;
    int lastMonth = 0 ;
    int last2Year = 0;
    int last2Month = 0 ;
    if("1".equals(type)){
        String year = Util.null2String(request.getParameter("year"));
        String month = Util.null2String(request.getParameter("month"));
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(year+"-"+month+"-01"));
            currentYear = cal.get(Calendar.YEAR);//获取年
            currentMonth = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
        } catch (ParseException e) {
            e.printStackTrace();
        }

        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(year+"-"+month+"-01"));
            cal.add(Calendar.MONTH, -1);
            lastYear = cal.get(Calendar.YEAR);//获取年
            lastMonth = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
        } catch (ParseException e) {
            e.printStackTrace();
        }

        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(year+"-"+month+"-01"));
            cal.add(Calendar.MONTH, -2);
            last2Year = cal.get(Calendar.YEAR);//获取年
            last2Month = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(currentMonth == 1){
            startdate = (currentYear-1)+"-01-01";
            enddate = (currentYear-1)+"-12-31";
        }else{
            startdate = currentYear+"-01-01";
            enddate = currentYear+"-12-31";
        }

    }else{

        Calendar cal1 = Calendar.getInstance();
        currentYear = cal1.get(Calendar.YEAR);//获取年
        currentMonth = cal1.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）


        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(new Date());
        cal2.add(Calendar.MONTH, -1);
        lastYear = cal2.get(Calendar.YEAR);//获取年
        lastMonth = cal2.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）


        Calendar cal3 = Calendar.getInstance();
        cal3.setTime(new Date());
        cal3.add(Calendar.MONTH, -2);
        last2Year = cal3.get(Calendar.YEAR);//获取年
        last2Month = cal3.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）

        if(currentMonth == 1){
            startdate = (currentYear-1)+"-01-01";
            enddate = (currentYear-1)+"-12-31";
        }else{
            startdate = currentYear+"-01-01";
            enddate = currentYear+"-12-31";
        }
    }

    User user = HrmUserVarify.getUser(request , response);
    int userid = user.getUID();

    bb.writeLog("startdate:"+startdate);
    bb.writeLog("enddate:"+enddate);
    List<String> monthList = getMonthBetweenDate(startdate,enddate);
    bb.writeLog("monthList:"+monthList.size());

    List<Map<String,String>> data = getPersonAccessScore(monthList,startdate,enddate,userid);

    List<Map<String,String>> item = getAccessItem(lastYear,lastMonth,user);

    lastscop = getPersonAccessLastScore(userid,lastYear,lastMonth,last2Year,last2Month);


    JSONObject jsonObject = new JSONObject();
    jsonObject.put("scoreData",data);
    jsonObject.put("scoreYear",currentYear);
    jsonObject.put("itemData",item);
    jsonObject.put("lastScoreData",lastscop);
    jsonObject.put("startdate",startdate);
    jsonObject.put("enddate",enddate);
    bb.writeLog("jsonObject:"+jsonObject.toJSONString());

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

<%!
    /***
     *
     * @param year
     * @param month
     * @param
     * @return
     */
    public List<Map<String,String>> getAccessItem(int year,int month,User user)
    {
        AccessItemComInfo accessItemComInfo = null;
        int userid = user.getUID();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
        try {
            accessItemComInfo = new AccessItemComInfo();
            String scopid = "" ;
            String sql = " select id from GP_AccessScore where isvalid = 1 and userid=? and year=? and type2=? ";
            rs.executeQuery(sql,new Object[]{userid,year,month});
            if(rs.next()){
                scopid = Util.null2String(rs.getString("id"));
            }
            bb.writeLog("scopid:"+scopid);

            if(StringUtils.isEmpty(scopid)){
                sql = " select id from GP_AccessScore where isvalid = 1 and userid=? and year=? and type2=? ";
                rs.executeQuery(sql,new Object[]{userid,year,(month-1)});
                if(rs.next()){
                    scopid = Util.null2String(rs.getString("id"));
                }
            }
            bb.writeLog("scopid:"+scopid);

            Map<String,String> dataMap = null;
            if(StringUtils.isNotEmpty(scopid))
            {
                //当前绩效具体数据
                String backfields = " select top(2) t.accessitemid,t.description,t.rate ";
                String fromsql = " from GP_AccessScoreDetail t";
                String sqlwhere = " where t.scoreid=" + scopid;
                String orderby = " order by t.rate desc";

                bb.writeLog("sql:"+backfields + fromsql + sqlwhere + orderby);

                rs.executeQuery(backfields + fromsql + sqlwhere + orderby);
                while (rs.next()) {
                    dataMap = new HashMap<String, String>();
                    String accessitemid = Util.null2String(rs.getString("accessitemid"));
                    String formuladetail = accessItemComInfo.getFormuladetails(accessitemid);//指标公式
                    int formula = Util.getIntValue(accessItemComInfo.getFormula(accessitemid), 0);//指标计算公式类型
                    int itemtype = Util.getIntValue(accessItemComInfo.getType(accessitemid), 0);//指标所属类型

                    dataMap.put("accessitem", accessItemComInfo.getName(Util.null2String(rs.getString("accessitemid"))) + (itemtype==2? getFormulaName(Util.null2String(formula), formuladetail, accessItemComInfo.getDesc(Util.null2String(rs.getString("accessitemid"))),user):""));//指标名称
                    dataMap.put("description", Util.HTMLtoTxt(rs.getString("description")));//描述
                    dataMap.put("rate", Util.null2String(rs.getString("rate")));//权重
                    dataList.add(dataMap);
                }
            }

            if(dataList.size() == 0)
            {
                dataMap = new HashMap<String, String>();
                dataMap.put("accessitem", "未开始");//指标名称
                dataMap.put("description", "");//描述
                dataMap.put("rate", "");//权重
                dataList.add(dataMap);

                dataMap = new HashMap<String, String>();
                dataMap.put("accessitem", "未开始");//指标名称
                dataMap.put("description", "");//描述
                dataMap.put("rate", "");//权重
                dataList.add(dataMap);
            }
        }catch (Exception e){
            bb.writeLog("getAccessItem-e:"+e);
        }
        return dataList;
    }

    /***
     *
     * @param formula
     * @param formuladetail
     * @param detaildesc
     * @param user
     * @return
     */
    private String getFormulaName(String formula, String formuladetail, String detaildesc,User user) {
        String formulaName = "";
        if ("1".equals(formula)) {
            formulaName = "[" + SystemEnv.getHtmlLabelName(508618, user.getLanguage()) + "/" + SystemEnv.getHtmlLabelName(18087, user.getLanguage()) + "*5]";
        } else if ("2".equals(formula)) {
            formulaName = "[" + SystemEnv.getHtmlLabelName(24933, user.getLanguage()) + "]";
        } else if ("3".equals(formula)) {
            formulaName = "[" + SystemEnv.getHtmlLabelName(509216, user.getLanguage()) + "]";
        } else if ("4".equals(formula)) {
            formulaName = "[" + SystemEnv.getHtmlLabelName(509217, user.getLanguage()) + "]";
        } else if ("5".equals(formula)) {
            formulaName = "[" + SystemEnv.getHtmlLabelName(18087, user.getLanguage()) + "/" + SystemEnv.getHtmlLabelName(508618, user.getLanguage()) + "*3.5]";
        } else if ("11".equals(formula)) {
            formulaName = "[" + SystemEnv.getHtmlLabelName(508618, user.getLanguage()) + "/" + SystemEnv.getHtmlLabelName(18087, user.getLanguage()) + " * " + SystemEnv.getHtmlLabelName(509212, user.getLanguage()) + "]";
        } else if ("12".equals(formula)) {
            formuladetail = formuladetail.replace("gval", SystemEnv.getHtmlLabelName(18087, user.getLanguage())).replace("cval", SystemEnv.getHtmlLabelName(508618, user.getLanguage()));
            formulaName = "[" + formuladetail + "]";
        } else if ("13".equals(formula)) {
            if (!"".equals(detaildesc)) {
                formulaName = "[" + detaildesc + "]";
            } else {
                String[] farray = formuladetail.split("\\.");
                if (farray != null && farray.length != 0) {
                    formuladetail = farray[farray.length - 1];
                }
                formulaName = SystemEnv.getHtmlLabelName(501509, user.getLanguage()) + "：[" + formuladetail + "]";
            }
        }
        return formulaName;
    }

    /***
     *
     * @param monthList
     * @param starDate
     * @param endDate
     * @param
     * @return
     */
    public List<Map<String,String>> getPersonAccessScore(List<String> monthList,String starDate,String endDate,int userid)
    {
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        List<Map<String,String>> scorelist = new ArrayList<Map<String,String>>();
        try {
            if(StringUtil.isEmpty(starDate)){
                starDate = TimeUtil.getFirstDayOfTheYear();
            }
            if(StringUtil.isEmpty(endDate)){
                endDate = TimeUtil.getCurrentDateString();
            }

            int yearto = 0 ;
            int monthto = 0 ;
            if(StringUtils.isNotEmpty(endDate)){
                yearto = Util.getIntValue(endDate.substring(0,4));
                monthto = Util.getIntValue(endDate.substring(5,7));
            }

            int yearfrom = 0 ;
            int monthfrom = 0 ;
            if(StringUtils.isNotEmpty(starDate)){
                yearfrom = Util.getIntValue(starDate.substring(0,4));
                monthfrom = Util.getIntValue(starDate.substring(5,7));
            }

            Map<String,String> scoremap = new HashMap<String,String>();
            if(yearfrom>0 && monthfrom>0 && yearto>0 && monthto>0)
            {
                String sql = " select t1.id,t1.year,t1.type2,t1.result,t1.status,t1.startdate,t1.enddate from GP_AccessScore t1 where t1.isvalid=1 and t1.type1=1 and t1.userid="+userid;
                if(yearfrom == yearto){
                    sql += " and t1.year="+yearfrom+" and t1.type2>="+monthfrom+" and t1.type2<="+ monthto;
                }else{
                    sql += " and ((t1.year="+yearfrom+" and t1.type2>="+monthfrom+") or (t1.year="+yearto+" and t1.type2<="+ monthto+"))";
                }
                sql += " order by t1.year,t1.type2";
                bb.writeLog(sql);
                rs.executeQuery(sql);
                while(rs.next()){
                    int year = Util.getIntValue(rs.getString("year"));
                    int month = Util.getIntValue(rs.getString("type2"));
                    String result = Util.null2String(rs.getString("result"));

                    bb.writeLog("year:"+year+" month:"+month+" result:"+result);

                    String yearMonth = year+"-"+((month<10)?"0"+month:month) ;
                    scoremap.put(yearMonth,result);


                }
            }

            Map<String,String> dataMap = null;
            for(int i=0;i<monthList.size();i++)
            {
                String result = "0" ;
                dataMap = new HashMap<String,String>();
                String yearmonth = monthList.get(i);
                String newMonth = "" ;
                if(StringUtils.isNotEmpty(yearmonth))
                {
                    result = Util.null2String(scoremap.get(yearmonth),"0") ;
                    bb.writeLog("result:"+result);
                    String month = yearmonth.substring(5,7);
                    newMonth = transformMonth(month);
                    dataMap.put("month",newMonth);
                    dataMap.put("score",Util.null2String(result,"0"));
                    scorelist.add(dataMap);


                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("getPersonAccessScore:"+e);
        }
        return scorelist;
    }

    /***
     *
     * @param month
     * @return
     */
    public String transformMonth(String month){
        String newMonth = "" ;
        if(StringUtils.isNotEmpty(month)){
            if("01".equals(month)){
                newMonth = "一月";
            }else if("02".equals(month)){
                newMonth = "二月";
            }else if("03".equals(month)){
                newMonth = "三月";
            }else if("04".equals(month)){
                newMonth = "四月";
            }else if("05".equals(month)){
                newMonth = "五月";
            }else if("06".equals(month)){
                newMonth = "六月";
            }else if("07".equals(month)){
                newMonth = "七月";
            }else if("08".equals(month)){
                newMonth = "八月";
            }else if("09".equals(month)){
                newMonth = "九月";
            }else if("10".equals(month)){
                newMonth = "十月";
            }else if("11".equals(month)){
                newMonth = "十一月";
            }else if("12".equals(month)){
                newMonth = "十二月";
            }
        }

        return newMonth;
    }

    /**
     * 获取两个日期之间的所有月份 (年月)
     *
     * @param startTime
     * @param endTime
     * @return：YYYY-MM
     */
    public List<String> getMonthBetweenDate(String startTime, String endTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()){
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一天
                calendar.add(Calendar.MONTH, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }


    /***
     *
     * @param userid
     * @return
     */
    public Map<String,String> getPersonAccessLastScore(int userid,int lastYear,int lastMonth,int last2Year,int last2Month)
    {
        Map<String,String> lastScopMap = new HashMap<String,String>();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        try {
            String yearMonth = "" ;
            String score = "" ;
            String scopid = "" ;
            String msg = "" ;
            String result = "0";

            String sql = " select t1.id,t1.year,t1.type2,t1.result,t1.status,t1.startdate,t1.enddate from GP_AccessScore t1 where t1.isvalid=1 and status = 1 and t1.type1=1 and t1.userid=? and year=? and type2=? ";
            bb.writeLog(sql);
            rs.executeQuery(sql,new Object[]{userid,lastYear,lastMonth});
            if(rs.next()){
                int year = Util.getIntValue(rs.getString("year"));
                int month = Util.getIntValue(rs.getString("type2"));
                score = Util.null2String(rs.getString("result"));
                scopid = Util.null2String(rs.getString("id"));
                bb.writeLog("year:"+year+" month:"+month+" score:"+score);
                result = "1";
                yearMonth = year+"年"+((month<10)?"0"+month:month)+"月" ;
            }

            if(StringUtils.isEmpty(scopid)){
                sql = " select t1.id,t1.year,t1.type2,t1.result,t1.status,t1.startdate,t1.enddate from GP_AccessScore t1 where t1.isvalid=1 and t1.type1=1 and t1.userid=? and year=? and type2=? ";
                bb.writeLog(sql);
                rs.executeQuery(sql,new Object[]{userid,last2Year,last2Month});
                if(rs.next()){
                    int year = Util.getIntValue(rs.getString("year"));
                    int month = Util.getIntValue(rs.getString("type2"));
                    score = Util.null2String(rs.getString("result"));
                    scopid = Util.null2String(rs.getString("id"));

                    result = "1";

                    bb.writeLog("year:"+year+" month:"+month+" scopid:"+scopid);
                    yearMonth = year+"年"+((month<10)?"0"+month:month)+"月" ;
                }else{
                    yearMonth = last2Year+"年"+((last2Month<10)?"0"+last2Month:last2Month)+"月" ;
                    score = "";
                    scopid = "";
                    result = "0";
                    msg = "未开始";
                }
            }

            lastScopMap.put("msg",msg);
            lastScopMap.put("yearmonth",yearMonth);
            lastScopMap.put("score",score);
            lastScopMap.put("result",result);
            lastScopMap.put("scopid",scopid);

        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("getPersonAccessLastScore-e:"+e);
        }
        return lastScopMap;
    }

%>


