<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.util.*" %>
<%@ page import="com.censoft.common.db.ConnectionFactory" %>
<%@ page import="com.censoft.common.base.Pub" %>
<%@ page import="com.censoft.db.Logger" %>
<%@ page import="java.text.DateFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.text.ParseException" %>
<%!
    public static String getUserNames(ConnectionFactory cf,Connection conn,int startIndex,int n){
        Vector userListSize = cf.doQuery(conn,"select id from zb_user",null,new Object[]{});
        StringBuffer sql=new StringBuffer("select user_name from zb_user where 1=1 and order_num in(");
        List list= new ArrayList();
        String user_names="";
        int startIndex_2=startIndex;
        for(int i=0;i<n;i++){
            startIndex=startIndex+1;
            if(startIndex==userListSize.size()+1){
                startIndex=1;
            }
            if(i==n-1){
                sql.append(startIndex );
            }else{
                sql.append(startIndex + ",");
            }
        }
        sql.append(") order by field (order_num,");
        for(int i=0;i<n;i++){
            startIndex_2=startIndex_2+1;
            if(startIndex_2==userListSize.size()+1){
                startIndex_2=1;
            }
            if(i==n-1){
                sql.append(startIndex_2 );
            }else{
                sql.append(startIndex_2 + ",");
            }
        }
        sql.append(") ");
        Vector userList = cf.doQuery(conn,sql.toString(),null,list.toArray());
        if(userList!=null && userList.size()>0){
            for(int i=0;i<userList.size();i++) {
                Hashtable ht1 = (Hashtable) userList.get(i);
                String user_name = (String) ht1.get("user_name");
                user_names=user_names+user_name+",";
            }
        }else{
            System.out.println("方法查询出错"+cf.getMsg());
        }
        return startIndex+"_"+user_names;
    }
    public static List<String> getDays(String startTime, String endTime) {
        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
    public static String getBeforeDay(String specifiedDay)
    {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try
        {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);
        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }
    public static int getUserOrder(ConnectionFactory cf,Connection conn,String username) {
        int order_num=0;
        Vector userList = cf.doQuery(conn,"select order_num from zb_user where user_name=?",null,new Object[]{username});
        if(userList!=null && userList.size()>0){
            Hashtable ht1 = (Hashtable) userList.get(0);
            order_num = Integer.parseInt((String) ht1.get("order_num"));
        }
        return order_num;
    }
    public static int getStartIndexByDate(ConnectionFactory cf,Connection conn,String date)
    {
        String zb_user ="";
        Vector userList = cf.doQuery(conn,"select zb_user from zb_user_gl where year=? order by id desc",null,new Object[]{date});
        if(userList!=null && userList.size()>0) {
            Hashtable ht1 = (Hashtable) userList.get(0);
            zb_user = (String) ht1.get("zb_user");
        }
        if(zb_user.indexOf(",")>0){
            zb_user=zb_user.substring(zb_user.lastIndexOf(",")+1,zb_user.length());
        }
       return getUserOrder(cf,conn,zb_user);
    }
%>
<%
    ConnectionFactory cf = new ConnectionFactory();
    Pub pub = new Pub();
    Connection conn = null;
    String action = pub.trimNull(request.getParameter("action"));
    String action_msg="";
    String mx_id = pub.trimNull(request.getParameter("mx_id"));
    String b_time = pub.trimNull(request.getParameter("b_time"));
    String e_time = pub.trimNull(request.getParameter("e_time"));
    String date_left = pub.trimNull(request.getParameter("date_left"));
    String date_right = pub.trimNull(request.getParameter("date_right"));
    String user_left = pub.trimNull(request.getParameter("user_left"));
    String user_right = pub.trimNull(request.getParameter("user_right"));
    String zb_type_left = pub.trimNull(request.getParameter("zb_type_left"));
    String zb_type_right = pub.trimNull(request.getParameter("zb_type_right"));
    String mx_day ="";
    String mxId="";
    if(!"".equals(mx_id)){
         mx_day = mx_id.substring(mx_id.indexOf("_")+1,mx_id.length());//模型天数
         mxId=mx_id.substring(0,mx_id.indexOf("_"));;//模型id
    }
    int mxDay=1;
    if(!"".equals(mx_day)){
        mxDay=Integer.parseInt(mx_day);
    }
    String userNames="";
    List<String> list=null;
    int selectDay=0;
    if(!"".equals(b_time)&&!"".equals(e_time)){
        list= getDays(b_time,e_time);//获取两个时间点之间的日期
        selectDay=list.size();
    }
    String add_user = pub.trimNull((String) session.getAttribute("session_login_id"));
    if ("".equals(add_user)) {
        System.out.println("当前没有用户信息");
    }
    int startIndexBefore=0;
    String add_time = pub.getCurrentServerTime();
    StringBuffer sql_add=new StringBuffer("insert into zb_zdpb (b_time,e_time,mx_id,add_time,add_user) values (?,?,?,?,?)");
    try {
        conn = com.censoft.db.DBUtil.getConnection();
        List list_add= new ArrayList();
        list_add.add(b_time);
        list_add.add(e_time);
        list_add.add(mxId);
        list_add.add(add_time);
        list_add.add(add_user);
        conn.setAutoCommit(false);
        boolean is_oper = false;
        if("add".equals(action)){
            if(!"".equals(b_time)){
                String beforeDate=getBeforeDay(b_time);//获取开始时间的上一天
                startIndexBefore=getStartIndexByDate(cf,conn,beforeDate);//根据上一天获取最后人员的序号
            }
            action_msg="新增";
            is_oper = cf.executeUpdate(conn, sql_add.toString(),list_add.toArray());
            if (!is_oper) {
                conn.rollback();
                System.out.println("新增zb_zdpb表出错了" + cf.getMsg());
                return;
            }
            int startIndex=startIndexBefore;
            int index=0;
            StringBuffer sql1=new StringBuffer("insert into zb_user_gl (year,zb_type,zb_user,order_num,add_user,add_time) values (?,?,?,?,?,?)");
            Vector zb_type_list = cf.doQuery(conn,"select * from zb_type where mx_id=? order by order_num asc",null,new Object[]{mxId});
            if(selectDay/mxDay>0){//所选天数比模型天数多
                for(int a=0;a<selectDay/mxDay;a++){//按照模型天数轮回
                    if(zb_type_list!=null && zb_type_list.size()>0) {
                        for (int i = 0; i < zb_type_list.size(); i++) {
                            Hashtable ht = (Hashtable) zb_type_list.get(i);
                            String ren_num = pub.trimNull((String) ht.get("ren_num"));
                            String zb_type = pub.trimNull((String) ht.get("zb_type"));
                            for(int n=0;n<mxDay;n++){//按照模型天数，从开始日期逐天插入
                                index=a*mxDay+n;//日期坐标索引
                                if(n==mxDay){
                                    index=0;
                                }
                                //根据开始人员序号索引和人数进行插入
                                userNames=getUserNames(cf,conn,startIndex,Integer.parseInt(ren_num));
                                if(!"".equals(userNames)){
                                    startIndex = Integer.parseInt(userNames.substring(0,userNames.indexOf("_")));
                                    userNames = userNames.substring(userNames.indexOf("_")+1,userNames.length()-1);
                                }
                                is_oper = cf.executeUpdate(conn, sql1.toString()
                                        , new Object[]{list.get(index),zb_type, userNames,index+1,add_user,add_time});
                                if (!is_oper) {
                                    System.out.println("新增zb_user_gl表出错了" + cf.getMsg());
                                    conn.rollback();
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            //剩余天数
            if(selectDay%mxDay>0) {
                for (int i = 0; i < zb_type_list.size(); i++) {
                    Hashtable ht = (Hashtable) zb_type_list.get(i);
                    String ren_num = pub.trimNull((String) ht.get("ren_num"));
                    String zb_type = pub.trimNull((String) ht.get("zb_type"));
                    index=selectDay-(selectDay%mxDay);
                    for(int n=0;n<selectDay%mxDay;n++){
                        userNames=getUserNames(cf,conn,startIndex,Integer.parseInt(ren_num));
                        if(!"".equals(userNames)){
                            startIndex = Integer.parseInt(userNames.substring(0,userNames.indexOf("_")));
                            userNames = userNames.substring(userNames.indexOf("_")+1,userNames.length()-1);
                        }
                        is_oper = cf.executeUpdate(conn, sql1.toString()
                                , new Object[]{list.get(index),zb_type, userNames,index+1,add_user,add_time});
                        if (!is_oper) {
                            System.out.println("新增zb_user_gl表出错了" + cf.getMsg());
                            conn.rollback();
                            return;
                        }
                        index++;
                    }
                }
            }
        }else if("delete".equals(action)){
            is_oper = cf.executeUpdate(conn, "delete from zb_zdpb where b_time=? and e_time=?"
                    , new Object[]{b_time,e_time});
            if (!is_oper) {
                System.out.println("删除zb_zdpb表出错了" + cf.getMsg());
                conn.rollback();
                return;
            }
            is_oper = cf.executeUpdate(conn, "delete from zb_user_gl where year>=? and year<=?"
                    , new Object[]{b_time,e_time});
            if (!is_oper) {
                System.out.println("删除zb_user_gl表出错了" + cf.getMsg());
                conn.rollback();
                return;
            }
        }else if("changeUser".equals(action)){
            is_oper = cf.executeUpdate(conn, "update zb_user_gl set zb_user=REPLACE(zb_user,?,?) where year=? and zb_type=?"
                    , new Object[]{user_left,user_right,date_left,zb_type_left});
            if (!is_oper) {
                System.out.println("交换zb_user_gl表出错了" + cf.getMsg());
                conn.rollback();
                return;
            }
            is_oper = cf.executeUpdate(conn, "update zb_user_gl set zb_user=REPLACE(zb_user,?,?) where year=? and zb_type=?"
                    , new Object[]{user_right,user_left,date_right,zb_type_right});
            if (!is_oper) {
                System.out.println("交换zb_user_gl表出错了" + cf.getMsg());
                conn.rollback();
                return;
            }
        }
        if (!is_oper) {
            conn.rollback();
            System.out.println("操作出错了" + cf.getMsg());
            return;
        }
        Logger.log(conn, "值班管理",action_msg,  add_user, "", request);
        conn.commit();
        if (!is_oper) {
            conn.rollback();
            out.println(cf.getMsg());
        } else {
            out.println("success,"+mx_id);
        }
    } catch (Exception e) {
        conn.rollback();
        System.out.println("有异常" + e);
        return;
    } finally {
        if (conn != null) {
            conn.setAutoCommit(true);

            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
%>
