$(function () {
    /*表单验证：begin*/
    //自定义规则，用法：验证元素上加class="js-pattern-sort"
    if ($.AMUI && $.AMUI.validator) {
        $.AMUI.validator.patterns.sort = /^([0-9]+)$/;
    }
    $("#tmpForm").validator({
        // 域通过验证时回调
        onValid: function (validity) {
            $(validity.field).closest('.am-form-group').find('.am-alert').hide();
        },
        // 域验证通过时添加的操作，通过该接口可定义各种验证提示
        markValid: function (validity) {
            // this is Validator instance
            var $field = $(validity.field);
            //add by zxl，只对有required属性的字段进行验证
            if (typeof($field.attr("required")) != "undefined") {
                var options = this.options;
                var $parent = $field.closest('.am-form-group');
                $field.addClass(options.validClass).removeClass(options.inValidClass);

                $parent.addClass('am-form-success').removeClass('am-form-error');

                options.onValid.call(this, validity);
            }
        },
        // 验证出错时的回调， validity 对象包含相关信息，格式通 H5 表单元素的 validity 属性
        onInValid: function (validity) {
            var $field = $(validity.field);
            var $group = $field.closest('.am-form-group');
            var $alert = $group.find('.am-alert');
            // 使用自定义的提示信息 或 插件内置的提示信息
            var msg = $field.data('validationMessage') || this.getValidationMessage(validity);

            if (!$alert.length) {
                $alert = $("<div class='am-alert am-alert-danger'></div>").hide().appendTo($group.find(".input-msg"));
            }
            console.log("onInValid : " + $field.val());
            $alert.html(msg).show();
        }
    });
    /*表单验证：end*/

    /*滑动按钮 begin*/
    $("#switch").on({
        'switchChange.bootstrapSwitch': function (event, state) {
            if (state.toString() == "true") {
                $("#isEnable").val("1");
            } else {
                $("#isEnable").val("0");
            }
        }
    });
    /*滑动按钮 end*/

    generateFileupload('icon');
    generateFileupload('backgroundImage');

    var banner_div = $(".banner_div");
    for (var i = 1; i <= banner_div.length; i++) {
        generateFileupload('banner-' + i);
    }

    if ($("#deployMethodVal").val() == 1) {
        $("#remark").hide();
    }


    $("#submitBtn").click(function () {
        checkFormField();
    });
});


var checkFormField = function () {
    if ($("#sort").val().length == "") {
        parent.layer.msg("请输入排序");
        return;
    }

    var checkID = [];//定义一个空数组
    $("input[name='at']:checked").each(function(i){//把所有被选中的复选框的值存入数组
        checkID[i] =$(this).val();
    });
    if(checkID.length == 0) {
        parent.layer.msg("请选择权限配置");
        return;
    }else if(checkID.length == 1){
        $("#authType").val(checkID[0]);
    }else if(checkID.length == 2) {
        $("#authType").val(3);// 设置authType=3 表示校园渠道和泛渠道可见
    }

    if($("#packageIds").val() == "") {
        parent.layer.msg("请至少选择一个业务");
        return;
    }

    $("#tmpForm").submit();
};

/*ueditor 编辑器 begin*/
//酬金规则
var ue = UE.getEditor('detail', {
    toolbars: [
        [
            'fullscreen', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript',
            'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
            'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'emotion', 'scrawl',
            'pagebreak', 'template', '|',
            'horizontal', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittocols', '|'
        ]
    ],
    maximumWords: 500
});

//业务规则
var ue2 = UE.getEditor('businessRule', {
    toolbars: [
        [
            'fullscreen', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript',
            'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
            'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'emotion', 'scrawl',
            'pagebreak', 'template', '|',
            'horizontal', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittocols', '|'
        ]
    ],
    maximumWords: 800
});

//业务简介
var ue3 = UE.getEditor('businessIntro', {
    toolbars: [
        [
            'fullscreen', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript',
            'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
            'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'emotion', 'scrawl',
            'pagebreak', 'template', '|',
            'horizontal', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittocols', '|'
        ]
    ],
    maximumWords: 800
});

//业务详情
var ue4 = UE.getEditor('businessDetail', {
    toolbars: [
        [
            'fullscreen', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript',
            'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
            'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'emotion', 'scrawl',
            'pagebreak', 'template', '|',
            'horizontal', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittocols', '|'
        ]
    ],
    maximumWords: 800
});

