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

var amountTotal;
var receiptNumber;

var approvalNumber;
var approvalTime;
var instPlan;
var referenceNo;
var kakaoPayType;
var kakaoDiscount;
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":"COMMON_KAKAO_MONEY"};
        
        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;
        var kind = receiptData.payKind;
        kakaoPayType = receiptData.kakao_paytype;
        kindName = kind;
        $("#title").html(receiptData.payKind + receiptData.authType + ' 영수증');
        $("#li_kind").html(receiptData.cardName);//window.AndroidInterface.getCardName());
        var kind_sub;
        var WCC = receiptData.wcc;
        var cardType = "";
        if(kakaoPayType.length != 0){
            if("C" == kakaoPayType) cardType = "카카오신용";
            else if("D" == kakaoPayType) cardType = "카카오머니";
        }
        $("#li_kind_sub").html(cardType + " " + receiptData.authType);
        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 = "-";
        }
        kakaoDiscount = String(Number(receiptData.kakao_discount));
        amountTotal = Number(receiptData.kakao_discount) + Number(receiptData.totalAmount);
        if(0 == Number(kakaoDiscount)){
            $("#li_discount").html(numberWithCommas(kakaoDiscount) + '원');
        }else {
            $("#li_discount").html(sign + numberWithCommas(kakaoDiscount) + '원');
        }
        $("#li_total").html(sign + numberWithCommas(amountTotal) + '원');//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()
        var isCancelPay = false;
        if(isIphone()){
            if ("Y" == receiptData.isCancelPayment || receiptData.authType == "취소"){
                isCancelPay = true;
            }
        }else {
            if (false == receiptData.isCancelPayment || receiptData.authType == "취소"){
                isCancelPay = true;
            }
        }
        if (isCancelPay) {
          $("#buttons").html("<div id='buttons' class='btnSection marginT13'><button onclick='app.sendMMS();;' class='btn wd100'>문자 영수증 전송</button></div>");
        }else {
            if(!isIphone()){
                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 && !isIphone()){
            $("#print_button").css("display","inline-block");
        }else {
            $("#print_button").css("display","none");
        }
        catId = receiptData.catId;
        if(!isIphone()) isTaxIncluded = receiptData.isTaxIncluded;
        if(isIphone()) receiptNumber = receiptData.receiptNumber;

    },
    requestCancel:function(){

        if(isIphone()){
            KAKAO_SEARCH_CAN.DATA.RECEIPT_ID = receiptNumber;
        }else {
            //금액
//            var amount = $("#li_total").html();
//            if('not_included' == isTaxIncluded){
//                amount = $("#li_supply").html();
//            }
//            amount = replaceAll(amount,"-","");
//            amount = replaceAll(amount,"원","");
//            amount = replaceAll(amount,",","");
//
//            var vatAmount = $("#li_tax").html();
//            vatAmount = replaceAll(vatAmount,"-","");
//            vatAmount = replaceAll(vatAmount,"원","");
//            vatAmount = replaceAll(vatAmount,",","");

            var amount = getAmount($("#li_total").html());
            var supplyAmount = getAmount($("#li_supply").html());
            var vatAmount = getAmount($("#li_tax").html());

            var discount = $("#li_discount").html();
            discount = replaceAll(discount,"-","");
            discount = replaceAll(discount,"원","");
            discount = replaceAll(discount,",","");
            //할부 개월 수
            var month = $("#li_month").html();
            if('일시불' == month){
                month = '0';
            }else {
                month = replaceAll(month,"개월","");
            }
            if(isIphone())KAKAO_SEARCH_CAN.DATA.RECEIPT_ID = receiptNumber;
            KAKAO_SEARCH_CAN.DATA.approvalNumber = $("#li_approval").html();
            KAKAO_SEARCH_CAN.DATA.tradeDate = approvalTime;
            KAKAO_SEARCH_CAN.DATA.totalAmount = String(Number(amount) - Number(discount));
            KAKAO_SEARCH_CAN.DATA.supplyAmount = supplyAmount;
            KAKAO_SEARCH_CAN.DATA.vatAmount = vatAmount;
            KAKAO_SEARCH_CAN.DATA.instPlan = month;
            KAKAO_SEARCH_CAN.DATA.catId = catId;
            KAKAO_SEARCH_CAN.DATA.referenceNo = referenceNo;
            KAKAO_SEARCH_CAN.DATA.kakaoDiscount = discount;
            KAKAO_SEARCH_CAN.DATA.kakaoPayType = kakaoPayType;
        }
        cordova.plugins.finPlugin.requestCancel(KAKAO_SEARCH_CAN.DATA,null, null);
        
    },
    sendMMS:function(){
        var data = {"TYPE":"COMMON_KAKAO"};
        cordova.plugins.finPlugin.sendMMS(data,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();