let androidPhoneNumber;
var product_name;   //define.js에서 재설정이 가능한 항목들은 var 로 선언함
Storage.prototype.setArray = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getArray = function(key) {
    return JSON.parse(this.getItem(key))
}
//null check
function nullcheck(el){
    // console.log(arguments.callee.name,"el의 값:" + el);
    if( el == "" || el == null || el == undefined || ( el != null && typeof el == "object" && !Object.keys(el).length ) ){
        return true;
    } else {
        return false;
    }
}

function toast(msg){
 
	$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h3>"+msg+"</h3></div>")
	.css({ display: "block", 
		position: "fixed",
		padding: "12px",
        "text-align": "center",
        color: "#FFF",
        width: "270px",
        height: "50px",
        background: "#00000080",
        "line-height": "25px",
        "font-weight": "normal",
        "font-size": "11px",
        "border-radius":"25px",
		left: ($(window).width() - 284)/2,
		top: $(window).height()- 80 })
	.appendTo( ".body_wrap" ).delay( 1800 )
	.fadeOut( 100, function(){
		$(this).remove();
    });
}

//alert
function popAlert(msg){
    let alertEl = "<div class='bg_alert on'>";
    alertEl += "<div class='pop_alert'>";
    alertEl += "<p>" + msg.replace("\n", "<br/>") + "</p>";
    alertEl += "<button type='button' class='close_alert'>확인</button>";
    alertEl += "</div>";
    alertEl += "</div>";
    $(".body_wrap").append(alertEl);
}

//alert
function closePopAlert(){
    $(".bg_alert").removeClass("on");
    $(".bg_alert").remove();
}

function getRemovePlusEightTwo(el){
    let telephoneNumber = el;
    telephoneNumber = telephoneNumber.replace( '+82', '0' );
    return telephoneNumber;
}
//alert
function popAlertAction(msg,yesCallback){
    let alertEl = "<div class='bg_alert on'>";
    alertEl += "<div class='pop_alert'>";
    alertEl += "<p>" + msg + "</p>";
    alertEl += "<button type='button' class='close_alert_action'>확인</button>";
    alertEl += "</div>";
    alertEl += "</div>";
    $(".body_wrap").append(alertEl);

    $('.bg_alert.on .close_alert_action').on('click',function() {
        //alert("close_alert_action");
        $(".bg_alert").removeClass("on");
        $(".bg_alert").remove();
        yesCallback();
    });
}
//confirm
function popConfirmAction(msg,yesCallback){
    let alertEl = "<div class='bg_alert on'>";
    alertEl += "<div class='pop_alert'>";
    alertEl += "<p>" + msg.replace("\n", "<br/>") + "</p>";
    alertEl += "<button type='button' class='ok_confirm_action'>확인</button>";
    alertEl += "<button type='button' class='close_confirm_action'>취소</button>";
    alertEl += "</div>";
    alertEl += "</div>";
    $(".body_wrap").append(alertEl);
    
    $('.bg_alert.on .ok_confirm_action').on('click',function() {
        //alert("close_alert_action");
        $(".bg_alert").removeClass("on");
        $(".bg_alert").remove();
        yesCallback();
    });
    $('.bg_alert.on .close_confirm_action').on('click',function() {
        //alert("close_alert_action");
        $(".bg_alert").removeClass("on");
        $(".bg_alert").remove();
    });

}

function popCallAction(msg,noCallback){
    let alertEl = "<div class='bg_alert on'>";
    alertEl += "<div class='pop_alert'>";
    alertEl += "<p>" + msg + "</p>";
    alertEl += "<button type='button' class='ok_confirm_action'>확인</button>";
    alertEl += "<button type='button' class='close_confirm_action'>취소</button>";
    alertEl += "</div>";
    alertEl += "</div>";
    $(".body_wrap").append(alertEl);

    $('.bg_alert.on .ok_confirm_action').on('click',function() {
        $(".bg_alert").removeClass("on");
        $(".bg_alert").remove();
    });
    $('.bg_alert.on .close_confirm_action').on('click',function() {
        noCallback();
        $(".bg_alert").removeClass("on");
        $(".bg_alert").remove();
    });
}

/**
 * product_name : mcaller or callbanner or mbanner
 */