var addBanner = function () {
    var banner_div = $(".banner_div");
    var index = banner_div.length + 1;
    if (index > 5) {
        parent.layer.msg("banner配置过多，无法再继续配置");
        return;
    }
    var bannerId = 'banner-' + index;
    var html = '<div class="banner_div" id="banner_div_' + index + '">' +
        '<div class="am-g am-form-group am-margin-top">' +
        '<div class="am-u-sm-4 am-u-md-2 am-text-right banner_url_config"><span style="color: red;">*</span>banner配置' + index +
        '</div>' +
        '<div class="am-u-sm-6 am-u-md-6">' +
        '<input type="text" id="' + bannerId + '" name="' + bannerId + '" maxlength="500" value="" required placeholder="请上传banner（ *.gif,*.jpg,*.jpeg,*.png ）"/>' +
        ' </div>' +

        ' <div class="am-form-file am-text-xs">' +
        ' <button type="button" class="am-btn am-btn-primary am-btn-sm">' +
        '    <i class="am-icon-cloud-upload"></i> 上传' +
        '  </button>' +
        ' <input id="fileupload_button_' + bannerId + '" type="file" name="files[]" multiple>' +
        ' </div>' +
        ' <div id="progress-area-' + bannerId + '" class="am-margin-top-sm am-hide">' +
        '<div id="progress-text-' + bannerId + '" class="am-text-xs am-text-right"></div>' +
        '    <div class="am-progress am-progress-xs">' +
        '   <div class="am-progress-bar" style="width: 0%"></div>' +
        '   </div>' +
        '   </div>' +
        '   </div>' +
        '   <div class="am-g am-form-group am-margin-top">' +
        '   <div class="am-u-sm-4 am-u-md-2 am-text-right">banner链接地址' + index + '</div>' +
        '   <div class="am-u-sm-6 am-u-md-6">' +
        '  <input type="text" class="am-input"  data-validate-asyncdata-validation-message="banner链接地址"' +
        ' name="banner-link-' + index + '" placeholder="banner链接地址"' +
        ' value="" />' +
        '  </div>' +
        '  <div class="am-u-sm-2 am-u-md-4">' +
        ' <button type="button" onclick="deleteBanner(' + index + ')" class="am-btn am-btn-primary am-btn-sm">' +
        '<i class="am-icon-minus-square"></i>' +
        ' </button>' +
        '</div>' +
        '   </div> </div>';

    $("#bannerContainer").append(html);
    generateFileupload(bannerId);
};

var deleteBanner = function (id) {
    $("#banner_div_" + id).remove();
};

function cheakContent(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字而不是
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
}

var generateFileupload = function (name) {
    var progressArea = $("#progress-area-" + name);//div
    var progressText = $("#progress-text-" + name);//进度条提示
    var progressBar = $(".am-progress-bar");//进度条

    $("#fileupload_button_" + name).fileupload({
        url: base + "/file/upload",
        dataType: 'json',
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 10 * 1024 * 1024,
        maxNumberOfFiles: 1,
        messages: {
            maxFileSize: '最大允许上传的图片大小为10M',
            acceptFileTypes: '文件格式不正确，请上传gif、jpg、jpeg、png类型的图片文件'
        },
        start: function (e) {
            progressArea.removeClass("am-hide");
            progressText.removeClass("am-text-danger");
            progressText.html("");
            progressBar.css("width", "0%");
        },
        done: function (e, data) {
            console.log(data);
            //设置服务器返回的url
            $("#" + name).val(data.result.data);
            setTimeout(function () {
                progressArea.addClass("am-hide");
            }, 1500);
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            console.log(progress);
            progressBar.css("width", progress + "%");
            progressText.html(progress + "%");
        },
        error: function (jqXHR2, textStatus, errorThrown) {
            progressArea.removeClass("am-hide");
            progressText.addClass("am-text-danger");
            progressText.html("imageupload error！");
            progressBar.css("width", "0%");
            setTimeout(function () {
                progressArea.addClass("am-hide");
            }, 2000);
        },
        fail: function (jqXHR2, textStatus) {
            progressArea.removeClass("am-hide");
            progressText.addClass("am-text-danger");
            progressText.html("imageupload fail！");
            progressBar.css("width", "0%");
            setTimeout(function () {
                progressArea.addClass("am-hide");
            }, 2000);
        },
        processfail: function (e, data) {
            var currentFile = data.files[data.index];
            if (data.files.error && currentFile.error) {
                parent.layer.msg(currentFile.error);
            }
        }
    });
};

var unCheckAuthType2 = function (type) {
    if (2 == type) {
        $("#authType0").prop("checked", false);
        $("#authType1").prop("checked", false);
    } else {
        $("#authType2").prop("checked", false);
    }
};

var changeMethod = function () {
    if ($('input[name="deployMethod"]:checked').val() == 0) {
        $("#remark").show();
    } else {
        $("#remark").hide();
    }
};

