<%@ 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 int getUserOrder(ConnectionFactory cf,Connection conn,String username) {
        int order_num =1;
        if(username.indexOf(",")>0){
            username=username.substring(username.lastIndexOf(",")+1,username.length());
        }
        Vector userList = cf.doQuery(conn,"select order_num from zb_user where user_name=?",null,new Object[]{username});
        if(userList!=null && userList.size()>0){
            for(int i=0;i<userList.size();i++) {
                Hashtable ht1 = (Hashtable) userList.get(i);
                order_num = Integer.parseInt((String) ht1.get("order_num"));
            }
        }
        return order_num;
    }
%>
<%
    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 mx_day = mx_id.substring(mx_id.indexOf("_")+1,mx_id.length());
    String mxId=mx_id.substring(0,mx_id.indexOf("_"));;
    int mxDay=1;
    if(!"".equals(mx_day)){
        mxDay=Integer.parseInt(mx_day);
    }
    String userNames="";
    List<String> list= getDays(b_time,e_time);
    int selectDay=list.size();
    String add_user = pub.trimNull((String) session.getAttribute("session_login_id"));
    if ("".equals(add_user)) {
        System.out.println("当前没有用户信息");
    }
    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(mx_id);
        list_add.add(add_time);
        list_add.add(add_user);
        conn.setAutoCommit(false);
        boolean is_oper = false;
        if("add".equals(action)){
            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;
            }
            if(mxDay==selectDay){
                StringBuffer sql1=new StringBuffer("insert into zb_user_gl (year,zb_type,zb_user,order_num,add_user,add_time) values (?,?,?,?,?,?)");
                StringBuffer sql2=new StringBuffer("select t1.user_name,t2.zb_type from zb_mx_day t1 join zb_type t2 on t1.zb_type=t2.id" +
                        " where t1.mx_id=? order by t1.id asc");
                Vector mxList=cf.doQuery(conn,sql2.toString(),null,new Object[]{mxId});
                if(mxList!=null && mxList.size()>0){
                    int n=0;
                    for(int i=0;i<mxList.size();i++) {
                        if(i%selectDay==0){
                            n=0;
                        }
                        Hashtable ht = (Hashtable) mxList.get(i);
                        String user_name = pub.trimNull((String) ht.get("user_name"));
                        String zb_type = pub.trimNull((String) ht.get("zb_type"));
                        System.out.println(n);
                        is_oper = cf.executeUpdate(conn, sql1.toString(),new Object[]{list.get(n),zb_type,user_name,i+1,add_user,add_time});
                        if (!is_oper) {
                            conn.rollback();
                            System.out.println("插入zb_user_gl表操作出错了" + cf.getMsg());
                            return;
                        }
                        n++;
                    }
                }
            }else if(selectDay>mxDay){
                int startIndex=0;
                int renNum=0;
                int index=0;
                StringBuffer sql1=new StringBuffer("insert into zb_user_gl (year,zb_type,zb_user,order_num,add_user,add_time) values (?,?,?,?,?,?)");
                StringBuffer sql2=new StringBuffer("select t1.user_name,t2.zb_type,t2.ren_num from zb_mx_day t1 join zb_type t2 on t1.zb_type=t2.id" +
                        " where t1.mx_id=? order by t1.id asc");
                Vector mxList=cf.doQuery(conn,sql2.toString(),null,new Object[]{mxId});
                if(mxList!=null && mxList.size()>0){
                    for(int i=0;i<mxList.size();i++) {
                        Hashtable ht = (Hashtable) mxList.get(i);
                        String user_name = pub.trimNull((String) ht.get("user_name"));
                        if(i==mxDay-1){
                            startIndex=getUserOrder(cf,conn,user_name);
                        }
                        String zb_type = pub.trimNull((String) ht.get("zb_type"));
                        is_oper = cf.executeUpdate(conn, sql1.toString(),new Object[]{list.get(index),zb_type,user_name,i+1,add_user,add_time});
                        if (!is_oper) {
                            conn.rollback();
                            System.out.println("插入zb_user_gl表操作出错了" + cf.getMsg());
                            return;
                        }
                        index++;
                    }
                }
                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)/mxDay>0){
                    for(int a=0;a<(selectDay-mxDay)/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++){
                                    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_mx_day表出错了" + cf.getMsg());
                                        conn.rollback();
                                        return;
                                    }
                                }
                                index++;
                            }
                        }
                    }
                }
                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<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_mx_day表出错了" + cf.getMsg());
                                conn.rollback();
                                return;
                            }
                        }
                        index++;
                    }
                }

            }
        }
        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) {
            }
        }
    }
%>