function authorizeCust(product_name){

    if(product_name == undefined){
        try {
            product_name = (title != ''?title.toLocaleLowerCase():'mcaller');
        } catch (error) {
            product_name = 'mcaller';
        }
    }

    let dataSerializer = cordova.plugin.http.getDataSerializer();
    cordova.plugin.http.setDataSerializer('utf8');

    let tempUrl = `http://ent-update.lgntel.com/astroapi/verctrl/v1/appinfo/check/${product_name}/${$(".input_srv_name").val()}`;
    cordova.plugin.http.get(tempUrl, {}, {}, function(response) {
        let jsonData = JSON.parse(response.data);
        let jsonInfo = JSON.parse(jsonData.data.info);
        console.log(jsonInfo.server_host ,jsonInfo.server_port ,jsonInfo.update_name);

        //HP번호, HP모델, OS Version
        $(".loaderWrap").removeClass("hide");
        let companyId = $(".input_srv_name").val();
        let companyPw = $(".input_srv_pw").val();
        let mobileNumber = $(".input_number").val();
        let data = {
            cust_name: companyId, //지엔텔
            cust_pw: companyPw, //test1234
            device_id: device.uuid, // 1EBB6196-7830-46D5-83CC-93359F57CFDA
            device_number: mobileNumber, // 1234567890
            device_model: device.model, // iPhone7,1
            device_os: device.version, // 12.4.6
            device_platform: device.platform, // iOS
            device_app: app_ver_string // 1.0.0.1
        };
        console.log("device.uuid"+device.uuid);
        cordova.plugin.http.setServerTrustMode('nocheck', function() {
            console.log('success!');
        }, function() {
            console.log('error :(');
        });
        console.log("data:"+JSON.stringify(data));
        cordova.plugin.http.post(jsonInfo.server_host +jsonInfo.server_port+ '/astroapi/mdial/v1/searchcust', data, { }, function(response) {
            let jsonData = JSON.parse(response.data);
            let chkJsonData = jsonData["errcode"];
            console.log("jsonData:"+JSON.stringify(jsonData));
            $(".loaderWrap").addClass("hide");
            switch (chkJsonData) {
                case "0":
                    window.localStorage.setArray("serverData", jsonData);
                    //cust_acc_code_used : 중계선호출코드사용여부
                    //Y : 사용함
                    //N : 사용안함
                    //cust_acc_code : 중계선 호출코드
                    //cust_digit_cnt : 중계선 호출코드 적용 자릿수
                    let settingData = {
                        pbxType: jsonData.cust_pbx_type, // CM, FX
                        svcPrefixNo: jsonData.cust_svc_prefix_no, // 거래처 서비스 프리픽스
                        cidLength: jsonData.cust_cid_length, // 내선번호 자리수
                        fsSvcNo: jsonData.cust_fs_svc_no, // 거래처 FS일경우 서비스 번호
                        accCodeUsed: jsonData.cust_acc_code_used,
                        accCode: jsonData.cust_acc_code,
                        digitCount: jsonData.cust_digit_cnt,
                        companyId:companyId,
                        companyPw:companyPw,
                        cust_logo1: jsonData.cust_logo1,
                        cust_logo2: jsonData.cust_logo2,
                        cust_logo3: jsonData.cust_logo3,
                        autoLogin:"",
                        checkIdSave:"",
                        savedId:"",
                        mobileNumber:mobileNumber,
                        prefixNumber:"1000",
                        server_host : server_host,
                        server_port : server_port,
                    };
                    window.localStorage.setArray("settingData", settingData);

                    let OS = "IOS";
                    if ( device.platform == "Android" ) {
                        OS = "ANDROID";
                    }

                    // 업데이트 및 페이지 이동
                    window.plugins.gntel.setUpdateContentsUrl("https://ent-update.lgntel.com/astroapi/verctrl/v1/check/" + jsonInfo.update_name + "/" + OS, function() {
                        $("#loading-overlay").fadeIn();
                        window.plugins.gntel.updateContents(function () {
                            $("#loading-overlay").fadeOut();
                            window.plugins.gntel.loadLocalFile("index.html");
                        }, function () {
                            $("#loading-overlay").fadeOut();
                            window.plugins.gntel.loadLocalFile("index.html");
                        })
                    });

                    break;
                case "100":
                case "101":
                    popAlert("인증 정보를 확인해 주세요.");
                    break;
                case "110":
                    popAlert("서비스 기간이 만료 되었습니다.");
                    break;
                case "111":
                    popAlert("라이선스가 초과 되었습니다.");
                    break;
                case "112":
                    popAlert("서비스가 중지 되었습니다.");
                    break;
                default:
                    console.log('searchcust in response error :: ', response);
                    popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요.");
            }
        }, function(response) {
            $(".loaderWrap").addClass("hide");
            // prints 403
            console.log("searchcust :: response status:"+response.status);
            //prints Permission denied
            console.log('searchcust :: ',response.error);
            popAlert("인증 정보 확인중 오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요.");
        });
    }, function(response) {
        console.log(tempUrl);
        console.log("response status:"+response.status);
        console.log(response.error);
        popAlert("앱 정보 확인중 오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요.");
    });

    cordova.plugin.http.setDataSerializer(dataSerializer);
}

