layui.define(['jquery'],function (exports) {
    var $ = layui.jquery;
    var unipay = {};
    var QRCode=function () {
        this.v = '0.1.beta';
    };

    (function (win) {
        win.unipay = unipay;
        QRCode.prototype.Monitor = function (payType, outTradeNo, callback, config) {
            this.outTradeNo = outTradeNo;
            this.payType = payType;
            this.callback = callback;
            this.config = $.extend({maxRepeatTimes: 60, interval: 5}, config);
        };
        QRCode.prototype.Monitor.prototype.start = function () {
            // repeat interval 5s, max repeat times 60, total 5 minutes.
            var count = 0;
            var _this = this;
            var ajaxTimeout = this.config.interval * 1000;
            var maxRepeatTimes = this.config.maxRepeatTimes;
            var intervalToken = setInterval(function () {
                count++;

                $.ajax({
                    url: unipay.queryOrderStatusPath,
                    timeout: ajaxTimeout,
                    method: "POST",
                    data: {
                        type: _this.payType,
                        outTradeNo: _this.outTradeNo
                    }
                }).done(function (data) {
                    if (data.paid == "paid") {
                        clearInterval(intervalToken);
                        if (_this.callback.onPaySuccess) {
                            _this.callback.onPaySuccess.call(_this);
                        }
                    }
                });

                if (count == maxRepeatTimes) {
                    clearInterval(intervalToken);
                    if (_this.callback.onPayTimeout) {
                        _this.callback.onPayTimeout.call(_this)
                    }
                }
            }, _this.config.interval * 1000);
            _this.intervalToken = intervalToken;
        };

        QRCode.prototype.Monitor.prototype.stop = function () {
            clearInterval(this.intervalToken);
        };

        /**
         * @param payType wx|alipay
         * @param outTradeNo
         */
        QRCode.prototype.cancelOrder = function (payType, outTradeNo) {
            $.ajax({
                url: unipay.cancelPath,
                method: "POST",
                data: {
                    type: payType,
                    outTradeNo: outTradeNo
                }
            }).done(function (data) {});
        };

        /**
         * you must call this method before any other action.
         * @param config
         */
        QRCode.prototype.config = function (config) {
            unipay.cancelPath = config.cancelPath;
            unipay.queryOrderStatusPath = config.queryOrderStatusPath;
        }

    })(window);


    exports('unipay',new QRCode)
});


