define(['table', 'upload','form'], function (Table,Upload,Form) {
    var Questionnaire = {
        index: function () {
            window.statuskOption= Config.statusList;
            window.countryList= Config.questionnaire_country;
            var _categoryList = [];
            for (let i = 0; i < Config.categoryList.length; i++) {
                const element = Config.categoryList[i];
                _categoryList.push({
                    value:element.id,
                    label:element.title
                });
            }
            window.categoryList = _categoryList;
            
            Table.api.init({
                extend: {
                    index_url: 'questionnaire/select',
                    add_url: 'questionnaire/insert',
                    edit_url: 'questionnaire/update',
                    del_url: 'questionnaire/delete',
                    multi_url: 'questionnaire/multi',
                    //dragsort_url: 'questionnaire/weigh',
                    table: 'questionnaire',
                }
            });

            var table = $("#table");
            var tableOptions = {
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                search: false,
                columns: [
                    [
                        {checkbox: true},
                        {
                            field: 'id',
                            title: 'ID',
                            filter: "number",
                            sortable: true    // 是否排序
                        },
                        {
                            title: "编号",
                            field: "title",
                            filter: "string",
                        },
                        {
                            title: "分类",
                            field: "category_id",
                            filter: "select",
                            filterOption:'categoryList',
                            formatter:function(v,row){
                                return '<label class="label label-primary">'+row.category.title +'</label>';
                            }
                        },
                        {
                            title: "国家",
                            field: "country",
                            filter: "select",
                            filterOption:'countryList',
                            formatter:function(v,row){
                                return '<label class="label label-info">'+window.countryList[row.country] +'</label>';
                            }
                        },
                        {
                            title: "积分",
                            field: "score",
                            filter: "number",
                            formatter:Table.api.formatter.number
                        },
                        {
                            title: "开始时间",
                            field: "start_time",
                            filter: "datetime",
                            formatter:Table.api.formatter.datetime,
                        },
                        {
                            title: "结束时间",
                            field: "end_time",
                            filter: "datetime",
                            formatter:Table.api.formatter.datetime,
                        },
                        {
                            title: "题目数量",
                            field: "total",
                            filter: "number"
                        },
                        {
                            title: "状态",
                            field: "status",
                            sortable: true,
                            formatter:Table.api.formatter.status,
                            searchList:window.statuskOption,
                            operate:false,
                            filter: "select",
                            filterOption:"statuskOption"
                        },
                        {
                            title: "memo",
                            field: "memo",
                            visible: false,
                        },
                        {
                            title: "创建时间",
                            field: "created_at",
                            visible: false,
                        },
                        {
                            title: "更新时间",
                            field: "updated_at",
                            visible: false,
                        },
                        {field: 'operate', title: '操作', table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            };
            // 初始化表格
            table.bootstrapTable(tableOptions);
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        /**
         * 生成不重复的随机编号
         * 格式：固定9位纯数字，不以0开头
         * @returns {string}
         */
        generateUniqueNo: function() {
            // 生成前6位随机数字，第一位不能为0
            var numbers = '';
            // 第一位生成1-9的随机数字
            numbers += Math.floor(Math.random() * 9) + 1;
            // 后面5位生成0-9的随机数字
            for (var i = 1; i < 6; i++) {
                numbers += Math.floor(Math.random() * 10);
            }
            
            // 添加时间戳后3位确保唯一性
            var timestamp = Date.now().toString();
            var microtime = timestamp.substr(-3);
            
            return numbers + microtime;
        },
        update:function(){
            this.bindevent();
        },
        insert:function(){
            this.bindevent();
            $('#refresh-title').trigger('click');
        },
        bindevent:function(){
            var questionEditor = $('.question-editor');
            function rebuildindex(){
                questionEditor.find('.question-item').each(function(index,ele){
                    var q_index = index +1;
                    $(ele).data('index',q_index);
                    $(ele).find('.question-title>b').html(q_index+'.');
                    $(ele).find('.question-title>input').attr('name','body['+index+'][question]');
                    $(ele).find('.answer-item').each(function(a_index,answer){
                        var _a_index = a_index +1;
                        $(answer).data('index',_a_index);
                        $(answer).find('b').html(String.fromCharCode(64+_a_index)+'.');
                        $(answer).find('input').attr('name','body['+index+'][answer][]');
                    });
                });
                $('[name="total"]').val(questionEditor.find('.question-item').length);
                //console.log(a_index);
            }
            $(document).on('click','.btn-append-answer',function(){
                var dl = $(this).parents('.answer-list');
                var last_anser_node = dl.find('.answer-item:last');
                var html = ['<dd class="list-group-item answer-item" data-index="">',
                        '<b></b>',
                        '<input type="text" name="body[][answer][]" value="" class="form-control" data-rule="required;length(2~100)" />',
                        '<a class="btn btn-danger btn-delete"><i class="mdi mdi-close"></i></a>',
                    '</dd>'];
                if(last_anser_node.length>0){
                    last_anser_node.after(html.join(''));
                }else{
                    dl.prepend(html.join(''));
                }
                rebuildindex();
            });
            $(document).on('click','.btn-append-question',function(){
                var html = [];
                html.push('<dl class="list-group question-item" data-index="">');
                html.push('<dd class="list-group-item m-b-5 question-title">');
                html.push('<b></b>');
                html.push('<input type="text" name="body[][question]" value="" class="form-control" data-rule="required;length(2~100)" />');
                html.push('<a class="btn btn-danger btn-delete"><i class="mdi mdi-close"></i></a>');
                html.push('</dd>');
                html.push('<dd class="list-group-item m-b-5">');
                html.push('<dl class="list-group answer-list">');
                for(var index=1;index<=4;index++){
                    html.push('<dd class="list-group-item answer-item" data-index="">');
                    html.push('<b>');
                    html.push('.</b>');
                    html.push('<input type="text" name="body[][answer][]" value="" class="form-control" data-rule="required;length(2~100)" />');
                    html.push('<a class="btn btn-danger btn-delete"><i class="mdi mdi-close"></i></a>');
                    html.push('</dd>');
                }
                html.push('<dd class="m-l-15">');
                html.push('<a href="javascript:;" class="btn btn-sm btn-success btn-append-answer m-t-5  m-l-15"><i class="fa fa-plus"></i> 添加答案</a>');
                html.push('</dd>');
                html.push('</dl>');
                html.push('</dd>');
                html.push('</dl>');
                console.log(questionEditor.find('.question-item:last'));
                if(questionEditor.find('.question-item:last').length>0){
                    questionEditor.find('.question-item:last').after(html.join(''));
                }else{
                    questionEditor.prepend(html.join(''));
                }
                rebuildindex();
            });
            $(document).on('click','.btn.btn-delete',function(){
                if($(this).parent().hasClass('answer-item')){
                    $(this).parent().remove();
                    rebuildindex();
                }else{
                    $(this).parents('.question-item').remove();
                    rebuildindex();
                }
            });
            $(document).on('click','#refresh-title',function(){
                var no = Questionnaire.generateUniqueNo();
                $('[name="title"]').val(no);
            });
            if($('.question-item').length == 0){
                $('.btn-append-question').trigger('click');
            }else{
                rebuildindex();
            }
            var form = $('form');
            Form.api.bindevent(form);
        }
    };
    return Questionnaire
});