$(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*/
    var $mycheckbox = $('.switch-button');
    $mycheckbox.each(function () {
        $("#switch").on({
            'switchChange.bootstrapSwitch': function (event, state) {
                if (state.toString() == "true") {
                    $("#isEnable").val("0");
                } else {
                    $("#isEnable").val("1");
                }
            }
        });
    });
    /*滑动按钮 end*/

    generateFileupload('miniIcon');
    generateFileupload('icon');
    generateFileupload('backgroundImage');
    generateFileupload('detailUrl');

    categoryChange();

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

var categoryChange = function () {
    var categoryId = $("#categoryId").val();
    if ('1' == categoryId) {
        $("#discountsDiv").css("display", "none");//隐藏div
    } else {
        $("#discountsDiv").css("display", "block");//显示div
    }
    // 5为合家欢，隐藏酬金显示办理酬金
    if ("5"== categoryId){
        $("#salarysDiv").css("display", "none");//隐藏div
        $("#activateSalarySpan").html("办理酬金");
        $("#activateSalary").attr("data-validation-message","请输入办理酬金");
        $("#activateSalary").attr("placeholder","请输入办理酬金");
    } else {
        $("#salarysDiv").css("display", "block");//显示div
        $("#activateSalarySpan").html("激活酬金");
        $("#activateSalary").attr("data-validation-message","请输入激活酬金");
        $("#activateSalary").attr("placeholder","请输入激活酬金");
    }
};

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();
};

var addFlowPackage = function () {
    var package_div = $(".package_div");
    var index = package_div.length + 1;
    if (index > 6) {
        parent.layer.msg("资费配置过多，无法再继续配置");
        return;
    }
    var bannerId = 'package-' + index;
    var html = '<div class="package_div" id="package_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"><span                           ' +
        '                style="color: red;">*</span>资费名称 '+index+'                                  ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <input type="text" id="packageName-'+index+'" class="am-input"                       ' +
        '                   data-validate-async                                                 ' +
        '                   data-validation-message="请输入资费名称"                            ' +
        '                   name="packageName-'+index+'" placeholder="请输入资费名称" maxlength="30"      ' +
        '                   value="" required/>                    ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></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">                                ' +
        '            <span style="color: red;">*</span>资费代码 '+index+'                                   ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <input name="packageCode-'+index+'" class="js-ajax-validate package-code-input"                         ' +
        '                   data-validate-async data-validation-message="请输入资费代码"        ' +
        '                   type="text" id="packageCode-'+index+'"                                        ' +
        '                   value="" minlength="1"                 ' +
        '                   maxlength="20" placeholder="请输入资费代码" required                ' +
        '            />                                                                         ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"                                     ' +
        '             id="package_code_valid"></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"><span                           ' +
        '                style="color: red;">*</span>资费简介   '+index+'                                   ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <input type="text" id="packageBrief-'+index+'" class="am-input"                      ' +
        '                   data-validate-async                                                 ' +
        '                   data-validation-message="请输入资费简介"                            ' +
        '                   name="packageBrief-'+index+'" placeholder="请输入资费简介" maxlength="16"     ' +
        '                   value="" required/>                   ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></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">                                ' +
        '            资费说明                                       '+index+'                               ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <textarea rows="3" cols="20" id="packageInstructions-'+index+'"                      ' +
        '                      class="am-input" data-validate-async                             ' +
        '                      data-validation-message="请输入资费说明"                         ' +
        '                      name="packageInstructions-'+index+'"                                       ' +
        '                      placeholder="请输入资费说明"                      ' +
        '            required></textarea>                    ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></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">首笔酬金'+index+'   </div>                  ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <input type="text" id="firstSalary-'+index+'" class="am-input"                       ' +
        '                   data-validate-async                                                 ' +
        '                   data-validation-message="请输入首笔酬金"                            ' +
        '                   name="firstSalary-'+index+'" placeholder="请输入首笔酬金"                     ' +
        '                   onkeyup="cheakContent(this);" />                  ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></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">第二笔酬金'+index+'   </div>                ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <input type="text" id="secondSalary-'+index+'" class="am-input"                      ' +
        '                   data-validate-async                                                 ' +
        '                   data-validation-message="第二笔酬金"                                ' +
        '                   name="secondSalary-'+index+'" placeholder="第二笔酬金"                        ' +
        '                   onkeyup="cheakContent(this);"/>                                        ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></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">第三笔酬金'+index+'   </div>                ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '            <input type="text" id="thirdSalary-'+index+'" class="am-input"                       ' +
        '                   data-validate-async                                                 ' +
        '                   data-validation-message="第三笔酬金"                                ' +
        '                   name="thirdSalary-'+index+'" placeholder="第三笔酬金"                         ' +
        '                   onkeyup="cheakContent(this);"   />                                     ' +
        '        </div>                                                                         ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></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">' +
        '            <button type="button" onclick="deleteFlowPackage('+index+')"    ' +
        '                    class="am-btn am-btn-primary am-btn-sm">                           ' +
        '                <i class="am-icon-minus-square">删除</i>                               ' +
        '</div>                ' +
        '        <div class="am-u-sm-6 am-u-md-6">                                              ' +
        '        <div class="am-u-sm-2 am-u-md-4 input-msg"></div>                              ' +
        '        </div>                                                                         ' +
    '    </div>                                                                             '
    +'</div>';
    $("#packageContainer").append(html);
};


