/**
 * 自定义表单
 * @author pingyx
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'ztree', 'horizonTable', 'horizonFormtree', 'jqueryValidateAll', 'jqueryForm', 'chosenJquery', 'gritter'], factory);
    } else {
        factory(jQuery);
    }
}(function ($) {
    "use strict";

    var $dialog = $('#dialog-default');

    var _height = {
        outerHeight: function () {
            var _height = horizon.tools.getPageContentHeight(),
                $pageHeader = $('.page-header');
            if ($pageHeader.css('display') != 'none') {
                _height -= $pageHeader.outerHeight(true);
            }
            _height -= $('#formData').outerHeight(true);
            return _height;
        },
        treeHeight: function () {
            var outerHeight = this.outerHeight();
            var $container = $('.formtree-widget-box');
            return outerHeight - parseInt($container.css('borderTopWidth')) * 2
                - parseInt($container.find('.modal-body').css('paddingTop')) * 2
                - $container.find('.widget-header').outerHeight(true);
        },
    };
    var formtree = {
        group: '',
        init: function () {
            //初始化表单树
            var $formTree = $('#form-tree');
            $formTree.formtree({
                data: {
                    type: 'form'
                },
                defaultNode: [
                    {
                        id: 'createForm',
                        type: 'item',
                        text: horizon.lang.base["new"]
                    }
                ],
                defaultNodePosition: 'top',
                selected: formtree.selected,
                deselected: formtree.deselected,
                opened: formtree.selGroup,
                closed: formtree.selGroup
            });
        },
        selected: function () {
            if (arguments[1].target.id == 'createForm') {
                operate.initFormInfo();
            } else {
                formtree.group = arguments[1].target.text
                table.mytable.setTitle(arguments[1].target.text);
                operate.initFormInfo(arguments[1].target.id);
            }
        },
        deselected: function () {
            $(arguments[1].el).addClass('tree-selected');
        },
        selGroup: function () {
            $(arguments[0].target).find('.tree-item.tree-selected').removeClass('tree-selected');
            formtree.group = arguments[1].group;
        },
        reload: function () {
            $('#form-tree').formtree('reload');
        }

    };
    var selectTable = {
        tables: [],
        defsel: "",
        setting: {
            check: {
                enable: true,
                chkboxType: {"Y": "s", "N": "s"}
            },
            async: {
                url: horizon.tools.formatUrl('/simpleform/dataTable/list'),
                enable: true,
                dataType: "json",
                type: "post",
                open: "true",
                otherParam: {
                    dataSource: $('select[name="dataSource"]').val()
                }
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            view: {
                dblClickExpand: false,
                showIcon: false,
                showLine: false,
                selectedMulti: true
            },
            callback: {
                onCheck: function (e, treeId, treeNode) {
                    if (treeNode.checked && $.inArray(treeNode.id, selectTable.tables) < 0) {
                        selectTable.tables.push(treeNode.id);
                    } else {
                        selectTable.tables.splice($.inArray(treeNode.id, selectTable.tables), 1);
                    }
                    $('#formTable').val(selectTable.tables.join(";"));
                },
                onAsyncSuccess: function () {
                    var zTree = $.fn.zTree.getZTreeObj("table-tree")
                    var nodes = zTree.getNodes();
                    var checks = selectTable.defsel.split(";")
                    for (var i = 0; i < nodes.length; i++) {
                        var node = nodes[i];
                        if ($.inArray(node.id, checks) > -1) {
                            if ($.inArray(node.id, selectTable.tables) < 0) {
                                selectTable.tables.push(node.id);
                            }
                            zTree.checkNode(node, true, true);
                        }

                    }
                }
            }
        },
        init: function (value, dataSource) {
            var $tableTree = $('#table-tree');
            selectTable.setting.async.otherParam.dataSource = dataSource;
            selectTable.defsel = value;
            $.fn.zTree.init($tableTree, selectTable.setting);
        }
    };
    var table = {
        formFields: [],
        checkSelectedRow: function () {
            if (table.mytable.checkRowKeyArray.length) return true;
            var errorGritter = function () {
                horizon.notice.error(horizon.lang.message["deleteHelp"]);
            };
            if ($('.gritter-item-wrapper').length > 0) {
                errorGritter();
            } else {
                errorGritter();
            }
            return false;
        },
        init: function () {
            table.mytable = $('#formFieldDataTable').horizonTable({
                settings: {
                    title: "",
                    height: _height.outerHeight,
                    searchable: false,
                    columns: [
                        {
                            name: 'id',
                            columnClass: 'hidden',

                        },
                        {
                            name: 'formId',
                            columnClass: 'hidden',

                        },
                        {
                            name: 'dataSource',
                            title: horizon.lang["form-simpleform"]["dataSource"],
                            width: '200px',
                            orderable: false,
                        },
                        {
                            name: 'tableId',
                            title: horizon.lang["form-simpleform"]["formTable"],
                            width: '200px',
                            orderable: false,
                        },
                        {
                            name: 'fieldId',
                            title: horizon.lang["form-simpleform"]["colunmName"],
                            width: '200px',
                            orderable: false,
                        },
                        {
                            name: 'fieldName',
                            title: horizon.lang["form-simpleform"]["cnName"],
                            width: '300px',
                            columnClass: 'center',
                            orderable: false,
                        },
                        {
                            name: 'orderNo',
                            columnClass: 'hidden',
                        }
                    ],
                    buttons: [
                        {
                            id: 'import',
                            text: horizon.lang['form-simpleform']['fieldReset'],
                            icon: 'fa fa-share red2',
                            fnClick: function () {
                                table.reloadTable(true)
                            }
                        },
                        {
                            id: 'save',
                            text: horizon.lang['base']['save'],
                            icon: 'fa fa-save green',
                            fnClick: function () {
                                operate.checkForm()
                                $('#formData-container').submit();
                            }
                        },
                        {
                            id: 'delete',
                            text: horizon.lang['base']['delete'],
                            icon: 'fa fa-times red2',
                            fnClick: function () {
                                $dialog.dialog({
                                    closeText: horizon.lang['base']['close'],
                                    title: horizon.lang['message']['title'],
                                    dialogText: horizon.lang['form-simpleform']['sureDelete'],
                                    dialogTextType: 'alert-danger',
                                    buttons: [
                                        {
                                            html: horizon.lang['base']['ok'],
                                            "class": "btn btn-primary btn-xs",
                                            click: function () {
                                                var formId = $('#formData').find('input[name="id"]').val();
                                                if (formId == undefined || formId.trim() == "") {
                                                    $(this).dialog("close");
                                                    return;
                                                }
                                                $.ajax({
                                                    url: horizon.tools.formatUrl('/simpleform/delete'),
                                                    dataType: 'json',
                                                    type: 'post',
                                                    cache: false,
                                                    data: {
                                                        'formId': formId
                                                    },
                                                    error: function () {
                                                        horizon.notice.error(horizon.lang["message"]["operateError"]);
                                                    },
                                                    success: function () {
                                                        horizon.notice.success(horizon.lang["message"]["deleteSuccess"]);
                                                        operate.initFormInfo();
                                                        formtree.reload();
                                                    }
                                                });
                                                $(this).dialog("close");
                                            }
                                        }
                                    ]
                                });
                            }
                        }
                    ],
                    fnCreateCell: function (nTd, nTdData, rowData, iRow, i) {
                        var _html = '';
                        if (i == 2) {
                            var dataSource = $('select[name="dataSource"]').val();
                            if (dataSource == null) {
                                _html = '<span style="color: red" title="' + horizon.lang['form-simpleform']['dataSourceNotExist']+'">' + rowData.dataSource + '</span>';
                                var $ntd = $(nTd);
                                $ntd.html(_html);
                            }
                        }
                        if (i == 5) {//操作列
                            table.formFields.push(rowData);
                            _html = '<input type="text"  name="fieldCNName" value="' + rowData.fieldName + '" placeholder="'+horizon.lang["message"]["input"]+'">';
                            var $ntd = $(nTd);
                            $ntd.html(_html);
                            $ntd.find('input[name="fieldCNName"]').on('change', function () {
                                rowData.fieldName = $(this).val();
                                //先移除 再增加
                                var index = $.inArray(rowData, table.formFields)
                                if (index < 0) {
                                    table.formFields.push(rowData);
                                } else {
                                    table.formFields.splice(index, 1)
                                    table.formFields.push(rowData);
                                }
                            });
                        }
                    },
                },
                serverSideData: false
            });
            $('#formFieldData-container').find('.dataTables_header').addClass('hidden');
            var $dataTablesContainer = table.mytable.getPlaceholder().closest('.dataTables_widgetbox');
            $dataTablesContainer.unbind().on('reload.ace.widget', function () {
                table.reloadTable(false);
            });
            table.reloadTable(false);
        },
        reloadTable: function (inFlag) {
            if (inFlag == true && $('#formTable').val() == "") {
                horizon.notice.error(horizon.lang['form-simpleform']['selectTable']);
            } else {
                table.formFields = [];
                var data = $('#formData-container').serializeArray();
                table.mytable.showProcessing();
                data.push({name: 'import', value: inFlag});
                $.ajax({
                    url: horizon.tools.formatUrl('/simpleform/field/list'),
                    cache: false,
                    dataType: 'json',
                    type: 'post',
                    data: data,
                    success: function (data) {
                        table.mytable.hideProcessing();
                        table.mytable.pluginTable.fnClearTable(false);
                        var fields = data.data;
                        if (fields != undefined) {
                            for (var i = 0; i < fields.length; i++) {
                                var item = fields[i];
                                table.mytable.pluginTable.fnAddData(item, false);
                            }
                        }
                        table.mytable.reload();
                    },
                    error: function () {
                        let d1 = d;
                        $.gritter.add({
                            title: horizon.lang['message']['titleInfo'],
                            text: horizon.lang['message']['readFail'],
                            class_name: 'gritter-error'
                        });
                        table.mytable.hideProcessing();
                    }
                });
            }
        }
    };
    var operate = {
        init: function(){
            $.validator.addMethod("checkName", function(value, element, param) {
                return this.optional(element)|| /^[A-Za-z0-9\u4e00-\u9fa5]+$/g.test(value)
            }, horizon.lang['form-simpleform']['formNameCheck']);
            $.validator.addMethod("checkUrl", function(value, element, param) {
                return this.optional(element)|| /^\/([\u4E00-\u9FA5A-Za-z0-9_]+\/?)+([\u4E00-\u9FA5A-Za-z0-9_.])+\.ftl$/g.test(value)
            }, horizon.lang['form-simpleform']['formUrlCheck']);
        },
        initFormInfo: function (value) {
            $('#formData-container')[0].reset();
            $('#formData-container').find('input[type="hidden"]').val('');
            $('#formName-error').closest('.form-group').removeClass('has-error');
            $('#formName-error').html("");
            $("#table-tree").on("click", function (e) {
                e.stopPropagation();
            });
            $('select[name="dataSource"]').on('change', function () {
                $('#formTable').val("");
                selectTable.defsel = "";
                selectTable.tables = [];
                table.formFields = [];
            });
            $("input[name='formTable']").unbind(horizon.tools.clickEvent()).bind(horizon.tools.clickEvent(), function () {
                $("#table-tree").css("display", "block;");
                var formTable = $('#formTable').val();
                var dataSource = $('select[name="dataSource"]').val();
                if (dataSource == "") {
                    horizon.notice.error(horizon.lang['form-simpleform']['selectDatasource']);
                }
                if (formTable && formTable.length > 0){
                    selectTable.tables = formTable.split(";");
                }
                selectTable.init(formTable, dataSource);
            });
            $(".help-word").bind(horizon.tools.clickEvent(), function () {
                window.open(horizon.paths.syspath + "/manager/form/self.form.template.jsp.html");
            });
            if(value){
                $.ajax({
                    url: horizon.tools.formatUrl('/simpleform/form'),
                    dataType: 'json',
                    type: 'post',
                    cache: false,
                    data: {formId: value},
                    error: function () {
                        horizon.notice.error(horizon.lang['message']['operateError']);
                    },
                    success: function (data) {
                        if (data != null) {
                            $('#formData-container').find('input[name="id"]').val(data.id);
                            $('#formData-container').find('input[name="formName"]').val(data.formName);
                            $('#formData-container').find('input[name="formUrl"]').val(data.formUrl);
                            $('#formData-container').find('input[name="formTable"]').val(data.formTable);
                            operate.initFormGroup(data.formGroup)
                            operate.initDataSaurce(data.dataSource);
                        } else {
                            $('#formData-container').find('input[name="id"]').val("");
                            $('#formData-container').find('input[name="formName"]').val("");
                            $('#formData-container').find('input[name="formUrl"]').val("");
                            $('#formData-container').find('input[name="formTable"]').val("");
                            operate.initFormGroup("")
                            operate.initDataSaurce("");
                        }
                        if (!('placeholder' in document.createElement('input'))) {
                            operate.replacePlaceHolder();
                        }
                    }
                });
            }else {
                operate.initFormGroup("")
                operate.initDataSaurce("");
            }

        },
        replacePlaceHolder: function () {
            $("[placeholder]").each(function () {
                var _this = $(this);
                var left = _this.css("padding-left");
                _this.parent().append('<span class="placeholder" data-type="placeholder" style="left: ' + left + '">' + _this.attr("placeholder") + '</span>');
                if (_this.val() != "") {
                    _this.parent().find("span.placeholder").hide();
                }
                else {
                    _this.parent().find("span.placeholder").show();
                }
            }).on("focus", function () {
                $(this).parent().find("span.placeholder").hide();
            }).on("blur", function () {
                var _this = $(this);
                if (_this.val() != "") {
                    _this.parent().find("span.placeholder").hide();
                }
                else {
                    _this.parent().find("span.placeholder").show();
                }
            });
            // 点击表示placeholder的标签相当于触发input
            $("span.placeholder").on("click", function () {
                $(this).hide();
                $(this).siblings("[placeholder]").trigger("click");
                $(this).siblings("[placeholder]").trigger("focus");
            });
        },
        initFormGroup: function (value) {
            var $formGroup = $('select[name="formGroup"]');
            $formGroup.children().remove();
            $.ajax({
                url: horizon.tools.formatUrl('/simpleform/group/list'),
                dataType: 'json',
                type: 'post',
                cache: false,
                error: function () {
                    horizon.notice.error(horizon.lang['message']['operateError']);
                },
                success: function (data) {
                    $formGroup.append('<option value=""></option>');
                    $.each(data, function (i, group) {
                        var $option;
                        if (group == "empty") {
                            group = horizon.lang["base"]["noCategory"];
                            $option = $('<option value="empty">' + group + '</option>');
                        } else {
                            $option = $('<option value="' + group + '">' + group + '</option>');
                        }
                        $formGroup.append($option);
                    });
                    if (value) {
                        $formGroup.val(value);
                    }
                    if ($formGroup.data('chosen')) {
                        $formGroup.trigger('chosen:updated');
                    } else {
                        $formGroup.chosen({
                            allow_single_deselect: true,
                            no_results_text: horizon.lang["form-simpleform"]["noresult"] + ('<label class="blue">[' + horizon.lang["form-simpleform"]["add"] + ']</label>')
                        })
                    }
                    ;

                    //允许新增
                    var $chosenContainer = $formGroup.next();
                    $chosenContainer.find('input').on('keyup', function (e) {
                        var code = e.which || e.keyCode;
                        var $input = $(this);
                        var val = $input.val();
                        if (code != 13 || !val) return;
                        if (!(/^[A-Za-z0-9\u4e00-\u9fa5]+$/g.test(val))){
                            horizon.notice.error(horizon.lang["form-simpleform"]["formNameCheck"])
                            return;
                        }
                        if ($chosenContainer.find('.chosen-results > .no-results').length) {
                            $formGroup.append('<option value="' + val + '" selected>' + val + '</option>');
                            $formGroup.trigger('chosen:updated.chosen');
                            $formGroup.trigger('change');
                        }
                    });

                }
            });
        },
        initDataSaurce: function (value) {
            var $dataSource = $('select[name="dataSource"]');
            $dataSource.children().remove();
            $.ajax({
                url: horizon.tools.formatUrl('/system/datasource/list'),
                dataType: 'json',
                type: 'post',
                cache: false,
                error: function () {
                    horizon.notice.error(horizon.lang['message']['operateError']);
                },
                success: function (data) {
                    $dataSource.append('<option value=""></option>');
                    $.each(data, function (i, dataSource) {
                        var $option = $('<option value="' + dataSource + '">' + dataSource + '</option>');
                        $dataSource.append($option);
                    });
                    if (value) {
                        $dataSource.val(value);
                    }
                    if ($dataSource.data('chosen')) {
                        $dataSource.trigger('chosen:updated');
                    } else {
                        $dataSource.chosen({
                            no_results_text: horizon.lang['form-simpleform']['noFind'],
                            allow_single_deselect: true
                        });
                    }
                    table.reloadTable(false);
                }
            });
        },
        checkForm: function () {
            return $('#formData-container').validate({
                rules: {
                    formName: {
                        checkName: true,
                        rangelength: [2,32],
                        remote: {
                            url: horizon.tools.formatUrl('/simpleform/formName/check'),
                            cache: false,
                            data: {
                                formName: function () {
                                    return $('#formData-container').find('input[name="formName"]').val();
                                },
                                id: function () {
                                    return $('#formData-container').find('input[name="id"]').val();
                                }
                            }
                        },

                    },
                    formUrl:{
                        checkUrl: true,
                    },
                    formGroup:{
                        checkName: true,
                        rangelength:[2,32]
                    }
                },
                messages: {
                    formName: {
                        remote: horizon.lang['form-simpleform']['formNameExists'],
                    },
                },
                errorClass: 'help-block col-xs-12 col-sm-reset inline',
                errorPlacement: function (error, element) {
                    //error.insertAfter(element.closest('div[class*="col-"]'));
                    element.closest('div[class*="col-"]').append(error);
                },
                highlight: function (e) {
                    $(e).closest('div').addClass('has-error');
                },
                success: function (e) {
                    $(e).closest('div').removeClass('has-error');
                    $(e).remove();
                },
                submitHandler: function (form) {
                    var formTable = $('#formData-container').find('input[name="formTable"]').val();
                    if (!formTable){
                        horizon.notice.error(horizon.lang["form-simpleform"]["notSelectTable"]);
                        return;
                    }
                    if (!table.formFields.length){
                        horizon.notice.error(horizon.lang["form-simpleform"]["notTableField"]);
                        return;
                    }
                    var data = $('#formData-container').serializeArray();
                    data.push({name: 'formFields', value: JSON.stringify(table.formFields)});
                    $.ajax({
                        url: horizon.tools.formatUrl('/simpleform/save'),
                        dataType: 'json',
                        type: 'post',
                        cache: false,
                        data: data,
                        error: function () {
                            horizon.notice.error(horizon.lang["message"]["operateError"]);
                        },
                        success: function (data) {
                            if(data.restype == "success"){
                                $('input[name="id"]').val(data.msg[0]);
                                formtree.reload();
                                horizon.notice.success(horizon.lang["message"]["saveSuccess"]);
                            }else {
                                horizon.notice.error(data.msg ? data.msg[0] :horizon.lang["message"]["saveFail"]);
                            }
                        }
                    });
                }
            });
        },
    };
    if (!horizon.vars.touch) {
        $(window)
            .off('resize.chosen')
            .on('resize.chosen', function () {
                $('.chosen-select').each(function () {
                    var $this = $(this);
                    $this.next('.chosen-container').css({'width': $this.parent().width()});
                })
            }).trigger('resize.chosen');
    }
    ;
    return horizon.engine['simpleform'] = {
        init: function () {
            formtree.init();
            operate.init();
            operate.initFormInfo();
            operate.checkForm()
            table.init();
        }
    };
}));