define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'teacher/collection/index' + location.search,
                    add_url: 'teacher/collection/add',
                    edit_url: 'teacher/collection/edit',
                    del_url: 'teacher/collection/del',
                    multi_url: 'teacher/collection/multi',
                    import_url: 'teacher/collection/import',
                    table: 'teacher_collection',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'exam_collection_id',
                sortName: 'exam_collection_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                singleSelect : true, //
                searchFormVisible:true,
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'exam_collection_id', title: __('编号'),operate: false},
                        {field: 'exam_collection_name', title: __('Exam_collection_name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'sim_type', title: __('Sim_type'),searchList:{"0001":"FZD04B型侦毒器","0002":"FZB006型毒剂报警器","0003":"防化兵用毒剂报警器"},formatter: Table.api.formatter.simtype},
                        // {field: 'question_setting_method', title: __('Question_setting_method'),searchList:{"1":"系统随机","2":"教员自选","3":"任务自选"},formatter: Table.api.formatter.simmethod},
                        {
                            field: 'exam_collection_state',searchList:{"2":"打开","3":"关闭"},
                            title: __('Exam_collection_state'),
                            align: 'center',
                            table: table,
                            formatter: Table.api.formatter.collectonstate
                        },

                        // {field: 'task_id', title: __('Task_id')},
                        {field: 'limit_duration', title: __('Limit_duration')},
                        // {field: 'start_time', title: __('Start_time'), operate:false, addclass:'datetimerange', autocomplete:false},
                        // {field: 'end_time', title: __('End_time'), operate:false, addclass:'datetimerange', autocomplete:false},
                        // {field: 'create_user_id', title: __('Create_user_id')},
                        {field: 'create_by', title: __('Create_by'), operate: 'LIKE'},
                        // {field: 'qudui_count', title: __('区队数量'), operate: false},
                        {field: 'xueyuan_count', title: __('应考人数'), operate: false},
                        {field: 'yikao_count', title: __('已考人数'), operate: false},
                        {field: 'createtime', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,formatter: Table.api.formatter.datetime},
                        // {field: 'update_by', title: __('Update_by'), operate: 'LIKE'},
                        // {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'remark', title: __('Remark'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            // formatter: Table.api.formatter.operate
                            formatter: Table.api.formatter.buttons,
                            buttons: [
                                {
                                    name: 'dispatch',
                                    text: '编辑',
                                    icon: 'fa fa-pencil',
                                    title: '编辑',
                                    classname: 'btn btn-success btn-xs btn-magic btn-dialog',
                                    // extend: 'data-area=\'["85%","85%"]\'',
                                    url: 'teacher/collection/edit',
                                },
                                {
                                    name: 'dispatch',
                                    text: '进入考试',
                                    icon: 'fa fa-hand-pointer-o',
                                    title: '进入考试',
                                    visible: function (rr) {
                                        if(rr.exam_collection_state == 2){
                                            return true;
                                        }
                                        return false;
                                    },
                                    classname: 'btn btn-info btn-xs btn-magic btn-addtabs',
                                    url: 'teacher/exams/persent',
                                },
                                {
                                    name: 'dispatch',
                                    text: '查看学员',
                                    icon: 'fa fa-eye',
                                    title: '查看学员',
                                    visible: function (rr) {
                                        if(rr.user_count > 0){
                                            return true;
                                        }
                                        return false;
                                    },
                                    classname: 'btn btn-warning btn-xs btn-magic btn-dialog',
                                    extend: 'data-area=\'["85%","85%"]\'',
                                    url: 'teacher/collection/viewuser',
                                },
                                {
                                    name: 'dispatch',
                                    text: '添加学员',
                                    icon: 'fa fa-plus',
                                    title: '添加学员',
                                    classname: 'btn btn-success btn-xs btn-magic btn-dialog',
                                    extend: 'data-area=\'["85%","85%"]\'',
                                    url: 'teacher/collection/adduser',
                                },
                                {
                                    name: 'dispatch',
                                    text: '删除学员',
                                    icon: 'fa fa-pencil',
                                    title: '删除学员',
                                    visible: function (rr) {
                                        if(rr.user_count > 0){
                                            return true;
                                        }
                                        return false;
                                    },
                                    classname: 'btn btn-info btn-xs btn-magic btn-dialog',
                                    extend: 'data-area=\'["75%","75%"]\'',
                                    url: 'teacher/collection/edituser',
                                },
                                {
                                    name: 'dispatch',
                                    text: '删除',
                                    icon: 'fa fa-trash',
                                    title: '删除',
                                    classname: 'btn btn-danger btn-xs btn-magic btn-ajax',
                                    url: 'teacher/collection/del',
                                    confirm: '确定要删除吗？',
                                    success: function (data, ret) {
                                        $(".btn-refresh").trigger("click");
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }
                            ],
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $(document).on('click', '.btn-start', function () {
                var ids = Table.api.selectedids(table);
                Fast.api.ajax({
                    url: "teacher/collection/start/ids/"+ids,
                    type: "post",
                }, function () {
                    Layer.alert('开始成功');
                    table.bootstrapTable('refresh');
                    Layer.close(index);
                });
            });
        },

        viewuser: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'teacher/collection/viewuser/ids/' +Config.ids+ location.search,
                }
            });

            var table = $("#table");
            var multiple = true;
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'task_id',
                sortName: 'task_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                singleSelect : true,
                searchFormVisible:true,
                search: false,
                columns: [
                    [
                        // {checkbox: true},
                        // {field: 'task_id', title: __('Task_id'),operate: false},
                        {field: 'user_nickname', title: __('学员'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'sim_type', title: __('Sim_type'),searchList:{"0001":"FZD04B型侦毒器","0002":"FZB006型毒剂报警器","0003":"防化兵用毒剂报警器"},formatter: Table.api.formatter.simtype},
                        {field: 'question_setting_method', title: __('Question_setting_method'),searchList:{"1":"系统随机","2":"教员自选","3":"任务自选"},formatter: Table.api.formatter.simmethod},
                        {field: 'fault_names', title: __('故障内容'),formatter: Table.api.formatter.faultname,operate: false},
                        {field: 'createtime', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,formatter: Table.api.formatter.datetime},
                        // {
                        //     field: 'operate', title: __('Operate'), width: 85, events: {
                        //         'click .btn-chooseone': function (e, value, row, index) {
                        //             Fast.api.close({url: row.url, multiple: multiple,task_id:row.task_id,task_name:row.name,fault_name:row.fault_name});
                        //         },
                        //     }, formatter: function () {
                        //         return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                        //     }
                        // }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        task: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'teacher/collection/task/type/' +Config.sim_type+'/ids/'+Config.ids+ location.search,
                }
            });

            var table = $("#table");
            var multiple = true;
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'task_id',
                sortName: 'task_id',
                fixedColumns: true,
                fixedRightNumber: 1,
                singleSelect : true,
                searchFormVisible:true,
                search: false,
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'task_id', title: __('Task_id'),operate: false},
                        {field: 'name', title: __('任务名称'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'sim_type', title: __('Sim_type'),searchList:{"0001":"FZD04B型侦毒器","0002":"FZB006型毒剂报警器","0003":"防化兵用毒剂报警器"},formatter: Table.api.formatter.simtype},
                        {field: 'fault_name', title: __('故障内容'),formatter: Table.api.formatter.faultname},
                        {field: 'createtime', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), width: 85, events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    Fast.api.close({url: row.url, multiple: multiple,task_id:row.task_id,task_name:row.name,fault_name:row.fault_name});
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        faults: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'teacher/collection/faults/type/'+Config.sim_type + location.search,
                }
            });

            var table = $("#table");
            var multiple = true;
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'fault_id',
                sortName: 'fault_id',
                sortOrder:'asc',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:false,
                showExport:false,
                pagination:false,
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'sim_type', title: __('模拟器类型'),operate:false,searchList:{"0001":"FZD04B型侦毒器","0002":"FZB006型毒剂报警器","0003":"防化兵用毒剂报警器"},formatter: Table.api.formatter.simtype},
                        {field: 'parent_name', title: __('故障现象'), operate: false, table: table, class: 'autocontent',},
                        {field: 'name', title: __('故障内容'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {
                        //     field: 'operate', title: __('Operate'), width: 85, events: {
                        //         'click .btn-chooseone': function (e, value, row, index) {
                        //             Fast.api.close({url: row.url, multiple: multiple,task_id:row.fault_id});
                        //         },
                        //     }, formatter: function () {
                        //         return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                        //     }
                        // }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var exam_collection_type  = Config.rowinfo.exam_collection_type;
                var ids = Table.api.selectedids(table);
                if(ids.length!=3 && exam_collection_type==3){
                    Layer.alert('故障内容只允许选择3个');
                    return false
                }
                if(exam_collection_type==1 && ids.length>3){
                    Layer.alert('故障内容最多允许选择3个');
                    return false
                }
                console.log(ids)

                var taskname = [];
                var ptaskids = [];
                var datas = $("#table").bootstrapTable('getSelections');
                $.each(datas,function (index,val) {
                    taskname.push(val.name)
                    // var index = ptaskids.indexOf(val.parent_fault_id);
                    // if (index > -1) {
                    //     Layer.alert('一个故障现象下只允许申请一个故障部位');
                    //     return false
                    // }
                    ptaskids.push(val.parent_fault_id)
                })
                console.log(taskname)
                console.log('taskname')
                console.log(ptaskids);
                var obj = {};
                for (var i = 0; i < ptaskids.length; i++) {
                    var str = ptaskids[i];
                    if (obj[str]) {
                        Layer.alert('一个故障现象下只允许申请一个故障部位');
                        return;
                    } else {
                        obj[str] = str; // 存入对象中做标记
                    }
                }
                Fast.api.close({url: '', multiple: multiple, task_id:ids,task_name:taskname});
            });

            $("button[name=commonSearch]").css('display','none');
        },
        add: function () {
            Controller.api.bindevent1();
        },
        adduser: function () {
            Controller.api.bindevent2();
        },
        edituser: function () {
            Controller.api.bindevent2();
        },
        edit: function () {
            Controller.api.bindevent1();
        },
        api: {
            bindevent1: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            initSubTable: function (index, row, $detail,parent_table) {
                var admin_id = row.id;
                var cur_table = $detail.html('<table id="sub_'+ admin_id +'" style="background-color:#d7d1d147"></table>').find('table');
                var sub_table = $(cur_table);
                var parent_options = parent_table.bootstrapTable("getOptions");
                var parent_selectids = parent_options.selectedIds;
                var checked = false;
                if (parent_selectids.indexOf(admin_id) !== -1) {
                    checked = true;
                }
                parent_options.subSelectedIds[admin_id] = [];
                sub_table.bootstrapTable({
                    // url: 'area/index',
                    toolbar: false,
                    showColumns: false,
                    showToggle: false,
                    showExport: false,
                    search: false,
                    pagination:false,
                    commonSearch: false,
                    sortOrder: 'ASC',
                    checkboxHeader: false,
                    columns: [
                        {checkbox: true,
                            formatter: function(value,rows,index){
                                if(Config.user_ids.length==0){
                                    return false;
                                }else if(Config.user_ids.indexOf(rows.id)>-1){
                                    return true;
                                }else{
                                    return {disabled : true}
                                }
                            }
                        },
                        // {field: 'id', title: 'ID'},
                        {field: 'username', title: __('学号')},
                        {field: 'nickname', title: __('姓名')},
                    ],
                    data: row.alluser
                });
                Table.api.bindevent(sub_table);
                if(checked){
                    sub_table.bootstrapTable("checkAll");
                }else{
                    sub_table.bootstrapTable("uncheckAll");
                }
                sub_table.on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table post-body.bs.table", function (e) {
                    var selectedIds = Table.api.selectedids(sub_table);
                    //     selectedData = Table.api.selecteddata(sub_table);
                    // parent_options.subSelectedIds= [];
                    // parent_options.subSelectedIds[admin_id] = selectedIds;
                    // parent_options.subSelectedData[admin_id] = selectedData;
                    //
                    // var allSubselectIds = [];
                    // var allSubselectData = [];
                    // var allSubselectProjectlib = [];
                    // for (var i in parent_options.subSelectedIds) {
                    //     allSubselectIds.push.apply(allSubselectIds, parent_options.subSelectedIds[i]);
                    // }
                    // for (var j in parent_options.subSelectedData) {
                    //     allSubselectData.push.apply(allSubselectData, parent_options.subSelectedData[j]);
                    // }
                    // parent_options.allSubselectIds = allSubselectIds;
                    // parent_options.allSubselectData = allSubselectData;
                    console.log(selectedIds);
                    $(".xueyuan_input").val(selectedIds.length);
                    $(".xueyuan_total").html(selectedIds.length);
                    $(".depart_ids").val(selectedIds.join());
                });
            },
            bindevent2: function () {
                var rel_Ids = [];
                var qudui_total = 0;
                var xueyuan_total = 0;
                Table.api.init({
                    extend: {
                        index_url: 'department/admin/departadmintotal' + location.search,
                        // index_url: 'auth/admin/admintotal' + location.search,
                    }
                });
                var table = $("#table1");
                table.on('post-body.bs.table', function (e, data) {
                    $('#table1').bootstrapTable('expandAllRows');
                });
                // var oInit = new Object();
                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.index_url,
                    pk: 'id',
                    sortName: 'id',
                    fixedColumns: true,
                    fixedRightNumber: 1,
                    searchFormVisible:false,
                    subSelectedIds: {},
                    subSelectedData: {},
                    allSubselectIds: [],
                    allSubselectData: [],
                    // pagination:false,
                    detailView: true,//父子表
                    Search:false,
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'department_name', title: __('区队名称'), operate: false,width: '400px', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                            {field: 'department_admin_count', title: __('人员数量'),operate: false},
                        ]
                    ],
                    onExpandRow: function (index, row, $detail) {
                        Controller.api.initSubTable(index, row, $detail,table);
                    },
                    onCheck: function (row, $element) {
                        $('.btn-disabled').addClass('disabled');
                        var id = row.id;
                        console.log('选中了')
                        $("#sub_" + id).bootstrapTable("checkAll");
                    },
                    onUncheck: function (row) {
                        var id = row.id;
                        $("#sub_" + id).bootstrapTable("uncheckAll");
                    },
                });

                // 为表格绑定事件
                Table.api.bindevent(table);

                $(document).on('change', '#c-question_setting_method', function () {
                    if($(this).val()==1){
                        $(".btn-sm,.btn-task").css('display','none');
                    }else if($(this).val()==2){
                        $(".btn-sm").show();
                        $(".btn-task").css('display','none');
                    }else if($(this).val()==3){
                        $(".btn-sm").css('display','none');
                        $(".btn-task").show();
                    }
                    $(".question_ids").val(0);
                    $(".task_id").val(0);
                    $("#c-task_name").val('');
                    $("#c-fault_name").val('');
                    $("#c-question_name").val('');
                    $(".tasks,.questions").css('display','none')
                });
                //考题
                $(document).on('click', '.btn-sm', function () {
                    var simtype = $("#c-sim_type").val();
                    if(!simtype){
                        Layer.alert('请选择模拟器类型');
                        return false
                    }
                    var examid = $(".examid").val();
                    var title = '选择考题';
                    Fast.api.open(Fast.api.fixurl("teacher/collection/faults/type/"+simtype+"/ids/"+examid), title, {
                        area: ["85%", "85%"],
                        maxmin: true,
                        moveOut: false,
                        offset: ['40px'],
                        callback: function(value) {
                            if (value.task_id) {
                                $(".questions").css('display','block')
                                $(".question_ids").val(value.task_id);
                                $("#c-question_name").val(value.task_name);
                                $(".tasks").css('display','none')
                                $(".task_id").val(0);
                                $("#c-task_name").val('');
                                $("#c-fault_name").val('');
                            }
                        }
                    });
                });
                //任务
                $(document).on('click', '.btn-task', function () {
                    var simtype = $("#c-sim_type").val();
                    if(!simtype){
                        Layer.alert('请选择模拟器类型');
                        return false;
                    }
                    var examid = $(".examid").val();
                    var title = '选择任务';
                    parent.Fast.api.open(Fast.api.fixurl("teacher/collection/task/type/"+simtype+"/ids/"+examid), title, {
                        area: ["65%", "70%"],
                        maxmin: true,
                        moveOut: false,
                        offset: ['40px'],
                        callback: function(value) {
                            console.log(value);
                            if (value.task_id) {
                                $(".tasks").css('display','block')
                                $(".task_id").val(value.task_id);
                                $("#c-task_name").val(value.task_name);
                                $("#c-fault_name").val(value.fault_name);
                                $(".questions").css('display','none')
                                $(".question_ids").val(0);
                                $("#c-question_name").val('');
                            }
                        }
                    });
                });

                $("button[name=commonSearch]").css('display','none');
                $("input[name='btSelectAll']").css('display','none');
                Form.api.bindevent($("form[role=form]"));
            },
        }
    };
    return Controller;
});