var deleteFlowPackage = function (id) {
    var package_div = $(".package_div");
    var index = package_div.length + 1;
    console.log("deleteFlowPackage");
    console.log(index);
    if (index <= 2) {
        parent.layer.msg("资费不能为空！");
        return;
    }
    $("#package_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 checkFormField = function () {
    if (ue.getContentLength(true) > 500 || ue.getContentLength() > 1000) {
        parent.layer.msg("酬金规则过长");
        return false;
    }
    // var categoryId = $("#categoryId").val();
    if (ue2.getContent() == "") {
        parent.layer.msg("请输入业务规则");
        return false;
    }

    if (ue3.getContent() == "") {
        parent.layer.msg("请输入图文详情");
        return false;
    }

    if (ue2.getContentLength(true) > 1000 || ue2.getContentLength() > 2000) {
        parent.layer.msg("业务规则过长");
        return false;
    }

    if (ue3.getContentLength(true) > 1000 || ue3.getContentLength() > 2000) {
        parent.layer.msg("图文详情过长");
        return false;
    }

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

    var preferentialFlowId = $("#preferentialFlowId").val();
    var packageCodeList = $(".package-code-input");
    console.log(packageCodeList);
    var list = [];
    $.each(packageCodeList, function(index, item) {
        list.push($(item).val().trim());
    });
    var tempStr = list.join(',') + ',';
    try {
        list.forEach(function(value, index) {
            var packageCode = value;
            console.info('当前值：', preferentialFlowId);
            if (tempStr.replace(packageCode + ',', '').indexOf(packageCode + ',') > -1) {
                parent.layer.msg("资费代码" + packageCode + "重复，请重新输入");
                throw new Error('跳出循环');
            }
            if (packageCode != "" && preferentialFlowId == "0") {
                var isUsed = false;
                $.ajax({
                    url: base + "/packageSalary/packageCodeIsUsed",
                    data: {packageCode: packageCode},
                    type: "post",
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        console.info('当前状态：', data.status);
                        if (data.status == 1) {
                            isUsed = true;
                        }
                    }
                });

                if (isUsed) {
                    parent.layer.msg("资费代码" + packageCode + "已经配置，请重新输入");
                    $("#packageCode").focus();
                    throw new Error('跳出循环');
                }
            }
        })

    } catch(e) {
        return false;
    }

    var activityEndTime = $("#activityEndTime").val();
    if (activityEndTime != "") {
        $("#activityEndTime").val(activityEndTime + " 23:59:59");
    }

    if (time_range("00:00", "02:00")) {
        parent.layer.msg("00:00-02:00为结酬时间无法修改产品配置，请在非结酬时间修改");
        return false;
    }

    return confirm("注意：修改产品后当天订单按照最新配置结酬，即会影响结酬");
};

var time_range = function (beginTime, endTime) {
    var strb = beginTime.split(":");
    if (strb.length != 2) {
        return false;
    }
    var stre = endTime.split(":");
    if (stre.length != 2) {
        return false;
    }
    var b = new Date();
    var e = new Date();
    var n = new Date();
    b.setHours(strb[0]);
    b.setMinutes(strb[1]);
    e.setHours(stre[0]);
    e.setMinutes(stre[1]);

    if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
        return true;
    } else {
        //alert("当前时间是：" + n.getHours() + ":" + n.getMinutes() + "，不在该时间范围内！");
        return false;
    }
};


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

    console.info(name);


    $("#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);
            }
        }
    });
};

/*ueditor 编辑器 begin*/
//酬金规则
var ue = UE.getEditor('salaryRule', {
    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', '|',
            'simpleupload', 'insertimage', 'emotion', 'scrawl',
            'pagebreak', 'template', '|',
            'horizontal',  'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells',  'splittocols',  '|'
        ]
    ],
    maximumWords:1000,
});

//业务规则
var ue3 = UE.getEditor('detailUrl', {
    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', '|',
            'simpleupload', 'insertimage', 'emotion', 'scrawl',
            'pagebreak', 'template', '|',
            'horizontal',  'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells',  'splittocols',  '|'
        ]
    ],
    maximumWords:1000,
});
/*ueditor 编辑器 end*/
