function initDetail(detail) {
    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: 60000
    });
}
$(function () {
    var cities = [];
    var cityIds = [];
    $("#cityAuth").val(0);
    $("#city-box").hide();
    // 编辑逻辑
    var editCities = $('#citys').val();
    if (editCities) {
        cityIds = editCities.split(',');
        $("#city-box").show();
        $("#cityAuth").val(1);
        $(".myTabBtn").each(function () {
            if($(this).text() == '统一授权') {
                $(this).removeClass('am-btn-primary').addClass('am-btn-default');
            } else {
                $(this).removeClass('am-btn-default').addClass('am-btn-primary');
            }
        });
        $(".city-select-item>input").each(function () {
            var val = $(this).val();
            var text = $(this).parent().text();
            if (cityIds.indexOf(val) > -1) {
                $(this).prop('checked', true);
                cities.push(text);
            } else {
                $(this).prop('checked', false);
            }
        });
        var str = '';
        if (cities.length > 0) {
            for (var i = 0; i < cities.length; i++) {
                if (i == cities.length -1) {
                    str += cities[i];
                } else {
                    str+=cities[i]+',';
                }
            }
        }
        $("#city-conten").text(str);
    }
    $(document).click(function () {
        $("#city-select-box").hide();
    });
    $("#city-conten").click(function (event) {
       $("#city-select-box").show();
        event.stopPropagation();
    });
    $(document).on('click','#city-select-box > li', function (event) {
        $("#city-select-box").show();
        event.stopPropagation();
    });
    $(document).on('change', '#allChecked > input', function () {
        cities = [];
        cityIds= [];
       if ($(this).prop('checked')) {
           $(".city-select-item > input").each(function () {
               $(this).prop('checked',true);
               cities.push($(this).parent().text());
               cityIds.push($(this).val())
           })
       } else {
           $(".city-select-item > input").each(function () {
               $(this).prop('checked',false);
               cities = [];
               cityIds= [];
           })
       }
        var str = '';
        var strIds = '';
        if (cities.length > 0) {
            for (var i = 0; i < cities.length; i++) {
                if (i == cities.length -1) {
                    str += cities[i];
                    strIds += cityIds[i];
                } else {
                    str+=cities[i]+',';
                    strIds+=cityIds[i]+',';
                }
            }
        }
        $("#city-conten").text(str);
        $("#citys").val(strIds)
        $("#city-select-box").show();
    });

    $(document).on('change', '.city-select-item > input', function () {
        var text = $(this).parent().text();
        var id = $(this).val();
        if ($(this).prop('checked')) {
            cities.push(text);
            cityIds.push(id);
        } else {
            cities.splice($.inArray(text, cities), 1);
            cityIds.splice($.inArray(id, cities), 1);
        }
        var str = '';
        var strIds = '';
        if (cities.length > 0) {
            for (var i = 0; i < cities.length; i++) {
                if (i == cities.length -1) {
                    str += cities[i];
                    strIds += cityIds[i];
                } else {
                    str+=cities[i]+',';
                    strIds+=cityIds[i]+',';
                }
            }
        }
        $("#city-conten").text(str);
        $("#citys").val(strIds);
        $("#city-select-box").show();
    });
    $(document).on('click', '.myTabBtn', function() {
       $(this).addClass('am-btn-primary').siblings('.myTabBtn').removeClass('am-btn-primary').addClass('am-btn-default');
        var val = $(this).text();
        if (val == '统一授权') {
            $("#citys").val('');
            $("#cityAuth").val(0);
            $("#city-box").hide();
        } else {
            if (cityIds.length > 0) {
                $("#citys").val(cityIds.join(','));
            }
            $("#cityAuth").val(1);
            $("#city-box").show();
        }
    });
    var editPackageCodeArr = [];
    if ($("#priceCommissions").val()) {
        initEditPage ();
    }
    function initEditPage () {
        var editPagePriceCommissions = JSON.parse($("#priceCommissions").val());
        if (editPagePriceCommissions.length) {
          var str = '';
          for (var i=0; i<editPagePriceCommissions.length; i++) {
              if (i==0) {
                  str += getStr('#0e90d2', '添加业务', 'addBtn', editPagePriceCommissions[i], i)
              } else {
                  str += getStr('red', '删除业务', 'delBtn', editPagePriceCommissions[i], i)
              }
          }
          $("#hot-business").html(str);
            for (var i=0; i<editPagePriceCommissions.length; i++) {
                if (i==0) {
                    initDetail("businessDetail_1");
                } else {
                    var detail = 'businessDetail_'+(i+1);
                    initDetail(detail);
                }
            }
        }

        $(".packageCode").attr('readonly', 'readonly');
        $(".packageCode").each(function() {
            editPackageCodeArr.push($(this).val())
        });
        for (var i=0; i < editPackageCodeArr.length; i++) {
            var index = packageCodes.indexOf(editPackageCodeArr[i]);
            if (index > -1) {
                packageCodes.splice(index, 1)
            }
        }
    }
    $("#categoryType").val($("#categoryId").find("option:selected").attr("categoryType"));
    if ($("#categoryId").find("option:selected").attr("categoryType") == '0') {//号卡
        $("#packageCode").attr('name', 'packageCode');
        $("#broad-package-code").find('input').removeAttr('name');
        $("#broad-package-region").find('select').attr('name', 'regionId');
        $("#hot-business").hide();
        $("#banner").hide();
        $("#deployMethod").show();
        $("#broadTypeBox").hide();
        $("#businessIntroDiv").hide();
        $("#businessDetailDiv").hide();
        $("#broad-package-code").hide();
        $("#broad-package-region").show();
        $("#haoka").show();
    } else if($("#categoryId").find("option:selected").attr("categoryType") == '2') {//宽带预约
        $("#packageCode").removeAttr('name');
        $("#broad-package-code").find('input').attr('name', 'packageCode');
        $("#broad-package-region").find('select').attr('name', 'regionId');
        $("#hot-business").hide();
        $("#banner").hide();
        $("#deployMethod").show();
        $("#broad-package-code").show();
        $("#broad-package-region").show();
        $("#broadTypeBox").show();
        $("#businessIntroDiv").hide();
        $("#businessDetailDiv").hide();
        $("#haoka").hide();
    } else {//热门业务 和 电视
        $("#packageCode").attr('name', 'packageCode');
        $("#broad-package-code").find('input').removeAttr('name');
        $("#broad-package-region").find('select').removeAttr('regionId');
        $("#hot-business").show();
        $("#banner").show();
        $("#deployMethod").show();
        $("#broadType").hide();
        $("#broadTypeBox").hide();
        $("#businessIntroDiv").show();
        $("#businessDetailDiv").show();
        $("#haoka").hide();
        $("#broad-package-code").hide();
        $("#broad-package-region").hide();
    }

    $("#categoryId").change(function(){
        var categoryType = $("#categoryId").find("option:selected").attr("categoryType");
        $("#categoryType").val(categoryType);

        if (categoryType == '0') { //号卡
            $("#packageCode").attr('name', 'packageCode');
            $("#broad-package-code").find('input').removeAttr('name');
            $("#broad-package-region").find('select').attr('name', 'regionId');
            $("#hot-business").hide();
            $("#banner").hide();
            $("#deployMethod").show();
            $("#broadTypeBox").hide();
            $("#businessIntroDiv").hide();
            $("#businessDetailDiv").hide();
            $("#broad-package-code").hide();
            $("#broad-package-region").show();
            $("#haoka").show();
        } else if(categoryType == '2') {//宽带预约
            $("#packageCode").removeAttr('name');
            $("#broad-package-code").find('input').attr('name', 'packageCode');
            $("#broad-package-region").find('select').attr('name', 'regionId');
            $("#hot-business").hide();
            $("#banner").hide();
            $("#deployMethod").show();
            $("#broad-package-code").show();
            $("#broad-package-region").show();
            $("#broadTypeBox").show();
            $("#businessIntroDiv").hide();
            $("#businessDetailDiv").hide();
            $("#haoka").hide();
        } else {//热门业务 和 电视
            $("#packageCode").attr('name', 'packageCode');
            $("#broad-package-code").find('input').removeAttr('name');
            $("#broad-package-region").find('select').removeAttr('regionId');
            $("#hot-business").show();
            $("#banner").show();
            $("#deployMethod").show();
            $("#businessIntroDiv").show();
            $("#businessDetailDiv").show();
            $("#haoka").hide();
            $("#broadTypeBox").hide();
            $("#broad-package-code").hide();
            $("#broad-package-region").hide();
        }
    });


    $("#submitBtn").click(function () {
        // 校验业务代码
        if ($("#categoryType").val() == "2") {

        }
        if ($("#categoryType").val() != '0' && $("#categoryType").val() != '2') {
            var flag = true;
            $("#hot-business").find(".hot-business-item").each(function () {
                if ($(this).find('.packageName').val() == '' || $(this).find('.packageCode').val() == '' || $(this).find('.incentiveSalary').val() == '' || $(this).find('.commission').val() == '') {
                    flag = false
                }
            });
            if (!flag) {
                alert('带*号为必填字段');
                return
            }
            var tmpInput = $("#priceCommissions");
            var priceCommissions = [];
            $("#hot-business").find(".hot-business-item").each(function () {
                priceCommissions.push({
                    packageCode: $(this).find('.packageCode').val(),
                    packageName: $(this).find('.packageName').val(),
                    regionId: $(this).find('.regionId').val(),
                    feeDetail: $(this).find('.feeDetail').val(),
                    packageExplain: $(this).find('.packageExplain').val(),
                    packageTariffType: $(this).find('.packageTariffType').val(),
                    incentiveSalary: $(this).find('.incentiveSalary').val(),
                    businessDetail: $(this).find('textarea').val(),
                    commission: $(this).find('.commission').val()
                })
            });
            var myform = $("#tmpForm");
            tmpInput.attr("value", JSON.stringify(priceCommissions));
            myform.append(tmpInput);
            //console.log(myform);
        }
        var myform = $("#tmpForm");
        console.log(myform);
        checkFormField();
    });


    function getStr(btnColor, btnText, btnClass, obj, size) {
        var number = size + 1;
        var select0 = (obj.packageTariffType == 0) ? 'selected' : '';
        var select1 = (obj.packageTariffType == 1) ? 'selected' : '';
        var select2 = (obj.packageTariffType == 2) ? 'selected' : '';
        var select3 = (obj.packageTariffType == 3) ? 'selected' : '';
        var str = '';
        str += '<div class="hot-business-item">'
            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right"><span style="color: red;">*</span>资费名称'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<input class="js-ajax-validate packageName" value="'+obj.packageName+'" data-validate-async data-validation-message="请输入资费名称" type="text" minlength="1" maxlength="12" placeholder="请输入资费名称" required />'
            +'</div>'
            +'<div class="'+btnClass+' businessBtn" style="width: 100px;background-color: '+btnColor+';">'+btnText+'</div> </div>'
            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right"><span style="color: red;">*</span>资费代码'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<input class="js-ajax-validate packageCode" value="'+obj.packageCode+'" data-validate-async data-validation-message="请输入资费代码" type="text" minlength="1" maxlength="20" placeholder="请输入资费代码" required />'
            +'</div>'
            +'<div></div>'
            +'</div>'

            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right"><span style="color: red;">*</span>资费类型'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<select class="packageTariffType">'
            + '<option value="0" ' + select0 + '>主资费</option>'
            + '<option value="1" ' + select1 + '>附加资费</option>'
            + '<option value="2" ' + select2 + '>营销活动</option>'
            + '<option value="3" ' + select3 + '>营销活动（短信）</option>'
            +'</select>'
            +'</div>'
            +'<div></div>'
            +'</div>'

            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right">资费简介'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<input class="js-ajax-validate feeDetail" value="'+obj.feeDetail+'" type="text" maxlength="16" />'
            +'</div>'
            +'<div></div>'
            +'</div>'

            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right">资费说明'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<input class="js-ajax-validate packageExplain" value="'+obj.packageExplain+'" type="text" maxlength="100" />'
            +'</div>'
            +'<div></div>'
            +'</div>'

            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right"><span style="color: red;">*</span>队长酬金'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<input class="js-ajax-validate incentiveSalary" value="'+obj.incentiveSalary+'" data-validate-async data-validation-message="请输入队长酬金" type="text" minlength="1" maxlength="20" placeholder="所有业务必填" required onkeyup="cheakContent(this);"/>'
            + '<div style="color:red;">提示：订购成功即可获得相应酬金，不考虑退订等其他情况</div>'
            +'</div>'
            +'<div>元</div>'
            +'</div>'
            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right"><span style="color: red;">*</span>队员酬金'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +'<input class="js-ajax-validate commission" value="'+obj.commission+'" data-validate-async data-validation-message="请输入队员酬金" type="text" minlength="1" maxlength="20" placeholder="非号卡业务必填" required onkeyup="cheakContent(this);"/>'
            + '<div style="color:red;">提示：订购成功即可获得相应酬金，不考虑退订等其他情况</div>'
            +'</div>'
            +'<div>元</div>'
            +'</div>'

            +'<div class="am-g am-form-group am-margin-top" style="display: flex;">'
            +'<div class="am-u-sm-4 am-u-md-2 am-text-right">业务详情'+ number + '</div>'
            +'<div class="am-u-sm-6 am-u-md-6">'
            +' <textarea type="text/plain"'
            + 'class="businessDetail" id="businessDetail_'+number+'" style="height:20rem;" >'+obj.businessDetail+'</textarea>'
            +'</div>'
            +'<div></div>'
            +'</div>'

            +'</div>';
        return str;
    };
    $(document).on('click', '.addBtn', function(){
        var str = getStr('red', '删除业务', 'delBtn', {packageCode: '',packageName: '',feeDetail: '', packageTariffType:'0', incentiveSalary: '0', commission: '0',packageExplain:"", businessDetail:''}, $(".hot-business-item").length);
        $('#hot-business').append(str);
        var detail = 'businessDetail_'+$(".hot-business-item").length;
        initDetail(detail);
        packageNameLength();
    });
    $(document).on('click', '.delBtn', function(){
        $(this).parent().parent().remove();
    });
    /*表单验证：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('detailUrl');
    generateFileupload('backgroundImage');

    //categoryChange();

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

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

    packageNameLength();
});
/*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: 60000
});


/*ueditor 编辑器 end*/
var categoryChange = function () {
    var categoryId = $("#categoryId").val();
    if ('1' == categoryId) {
        $("#discountsDiv").css("display", "none");//隐藏div
        // 资费代码
        $("#packageCodeSpan").html("资费代码");
        $("#packageCode").attr("data-validation-message","请输入资费代码");
        $("#packageCode").attr("placeholder","请输入资费代码");
        //资费名称
        $("#packageNameSpan").html("资费名称");
        $("#packageName").attr("data-validation-message","请输入资费名称");
        $("#packageName").attr("placeholder","请输入资费名称");
        //资费简介
        $("#packageBriefSpan").html("资费简介");
        $("#packageBrief").attr("data-validation-message","请输入资费简介");
        $("#packageBrief").attr("placeholder","请输入资费简介");
    } else {
        $("#discountsDiv").css("display", "block");//显示div
        // 资费代码
        $("#packageCodeSpan").html("产品代码");
        $("#packageCode").attr("data-validation-message","请输入产品代码");
        $("#packageCode").attr("placeholder","请输入产品代码");
        //资费名称
        $("#packageNameSpan").html("产品名称");
        $("#packageName").attr("data-validation-message","请输入产品名称");
        $("#packageName").attr("placeholder","请输入产品名称");
        //资费简介
        $("#packageBriefSpan").html("产品简介");
        $("#packageBrief").attr("data-validation-message","请输入产品简介");
        $("#packageBrief").attr("placeholder","请输入产品简介");
    }
    // 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();
};

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

    var checkFlag = true;
    var startTime = $("#startTime").val();
    var endTime = $("#endTime").val();
    if(startTime != "" && endTime != "") {
        var date1=new Date(startTime);
        var date2=new Date(endTime);
        if(date1>date2){
            parent.layer.msg("开始日期不能大于截止日期");
            checkFlag = false;
        }
    }

    if (checkFlag) {
        if (startTime != "") {
            $("#startTime").val(startTime + " 00:00:00");
        }
        if (endTime != "") {
            $("#endTime").val(endTime + " 23:59:59");
        }
        $("#tmpForm").submit();
    }
};


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

function packageNameLength() {
    if ($("#remarkInput").val() && $("#remarkInput").val() == 1) {
        $(".packageName").attr("maxlength", 50);
        return true;
    } else {
        $(".packageName").attr("maxlength", 12);
        return true;
    }
    return false;
}

