    $(document).ready(function() {

        //  $("#main_content_title").html("稽查人员排班")

        var user = $.zui.store.get("user"); // 缓存用户信息，取出dept_id
        // console.log(user );
        // 用户的dept_id
        var user_dept_id = user.organid;

        // 稽查小组type
        var team_type = 2;

        // 日期游标
        var date_cursor = 0;

        // 选择下拉框
        var role_selectinput;

        var team_stuffs = [];

        selectInitInput(team_stuffs);

        function selectInitInput(objs) {
            $("#relash").empty();
            $("#relash").append('<input type="text" class="form-control class_team_41" id="team_detail" >');
            role_selectinput = $('#relash #team_detail').comboTree({
                source: objs,
                isMultiple: true
            });
        }

        function getSelectInputValue() {
            return role_selectinput.getSelectedItemsId();
        }

        $('#calendar').calendar();
        var calendar = $('#calendar').data('zui.calendar');

        calendarInit();

        // 请求稽查人员排班数据
        function calendarInit(data_param) {
            var data = {
                "dept_id": user_dept_id,
                "start_time": getCurrentMonthFirst(),
                "end_time": getCurrentMonthLast(),
                'type': team_type
            }
            if (data_param != undefined) {
                data = data_param;
            }
            getTeamClass(data, function(data) {
                var newEvents = [];
                //  console.log(data);
                for (var i = 0; i < data.length; i++) {
                    var obj = { id: data[i].id, desc: data[i].team_name, title: data[i].team_name + "-" + getTeamName(data[i].class_type), start: data[i].start_time, end: data[i].start_time };
                    newEvents.push(obj);
                }
                // console.log(newEvents)
                calendar.addEvents(newEvents);
            })
        }

        // 获取排班信息
        function getTeamClass(data, _function) {
            post_common_service("teamClass/getClassList", data, function(data) {
                _function(data);
            }, function(error) {
                return "";
            })
        }

        // 更新日历数据
        function updateCalendar(data) {
            calendar.events = [];
            calendar.display();
            calendarInit(data);
        }

        // 当月第一天
        function getCurrentMonthFirst() {
            var date = new Date();
            date.setDate(1);
            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            return date.Format("yyyy-MM-dd HH:mm:ss");
        }

        // 当月最后一天
        function getCurrentMonthLast() {
            var date = new Date();
            var currentMonth = date.getMonth();
            var nextMonth = ++currentMonth;
            var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
            var oneDay = 1000 * 60 * 60 * 24;
            var date1 = new Date(nextMonthFirstDay - oneDay);
            date1.setHours(0);
            date1.setMinutes(0);
            date1.setSeconds(0);
            return date1.Format("yyyy-MM-dd HH:mm:ss");
        }

        // 上一个月或者下个月的第一天或者最后一天
        function getMonthByCondition(pre_or_after, first_or_last) {
            if (first_or_last == 'first') {
                var date = new Date();
                date.setDate(1);
                date.setMonth(date.getMonth() + pre_or_after);
                return date;
            } else if (first_or_last == 'last') {
                var date = new Date();
                var currentMonth = date.getMonth();
                var nextMonth = ++currentMonth;
                var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
                var oneDay = 1000 * 60 * 60 * 24;
                date = new Date(nextMonthFirstDay - oneDay);
                date.setMonth(date.getMonth() + pre_or_after);
                return date;
            }
        }

        $('#calendar').calendar().on("clickEvent.zui.calendar", function(event) {
            // console.log(event);
            click_function(event.event.start);
        });

        /**
         * 点击日历触发函数
         */
        function click_function(date) {
            setAddTermTitle(date.format("yyyy-MM-dd"));
            // 保存当前日期
            $("#save_term_class").data("date", date.format("yyyy-MM-dd"));
            $("#team_detail").val("");
            var data = {
                "dept_id": user_dept_id,
                "start_time": date.format("yyyy-MM-dd 00:00:00"),
                "end_time": date.format("yyyy-MM-dd 00:00:00"),
                'type': team_type
            }

            getTeamClass(data, function(data) {
                for (var i = 0; i < $("select[id*='_term']").length; i++) {
                    $("select[id*='_term']").eq(i).val("");
                }

                if (data.length > 0) {

                    $("#save_term_class").data("modify_flag", 1);
                    for (var i = 0; i < data.length; i++) {
                        $(".class_team_" + data[i].class_type).val(data[i].team_id);
                    }

                    var user_ids_name = data[0].user_ids_name;
                    var user_ids = data[0].user_ids;
                    // 请求班组下人员信息
                    var dataObj = { "id": data[0].team_id };
                    post_common_service("team/getDetailById", dataObj, function(data) {
                        get_input_data(data);
                        // $("#team_detail").val(user_ids_name.substring(0,user_ids_name.length-1));
                        var user_id = user_ids.split(",");
                        var user_name = user_ids_name.substring(0, data.user_ids_name.length - 1).split(',');
                        var team_temp_stuffs = [];
                        for (var i = 0; i < user_id.length; i++) {
                            $('span[data-id="' + user_id[i] + '"] input').attr("checked", true);
                            var zdataItem = {};
                            zdataItem["id"] = user_id[i];
                            zdataItem["title"] = user_name[i];
                            team_temp_stuffs.push(zdataItem);
                        }
                        role_selectinput._selectedItems = team_temp_stuffs;
                        role_selectinput.refreshInputVal();
                    }, function(error) {})
                } else {
                    $("#save_term_class").data("modify_flag", 0);
                }
                $('#myModal').modal();
            })
        }

        $('#calendar').calendar().on("clickCell.zui.calendar", function(event) {
            // console.log(event);
            click_function(event.date);
        });

        // 下一个日期
        $('#calendar').calendar().on("clickNextBtn.zui.calendar", function(event) {
            // console.log(event);
            date_cursor++;

            var data = {
                "dept_id": user_dept_id,
                "start_time": getMonthByCondition(date_cursor, 'first').format("yyyy-MM-dd 00:00:00"),
                "end_time": getMonthByCondition(date_cursor, 'last').format("yyyy-MM-dd 00:00:00"),
                'type': team_type
            }
            updateCalendar(data);
        });

        // 上一个日期
        $('#calendar').calendar().on("clickPrevBtn.zui.calendar", function(event) {
            date_cursor--;
            var data = {
                "dept_id": user_dept_id,
                "start_time": getMonthByCondition(date_cursor, 'first').format("yyyy-MM-dd 00:00:00"),
                "end_time": getMonthByCondition(date_cursor, 'last').format("yyyy-MM-dd 00:00:00"),
                'type': team_type
            }
            updateCalendar(data);
        });

        // 今天
        $('#calendar').calendar().on("clickTodayBtn.zui.calendar", function(event) {
            // console.log(event);
            date_cursor = 0;
            calendarInit();
        });

        $("#save_term_class").click(function() {
            var data = [];
            var user_ids = getSelectInputValue();
            var str_user_ids = '';
            if (user_ids != false) {
                for (var i = 0; i < user_ids.length; i++) {
                    str_user_ids = str_user_ids + ((i != 0) ? (',' + user_ids[i]) : user_ids[i]);
                }
            }
            if (str_user_ids == '') {
                tip("请选择值班人员");
                return;
            }
            for (var i = 0; i < $("select[id*='_term']").length; i++) {
                if ($("select[id*='_term']").eq(i).val() != "") {
                    var obj = {
                        "class_type": 4,
                        "team_id": $("select[id*='_term']").eq(i).val(),
                        "work_date": $("#save_term_class").data("date") + " 00:00:00",
                        "start_time": $("#save_term_class").data("date") + " 00:00:00",
                        "end_time": $("#save_term_class").data("date") + " 00:00:00",
                        "dept_id": user_dept_id,
                        "user_ids": str_user_ids,
                        "user_type": 2 //表示稽查办
                    };
                    data.push(obj);
                }
            }

            if (data.length == 0) {
                tip("请填写排班信息!");
                return;
            }
            if ($("#save_term_class").data("modify_flag") != 1) {
                post_common_service("teamClass/add/list", data, function(data) {
                    updateCalendar();
                    tip("今日排班成功!");
                    $('#myModal').modal('hide');
                }, function(error) {
                    $('#myModal').modal('hide');
                })
            } else {
                post_common_service("teamClass/update/list", data, function(data) {
                    updateCalendar();
                    tip("今日排班成功!");
                    $('#myModal').modal('hide');
                }, function(error) {
                    $('#myModal').modal('hide');
                })
            }
        })

        $("#close_btn").click(function() {
            $('#myModal').modal('hide');
        })

        // 获取部门为1的班组信息
        getTermClass(user_dept_id);

        // 获取班组信息
        function getTermClass(dept_id) {
            var data = {
                'dept_id': dept_id,
                'type': team_type
            }
            post_common_service("team/getTeamByDeptId/1/50", data, function(data) {
                for (var i = 0; i < data.list.length; i++) {
                    $("#mooring_term,#middle_term,#night_term,#all_term").append("<option value='" + data.list[i].id + "'>" + data.list[i].name + "</option>")
                }
                //cs客户端弹出框显示下拉框有问题
                $('#all_term').chosen({
                    width: '200px',
                    height: '100px',
                    no_results_text: '没有找到', // 当检索时没有找到匹配项时显示的提示文本
                    disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框
                    search_contains: true // 从任意位置开始检索
                });
            }, function(error) {})
        }


        $("#all_term").change(function() {
            if ($(this).val() != "") {
                // 请求班组下人员信息
                var data = { "id": $(this).val() };
                post_common_service("team/getDetailById", data, function(data) {

                    get_input_data(data)
                }, function(error) {})
            } else {
                $("#team_detail").val();
            }
        })

        function get_input_data(data) {
            if (data.user_ids.length > 0) {
                var user_name = data.user_ids_name.substring(0, data.user_ids_name.length - 1).split(',');
                var user_id = data.user_ids.split(",");
                team_stuffs = [];
                for (var i = 0; i < user_name.length; i++) {
                    var zdataItem = {};
                    zdataItem["id"] = user_id[i];
                    zdataItem["title"] = user_name[i];
                    team_stuffs.push(zdataItem);
                }
                selectInitInput(team_stuffs);
            }
        }


        // 根据class_type 获取班次名称
        function getTeamName(class_type) {
            if (class_type == 1) {
                return "早班";
            } else if (class_type == 2) {
                return "中班";
            } else if (class_type == 3) {
                return "夜班";
            } else if (class_type == 4) {
                return "全班";
            }
        }

        function setAddTermTitle(title) {
            $(".modal-title").html("添加班组-" + title);
        }

    })