var startDate;
var endDate;
var kindName;
var catId;

var amountTotal;
var receiptNumber;

var approvalNumber;
var approvalTime;
var instPlan;
var referenceNo;
var isTaxIncluded;

var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        this.itemInit();
        this.eventInit();
        this.otherInit();
    },
    itemInit:function() {
        $(document).on("keyup", ".uPayN", function() {
            $(this).number(true);
        });
        if ($(".uPayN").length > 0) {
            $(".uPayN").number(true);
        }

        if(isIphone()){
            jQuery('#print_button').css("display", "none");
        }
        
        var data = {"TYPE":"ZERO"};
        
        cordova.plugins.finPlugin.getReceiptData(data,function(res){
            app.showReceiptData(res);
        }, function(error){
            showToastMessage(error);
        });
    },
    eventInit:function(){

    },
    otherInit:function(){

    },
    showReceiptData:function(res){
        var receiptData = JSON.parse(res);
        if(null == receiptData) return;
        
        if(isIphone())
        {
            $("#li_kind_sub").html(receiptData['tradingCategory']);
            $("#li_kind").html(receiptData['cardName']);
            $("#li_time").html(receiptData['dateAndTime']);
            $("#li_cardNumber").html(receiptData['cardNumber']);
            $("#li_month").html(receiptData['installDoc']);
            $("#li_readerNumber").html(receiptData['merchantNumber']);
            $("#li_approval").html(receiptData['approvalNumber']);
            
            var notice = receiptData['notice'];
            if(notice.length == 0)
            {
                $("#li_buyCompany").html(receiptData['acquirersName']);
            }else
            {
                $("#li_buyCompany").html(receiptData['acquirersName'] +"(" + notice + ")");
            }
            $("#li_supply").html(receiptData['supplyAmount'] + " 원");
            $("#li_tax").html(receiptData['taxAmount'] + " 원");
            $("#li_total").html(receiptData['totalAmount'] + " 원");
            $("#li_bizName").html(receiptData['storeName']);
            $("#li_bizNumber").html(receiptData['businessNumber']);
            $("#li_bizOwner").html(receiptData['represent']);
            $("#li_bizCallNumber").html(receiptData['storePhone']);
            $("#li_bizAddress").html(receiptData['storeAddress']);

            receiptNumber = receiptData['receiptNumber'];
            catId = receiptData['readerNumber'];
            amountTotal = receiptData['totalAmount'];
            approvalNumber = receiptData['approvalNumber'];
            approvalTime = receiptData['dateOfApproval'];
            instPlan = receiptData['installment'];
            
            if(receiptData['isCanceled']=='Y')
            {
                $("#buttons").html("<div id='buttons' class='btnSection marginT13'><button onclick='app.sendMMS();;' class='btn wd100'>문자 영수증 전송</button></div>");
            }
        }else
        {
            var kind = receiptData.payKind;
            kindName = kind;
            $("#title").html(receiptData.payKind + ' ' + receiptData.authType + ' 영수증');
            $("#li_kind").html(receiptData.cardName);
            var kind_sub = receiptData.authType;
            $("#li_kind_sub").html(kind_sub);
            approvalTime = receiptData.time;
            referenceNo = receiptData.referenceNo;
            var viewTime = approvalTime.replace(/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/g, '$1/$2/$3 $4:$5:$6');
            $("#li_time").html(viewTime);
            $("#li_approval").html(receiptData.approvalNumber);
            $("#li_cardNumber").html(receiptData.cardNumber);
            var notice = receiptData.notice;
            if (notice.length == 0) {
                $("#li_buyCompany").html(receiptData.buyCompany);
            } else {
                $("#li_buyCompany").html(receiptData.buyCompany + '(' + notice + ')');
            }
            var month = receiptData.month;//window.AndroidInterface.getMonth();
            if (month == "0") {
                month = "일시불";
            } else {
                month = month + "개월";
            }
            $("#li_month").html(month);
            var sign = "";
            if (receiptData.authType == "취소") {
                sign = "-";
            }
            $("#li_total").html(sign + numberWithCommas(receiptData.totalAmount) + '원');//window.AndroidInterface.getTotalAmount()
            $("#li_supply").html(sign + numberWithCommas(receiptData.supplyAmount) + '원');//window.AndroidInterface.getSupplyAmount()
            $("#li_tax").html(sign + numberWithCommas(receiptData.taxAmount) + '원');//window.AndroidInterface.getTaxAmount()
            $("#li_notice").html(receiptData.notice);

            $("#li_readerNumber").html(receiptData.storeNumber);//window.AndroidInterface.getStoreNumber()
            $("#li_bizName").html(receiptData.bizName);//window.AndroidInterface.getBizName()
            $("#li_bizOwner").html(receiptData.ownerName);//window.AndroidInterface.getBizOwner()
            var bizNumber = receiptData.bizNumber;//window.AndroidInterface.getBizNumber()
            if (bizNumber.length == 10) {
                $("#li_bizNumber").html(bizNumber.substring(0,3) + "-" + bizNumber.substring(3,5) + "-" + bizNumber.substring(5,10));
            } else {
                $("#li_bizNumber").html(bizNumber);
            }
            $("#li_bizCallNumber").html(receiptData.bizPhone);//window.AndroidInterface.getBizCallNumber()
            $("#li_bizAddress").html(receiptData.bizAddress);//window.AndroidInterface.getBizAddress()

            if(receiptData.isCancelPayment == false) {//window.AndroidInterface.isCancelPayment()
              $("#buttons").html("<div id='buttons' class='btnSection marginT13'><button onclick='app.sendMMS();;' class='btn wd100'>문자 영수증 전송</button></div>");
            }else {
              var message1 = receiptData.alipayTransId;//window.AndroidInterface.getAlipayTransId();
              var message2 = receiptData.alipayTransAmountCny;//window.AndroidInterface.getAlipayTransAmountCny();
              var message3 = receiptData.alipayExchangeRate;//window.AndroidInterface.getAlipayExchangeRate();
              var message4 = receiptData.alipayUserLoginId;//window.AndroidInterface.getAlipayUserLoginId();
              if (message3 == "www.kakaopaymall.com에서이용" && message4 == "발행처:쓰달/알파트레이드연합") {
                $("#noti_messages").show();
                $("#li_message1").html(message1.replace('SP조회:',''));
                $("#li_message2").html(message2.replace('SP승인:',''));
                $("#li_message3").html(message3);
                $("#li_message4").html(message4.replace('발행처:',''));
              }
            }
            if(receiptData.canPrint){
                $("#print_button").css("display","inline-block");
            }else {
                $("#print_button").css("display","none");
            }
            catId = receiptData.catId;
            isTaxIncluded = receiptData.isTaxIncluded;
        }
    },
    requestCancel:function(){
        
        if(isIphone())
        {
            //receiptNumber
            ZERO_CAN_PAY.DATA.RECEIPT_ID = receiptNumber;
            ZERO_CAN_PAY.DATA.approvalNumber = approvalNumber;
            ZERO_CAN_PAY.DATA.tradeDate = approvalTime;
            ZERO_CAN_PAY.DATA.totalAmount = amountTotal;
            ZERO_CAN_PAY.DATA.instPlan = instPlan;
            ZERO_CAN_PAY.DATA.catId = catId;
            cordova.plugins.finPlugin.requestCancel(ZERO_CAN_PAY.DATA,null, null);
        }else
        {
            //금액
            var amount = $("#li_total").html();
            if('not_included' == isTaxIncluded){
                amount = $("#li_supply").html();
            }
            amount = replaceAll(amount,"-","");
            amount = replaceAll(amount,"원","");
            amount = replaceAll(amount,",","");
            //할부 개월 수
            var month = $("#li_month").html();
            if('일시불' == month){
                month = '0';
            }else {
                month = replaceAll(month,"개월","");
            }

            ZERO_CAN_PAY.DATA.approvalNumber = $("#li_approval").html();
            ZERO_CAN_PAY.DATA.tradeDate = approvalTime;//$("#li_time").html();
            ZERO_CAN_PAY.DATA.totalAmount = amount;
            ZERO_CAN_PAY.DATA.instPlan = month;
            ZERO_CAN_PAY.DATA.catId = catId;
            ZERO_CAN_PAY.DATA.referenceNo = referenceNo;
            cordova.plugins.finPlugin.requestCancel(ZERO_CAN_PAY.DATA,null, null);

        }
    },
    sendMMS:function(){
        if(isIphone())
        {
            var data = {"TYPE":"ZERO"};
            cordova.plugins.finPlugin.sendMMS(data,null, null);
        }else
        {
            cordova.plugins.finPlugin.sendMMS("",null, null);
        }
    },
    printReceipt:function(){
        cordova.plugins.finPlugin.printReceipt("",null, function(error){
            showToastMessage(error);
        });
    },
    closeStack:function(){
        cordova.plugins.finPlugin.backButton("", null, null);
    },backbuttonAction:function(){
        var isPopupClose = false;
        if ($("#layerPopup.Popup12").is(':visible')){
            isPopupClose = true;
            app.hideWarnningPopup();
        }
        if(!isPopupClose){
            cordova.plugins.finPlugin.backButton("", null, null);
        }
    },backReceipAction:function(){
        if(isIphone()){
          cordova.plugins.finPlugin.moveStack(RECEIPT.DATA, null,null);
        }else {
          app.backbuttonAction();
        }
    }
};

app.initialize();