$(document).on("click", ".close_alert", function(){
    $(".bg_alert").removeClass("on");
    $(".bg_alert").remove();
});

function successCallback(result) {
    
    androidPhoneNumber=getRemovePlusEightTwo(result.phoneNumber);
    window.localStorage.setItem("androidPhoneNumber", androidPhoneNumber);//저장
    //alert("androidPhoneNumber"+androidPhoneNumber);
    console.log(arguments.callee.name,"androidPhoneNumber"+androidPhoneNumber);
    console.log(arguments.callee.name,"successCallback" + JSON.stringify(result));
    checkLocation();
}

function errorCallback(error) {
    console.log(arguments.callee.name,error);
    checkLocation();
}

// Android only: check permission
function hasReadPermission() {
    window.plugins.sim.hasReadPermission(hasSuccessCallback, hasErrorCallback);
}
function hasSuccessCallback(result) { 
    
    console.log(arguments.callee.name,"hasSuccessCallback" + JSON.stringify(result));
    console.log(arguments.callee.name,"hasSuccessCallback" + result);
    if(result){
        window.plugins.sim.getSimInfo(successCallback, errorCallback);
    }else{
        requestReadPermission();
    }
}

function hasErrorCallback(error) {
    console.log(arguments.callee.name,"hasErrorCallback" + error);
    requestReadPermission();
}
// Android only: request permission
function requestReadPermission() {
    window.plugins.sim.requestReadPermission(requestSuccessCallback, requestErrorCallback);
}
function requestSuccessCallback(result) {
    //window.plugins.sim.getSimInfo(successCallback, errorCallback); 
    console.log(arguments.callee.name,"requestSuccessCallback" + JSON.stringify(result));
    if(result == "OK"){
        window.plugins.sim.getSimInfo(successCallback, errorCallback);
    }else{
        requestReadPermission();
    }
}

function requestErrorCallback(error) {
    //checkLocation();
    popAlertAction("전화에 대한 권한을 허용 하셔야 사용 하실 수 있습니다.",function() {
        //hasReadPermission()
        navigator.app.exitApp();
    });
    console.log(arguments.callee.name,"requestErrorCallback" + error);
}

//alert
function popAlert_noti(msg, msg1){

    let alertEl = "<div class='bg_alert on'>";
    alertEl += "<div class='pop_alert'>";
    alertEl += "<p>" + msg + "</p>";
    alertEl += "<p>" + msg1 + "초 후에 통화가 진행됩니다. </p>";
    alertEl += "</div>";
    $(".body_wrap").append(alertEl);
}


// console log -> native 앱에 저장
let console=(function(oldCons){
    return {
        log: function(text){
            for(let idx=1;idx< arguments.length;idx++){
                text += (' ,'+arguments[idx]);
            }
            oldCons.log(text);
            try {
                window.plugins.gntel.pushGLog("log", text);
            } catch (ex) {}
        },
        info: function (text) {
            for(let idx=1;idx< arguments.length;idx++){
                text += (' ,'+arguments[idx]);
            }
            oldCons.info(text);
            try {
                window.plugins.gntel.pushGLog("info", text);
            } catch (ex) {}
        },
        warn: function (text) {
            for(let idx=1;idx< arguments.length;idx++){
                text += (' ,'+arguments[idx]);
            }
            oldCons.warn(text);
            try {
                window.plugins.gntel.pushGLog("warn", text);
            } catch (ex) {}
        },
        error: function (text) {
            for(let idx=1;idx< arguments.length;idx++){
                text += (' ,'+arguments[idx]);
            }
            oldCons.error(text);
            try {
                window.plugins.gntel.pushGLog("error", text);
            } catch (ex) {}
        }
    };
}(window.console));
window.console = console;

$(()=>{
    $(".company_logo0").attr("src", company_logo0);
    $(".title").text(title);
})