var businessNumber;
var productNumber;
var useType = '';
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);
        }
        //상단 표기 상태 변경
        cordova.plugins.finPlugin.getUseType("", function(res){
            if(0 < res.length){
                if('연동형' == res){
                    useType = '연동형';
                    $("#hd_title").html("<a href='#' onclick='app.backbuttonAction();'><h3 class='btnPre'><span class='blind'>이전</span></h3></a><h3 class='title'>현금영수증 취소</h3><h3 id='battery' class='battery'><span></span></h3>");
                    //연동형 인경우 스키마 값 체크
                    cordova.plugins.finPlugin.checkScheme("", function(isScheme){
                        //스키마 값이 있는 경우 해당 번호 기반으로 인증 정보를 가져와야 한다
                        //번호가 없는 경우 메인 사업장을 가져온다
                        app.getSchemeData();
                    }, function(error){
                        //스키마 값이 없는 경우 해당 앱에 정보 없음 Callback 을 한다.
                    });
                }else {
                    useType = '통합형';
                    //통합형 인 경우 연결된 모든 사업장을 가져온다
                    app.getCancelData();
                }
            }
        }, null);

    },
    eventInit:function(){
       
    },
    otherInit:function(){
        if(isIphone()){

        }else {
            document.addEventListener("backbutton", app.backbuttonAction, false);
        }
        UPDATE_CHECK();
    },
   
    backbuttonAction:function(){
        var isPopupClose = false;
        if ($("#layerPopup.Popup06").is(':visible')){
            isPopupClose = true;
            $('#layerPopup.Popup06').hide();
        }
        if(!isPopupClose){
            cordova.plugins.finPlugin.backButton("", null, null);
        }
    },
    getSchemeData:function(){
        //스키마 값 가져오기
        cordova.plugins.finPlugin.getSchemeData("", function(schemeData){
            app.setSchemeData(schemeData);
        },function(error){
            if(isIphone()) cordova.plugins.finPlugin.moveStack(SET01.DATA,null, null);
        });
    },
    setSchemeData:function(data){
        //스키마 값 셋팅 하기 (취소 데이터와 동일하게 한다)
        var receiptData = JSON.parse(data);
       if(null == receiptData) return;
       if(isIphone())
       {
           //$("#uIssue").val(receiptData['instlmtMonth']);
           $("#uApprovalNumber").val(receiptData['srcConfmNo']);
           $("#uInstPlan").val(receiptData['srcConfmDe']);
           $("#approvalDate").val(receiptData['srcConfmDe']);
           $("#uAmount").val(receiptData['totalAmount'] + " 원");
           $("#uBizName").val(receiptData['businessName']);
           productNumber = receiptData['productNumber'];
           businessNumber = receiptData['businessNumber'];
           $("#catId").val(receiptData['readerNumber']);

           if (receiptData['instlmtMonth'] == 0) {
              $("#uIssue").val("소득공제");
           } else if (receiptData['instlmtMonth'] == 1) {
               $("#uIssue").val("지출증빙");
           }else if (receiptData['instlmtMonth'] == 99) {
               $("#uIssue").val("자진발급");
               $("#checkNum").val('0100001234');
               $("#checkNum").prop("disabled", true);
               app.goneReadCard();
           }else {
               $("#uIssue").val("발행안함");
               $("#dv_ApprovalNumber").html('');
               $("#dv_confirmNumber").html('');
               app.goneReadCard();
           }
           
           /*
           if($("#uIssue").val() == '발행안함'){
               $("#dv_ApprovalNumber").html('');
               $("#dv_confirmNumber").html('');
               app.goneReadCard();
           }
           else if($("#uIssue").val() == '1'){
               $("#checkNum").val('0100001234');
               $("#checkNum").prop("disabled", true);
               app.goneReadCard();
           }
           */
       }
       else
       {
           $("#uIssue").val(app.replacaSchemeIssued(receiptData.issuedName));
           $("#uApprovalNumber").val(receiptData.approvalNumber);
           $("#uInstPlan").val(receiptData.approvalDate);
           $("#uAmount").val(receiptData.totalAmount);
           $("#uBizName").val(receiptData.storeName);
           $("#catId").val(receiptData.catId);

           if(receiptData.issuedName == '발행안함'){
               $("#dv_ApprovalNumber").html('');
               $("#dv_confirmNumber").html('');
               app.goneReadCard();
           }
           else if(receiptData.issuedName == '자진발급'){
               $("#checkNum").val('0100001234');
               $("#checkNum").prop("disabled", true);
               app.goneReadCard();
           }
       }
    },
    getCancelData:function(data){
        cordova.plugins.finPlugin.getCashCancelInfo("",function(res){
            app.setCancelCashInfo(res);
        }, function(error){
            showToastMessage(error);
        });
    },
   setCardNum:function(cardInfo){
        close_Progress();
       app.setChangeTextType();
       $("#checkNum").val(cardInfo);
       close_Progress();
       app.goneReadCard();
       
   },
   setChangeTextType:function(){
         var f = document.getElementById("checkNum");
         f.type= "text";
         document.getElementById("checkNum").disabled = true;
   },
    showReadCard:function () {
      $(".SaveBtnWrap02").html("<a href='#' onclick='app.reqReadCard();' class=''>카드읽기</a>");
    },goneReadCard:function() {
      $(".SaveBtnWrap02").html("<a href='#' onclick='app.reqCancel();' class=''>취소요청</a>");
    },setCancelCashInfo:function(res){
       var receiptData = JSON.parse(res);
       if(null == receiptData) return;
       if(isIphone())
       {
           $("#uIssue").val(receiptData['segment']);
           $("#uApprovalNumber").val(receiptData['approvalNumber']);
           $("#uInstPlan").val(receiptData['approvalDate']);
           $("#approvalDate").val(receiptData['dateOfApproval']);
           $("#uAmount").val(receiptData['amount'] + " 원");
           $("#uBizName").val(receiptData['storeName']);
           productNumber = receiptData['productNumber'];
           businessNumber = receiptData['businessNumber'];
           $("#catId").val(receiptData['readerNumber']);

           if($("#uIssue").val() == '발행안함'){
               $("#dv_ApprovalNumber").html('');
               $("#dv_confirmNumber").html('');
               app.goneReadCard();
           }
           else if($("#uIssue").val() == '자진발급'){
               $("#checkNum").val('0100001234');
               $("#checkNum").prop("disabled", true);
               app.goneReadCard();
           }
       }
       else
       {
           $("#uIssue").val(receiptData.issuedName);
           $("#uApprovalNumber").val(receiptData.approvalNumber);
           $("#uInstPlan").val(receiptData.approvalDate);
           $("#uAmount").val(receiptData.totalAmount);

           $("#uBizName").val(receiptData.storeName);
           $("#catId").val(receiptData.catId);

           if($("#uIssue").val() == '발행안함'){
               $("#dv_ApprovalNumber").html('');
               $("#dv_confirmNumber").html('');
               app.goneReadCard();
           }
           else if($("#uIssue").val() == '자진발급'){
               $("#checkNum").val('0100001234');
               $("#checkNum").prop("disabled", true);
               app.goneReadCard();
           }
       }
    },
    updateButton:function(confirmNumber) {
      if(confirmNumber.length > 0) {
        app.goneReadCard();
      } else {
        app.showReadCard();
      }
      cordova.plugins.finPlugin.changeInstPlan(confirmNumber, null, null);
    },
     reqCancel:function(){
            console.log('}}}}}}}}}}}}}} reqCancel');
         
            if(isIphone())
            {
                if (isClickedButton()) {
                    return;
                }
                var price = $("#uAmount").val(); // 판매금액 입력값
                var company = $(".company").val(); // 상호 선택값
                var issue = $(".issue").val(); // 발급구분 선택값
                
                if ($("#uIssue").val() == '발행안함'){
                    if(price == "" || company == "" ){
                        $("#layerPopup.Popup12").show();
                    }else{
                        app.showDeletePayPopup();
                    }
                } else  {
                    var cardnum = $("#checkNum").val(); // 확인번호 입력값
                    if(price == "" || company == "" || cardnum == ""){
                        $("#layerPopup.Popup12").show();
                    }else{
                        app.requestCancelation();
                    }
                }
            }else
            {
                
                if (isClickedButton()) {
                    return;
                }
                var price = $("#uAmount").val(); // 판매금액 입력값
                var company = $(".company").val(); // 상호 선택값
                var issue = $(".issue").val(); // 발급구분 선택값
                
                if ($("#uIssue").val() == '발행안함'){
                    if(price == "" || company == "" ){
                        $("#layerPopup.Popup12").show();
                    }else{
                        app.showDeletePayPopup();
                    }
                } else  {
                    var cardnum = $("#checkNum").val(); // 확인번호 입력값
                    if(price == "" || company == "" || cardnum == ""){
                        $("#layerPopup.Popup12").show();
                    }else{
                        app.requestCancelation();
                    }
                }
            }
         
            
        },
        requestCancelation:function(){
            if(isIphone()){
                var cardNum = "0";
                var approvalNumber = "0";
                
                if($('#checkNum').length > 0)
                {
                   cardNum = $('#checkNum').val();
                }
                
                if($('#uApprovalNumber').length > 0)
                {
                   approvalNumber = $('#uApprovalNumber').val();
                }
                
                var cancelData = {
                    "price":replaceAll($('#uAmount').val(), ",", ""),
                    "sepa":$("#uIssue").val(),
                    "cardNum":cardNum,
                    "readerNumber":$("#catId").val(),
                    "approvalNumber":approvalNumber,
                    "dateOfApproval":$("#uInstPlan").val(),
                    "businessNumber":businessNumber,
                    "productNumber":productNumber
                };
                cordova.plugins.finPlugin.ReqCashCancel(cancelData,
                null,
                function(error){
                    if(error) open_PopupError(error);
                    else open_PopupError('결제 취소 요청에 실패 하였습니다.');
                    cordova.plugins.finPlugin.backButton("", null, null);
                });
            }else {
                var cancelData = {
                    "instPlan":$('#checkNum').val(),
                    "price":replaceAll($('#uAmount').val(), ",", ""),
                    "catId":$("#catId").val(),
                    "sepa":$("#uIssue").val(),
                    "approvalNumber":$("#uApprovalNumber").val(),
                    "approvalDate":$("#uInstPlan").val()
                };
                cordova.plugins.finPlugin.requestPayment(cancelData, function(res){
                    open_PopupError('결제 취소가 완료 되었습니다.');
                    RECEIPT_CASH.DATA.RECEIPT_ID = res;
                    cordova.plugins.finPlugin.moveStack(RECEIPT_CASH.DATA,null, null);
                }, function(error){
                    if(error) open_PopupError(error);
                    else open_PopupError('결제 취소 요청에 실패 하였습니다.');
                });
            }
        },
     reqReadCard:function(){
        if (isClickedButton()) {
            return;
        }
        var price = $("#uAmount").val(); // 판매금액 입력값
        var catId = $('#catId').val(); // 상호 선택값
        if(price == "" || catId == ""){
            $("#layerPopup.Popup12").show();
        }else{
          var f = document.getElementById("checkNum");
          f.type= "text";
          document.getElementById("checkNum").disabled = true;

          var sendData = {
              "price":replaceAll(price, ",", ""),
              "catId":catId
          };
          //open_Progress('카드 읽기를 시작 합니다.');
          app.setCardNum('카드 읽기를 시작 합니다.');
          cordova.plugins.finPlugin.CashCancelReadCard(sendData,function(cardInfo){
//            app.setCardNum('카드 읽기를 시작 합니다.');
            app.setCardNum(cardInfo);
          }, function(error){
            close_Progress();
            showToastMessage(error);
          });
        }

    }, deletePayInfo:function() {
        $('#layerPopup.Popup06').hide();
        //window.AndroidInterface.onClickSign($("#uIssue").val(), $("#uAmount").val(), "", $("#utid").val());
        if (isClickedButton()) {
            return;
        }
        app.requestCancelation();
    },
    replacaSchemeIssued:function(issued){
        if("0" == issued){
            return '소비자 소득공제';
        }else if("1" == issued){
            return '사업자 지출증빙';
        }else if("99" == issued){
            return '자진발급';
        }else return issued;
    },
     showDeletePayPopup:function() {
        $('#layerPopup.Popup06').show();
    },errorOfPaymentByNetwork:function()
    {
        close_PopupError();
        open_PopupError('네트워크 문제로 인하여 결제 요청에 실패 하였습니다.');
        cordova.plugins.finPlugin.backButton("", null, null);
    }
};

app.initialize();
