__coupon__bak.js 9.18 KB
var $ = require('jquery');

require('../util/datepicker')($);
var Validator = require('../util/jquery.validate');// 浏览器就不用这句了,Validator是全局变量



/*获取优惠码信息渲染页面*/
exports.renderview = function(id, callback) {

    var _content = $("#basicForm");
    var options = {
        type: 'post',
        url: '/getPromotionCode',
        data: {
            id: id
        },
        dataType: "json",
        success: function(res) {
            res = res.data;
            if (res.code == 200) {
                for (var key in res.data) {
                    if (key == 'promotionInfo') {
                        var __promotionInfo = JSON.parse(res.data["promotionInfo"]);

                        $("#promotionInfo-type").val(__promotionInfo["type"]);
                        $("#promotionInfo-condition-amount_at_least").val(__promotionInfo["condition"]["amount_at_least"]);
                        $("#promotionInfo-condition-count_at_least").val(__promotionInfo["condition"]["count_at_least"]);
                        $("#promotionInfo-action-discount").val(__promotionInfo["action"]["discount"]);
                        $("#promotionInfo-action-discount_at_most").val(__promotionInfo["action"]["discount_at_most"]);
                        if ($("#promotionInfo-type").val() == "3") {
                            $("#resultdiscount").hide();
                        }
                    } else if (key == 'reqDepartment') {
                        $("#" + key).val(res.data[key]);
                        var arr = String.prototype.split.call(res.data["reqDepartment"], '/');
                        $("#department1").val(arr[0]);
                        if (arr[1]) {
                            $("#department2").val(arr[1]).show();
                        } else {
                            $("#department2").hide();
                        }
                    } else {
                        $("#" + key).val(res.data[key]);
                        if (key == "staff") {
                            $("#" + key).html(res.data[key]);
                        }
                    }
                }
                $("input:hidden", _content).each(function() {
                var _value = $(this).val();
                var _name = $(this).attr("id");

                $("#" + _name).prev("div").find("[name='" + _name + "']").each(function() {
                    if (_value.indexOf($(this).val()) > -1) {
                        $(this).prop("checked", true);
                    }
                });
            });
                callback && callback(res.data)
            }
        },
        error: function(err) {
            console.log(err);
        }
    };

    $.ajax(options);
};

/*点击按钮提交(优惠码添加修改)*/
exports.submit = function(url, callback) {

    var $submit = $('#basicForm'),
        $startTime = $('#limitDateFrom'),
        $endTime = $("#limitDateTo");

    //初始化时间控件
    //.add($endTime)
    var a = $startTime.fdatepicker({
        format: 'yyyy-mm-dd hh:ii:ss',
        pickTime: true
    }).data('datepicker');

    $startTime.click(function() {
        a.setEndDate($endTime.val());
    });
    var b = $endTime.fdatepicker({
        format: 'yyyy-mm-dd hh:ii:ss',
        pickTime: true
    }).data('datepicker');

    $endTime.click(function() {
        b.setStartDate($startTime.val());
    });

    //点击radio,checkbox,获取相关数据,录入相关隐藏控件中
    $discount = $("#promotionInfo-action-discount");
    $("input:checkbox").add("input:radio").change(function() {
        var _name = $(this).attr("name"),_value = [];
        var $checked = $("input[name=" + _name + "]:checked");

        if ($checked.prop("name") == "promotionInfo-type") {
            if ($checked.val() == "3") {
                $discount.prop("disabled", true).val("0.00").parents("#resultdiscount").hide();
            } else {
                $discount.prop("disabled", false).parents("#resultdiscount").show();
            }
        }

        $checked.each(function() {
            _value.push($(this).val());
        });
        $("#" + _name).val(_value.join(','));
    });


    //选择部门
    var departmentArr = String.prototype.split.call($("#reqDepartment").val(), '/'),
        $department1 = $("#department1"),
        $department2 = $("#department2");

    $("select").change(function() {
        if ($(this).is($department1)) {
            departmentArr.length = 0;
            departmentArr[0] = $(this).val();
            if ($(this).val() === "零售运营部") {
                $department2.show();
                departmentArr[1] = $department2.val();
            } else {
                $department2.hide();
            }
        } else {
            departmentArr[1] = $(this).val();
        }
        $("#reqDepartment").val(departmentArr.join('/'));
    });

    function __isRepeat(arr) {
        var hash = {};

        for (var i in arr) {
            if (hash[arr[i]]) {
                return true;
            }
            hash[arr[i]] = true;
        }
        return false;
    }
    function validate() {
        var rules = {},data = {};

        $("input:text").each(function() {
            var id = $(this).attr("id");
            var value = $(this).val();
            var rule = [];

            if ($(this).attr("required")) {
                rule.push("required");
            }
            if ($(this).attr("maxlength")) {
                rule.push("max:" + $(this).attr("maxlength"));
            }
            if ($(this).attr("minlength")) {
                rule.push("max:" + $(this).attr("minlength"));
            }

            if ($(this).attr("pattern")) {
                rule.push("regex:" + $(this).attr("pattern"));
            }
            rules[id] = rule.join('|');
            data[id] = value;
        });
        console.log(rules);
        console.log(data);
        var v = Validator.make(data, rules);

        if (v.fails()) {
            console.log(v.messages());
            return false;
        }
        if (v.passes()) {
            if ($startTime.val() && $endTime.val()) {
                var startTime = new Date($startTime.val().replace(/-/g, "/"));
                var endTime = new Date($endTime.val().replace(/-/g, "/"));

                if (endTime > startTime) {
                    return true;
                }
            }
            var arr = String.prototype.split.call($("#code").val(), ',');

            if (__isRepeat(arr)) {
                validity.valid = false;
                return validity;
            }
            $.ajax({
                        type: 'POST',
                        url: '/checkPromotionCode',
                        data: {
                            code:$("#code").val()
                        },
                        dataType: 'json'
                    }).then(function(data) {
                        data = data.data;
                        if (data.code == "20001") {
                            var badcode = [];

                            $.each(data.data, function(index, item) {
                                if (item.flag == "1") {
                                    badcode.push(item.code);
                                }
                            });
                            if (badcode.length == 0) {
                                return true
                            }
                        }
                        return false;
                    }, function() {
                        console.log("验证codeAjax", false);
                        return false;
                    });

            return false;
        }
    }


    $("#save_brand").click(function() {
        if (validate()) {
            var data = {},key2,data2 = {};

            $submit.find("input").each(function() {
                var _key = $(this).attr("id");

                if (_key) {
                    var _value = $(this).val();

                    if (_key.indexOf('-') > -1) {
                        var arr = _key.split('-');

                        key2 = arr[0];
                        data[arr[0]] = data[arr[0]] || {};
                        if (arr.length == 2) {
                            data2[arr[1]] = _value;
                        }
                        if (arr.length == 3) {
                            data2[arr[1]] = data2[arr[1]] || {};
                            data2[arr[1]][arr[2]] = _value;
                        }
                    } else {
                        data[_key] = _value;
                    }
                }
            });
            data[key2] = JSON.stringify(data2);
            if (data.status === "2") {
                data.status = "0";
            }

            var options = {
                type: 'post',
                url: url,
                data: data,
                dataType: "json",
                success: function(res) {
                    location.href = "/list";
                    callback && callback(res);
                },
                error: function(err) {
                    console.log(err);
                }
            };

            //console.log("AJAX");
            $.ajax(options);
            return false;
        } else {
            console.log("验证不通过");
        }
    });

}