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, callback){
    let alertEl = 
    `<div class='bg_alert on'>
        <div class='pop_alert'>
            <p>${msg.replace("\n", "<br/>") }</p>
            <button type='button' class='close_alert'>확인</button>
        </div>
    </div>`;
    $(".body_wrap").append(alertEl);

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

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

function getRemovePlusEightTwo(el){
    let telephoneNumber = el;
    telephoneNumber = telephoneNumber.replace( '+82', '0' );
    return telephoneNumber;
}

//confirm
function popConfirm(msg,yesCallback){
    let alertEl = 
    `<div class='bg_alert on'>
        <div class='pop_alert'>
            <p>${msg.replace("\n", "<br/>")}</p>
            <button type='button' class='ok_confirm_action'>확인</button>
            <button type='button' class='close_confirm_action'>취소</button>
        </div>
    </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'>
        <div class='pop_alert'>
            <p>${msg}</p>
            <button type='button' class='ok_confirm_action'>확인</button>
            <button type='button' class='close_confirm_action'>취소</button>
        </div>
    </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);

        $(".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,
            device_id: device.uuid,
            device_number: mobileNumber,
            device_model: device.model,
            device_os: device.version,
            device_platform: device.platform,
            device_app: app_ver_string
        };

        console.log("device.uuid" + device.uuid);

        cordova.plugin.http.setServerTrustMode('nocheck', function () {
            console.log('success!');

            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":
                        let settingData = {
                            companyId: companyId,
                            companyPw: companyPw,
                            autoLogin: "",
                            checkIdSave: "",
                            savedId: "",
                            mobileNumber: mobileNumber,
                            prefixNumber: "1000",
                            server_host: jsonInfo.server_host,
                            server_port: jsonInfo.server_port,
                            otp_used: jsonData.otp_used,
                            otp_type: jsonData.otp_type,
                            request_cm_through_astro: jsonData.request_cm_through_astro
                        };

                        searchCustSuccessCallback(settingData, jsonData);

                        let OS = device.platform === "Android" ? "ANDROID" : "IOS";

                        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");
                console.log("searchcust :: response status:" + response.status);
                console.log('searchcust :: ', response.error);
                popAlert("인증 정보 확인중 오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요.");
            });

        }, function () {
            console.log('setServerTrustMode error :(');
            popAlert("SSL 보안 설정 중 오류가 발생했습니다.");
        });
    }, 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() {
    try {
        window.plugins.sim.hasReadPermission(hasSuccessCallback, hasErrorCallback);
    } catch (error) {}
}
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);
    }
}

function requestErrorCallback(error) {
    //checkLocation();
    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);
}

const searchCustSuccessCallback = (settingData, jsonData) => {
    window.localStorage.setArray("serverData", jsonData);

    let keyset = [
        { settingkey: 'pbxType', jsonkey: 'cust_pbx_type' },
        { settingkey: 'svcPrefixNo', jsonkey: 'cust_svc_prefix_no' },
        { settingkey: 'cidLength', jsonkey: 'cust_cid_length' },
        { settingkey: 'fsSvcNo', jsonkey: 'cust_fs_svc_no' },
        { settingkey: 'accCodeUsed', jsonkey: 'cust_acc_code_used' },
        { settingkey: 'accCode', jsonkey: 'cust_acc_code' },
        { settingkey: 'digitCount', jsonkey: 'cust_digit_cnt' },
        { settingkey: 'cust_logo1', jsonkey: 'cust_logo1' },
        { settingkey: 'cust_logo2', jsonkey: 'cust_logo2' },
        { settingkey: 'cust_logo3', jsonkey: 'cust_logo3' },
        { settingkey: 'cust_func_code', jsonkey: 'cust_func_code' },
        { settingkey: 'rootGroupcode', jsonkey: 'rootGroupcode' },
        { settingkey: 'notice_used', jsonkey: 'notice_used', default: 'Y' },
        { settingkey: 'notice_def_remains', jsonkey: 'notice_def_remains', default: '0' },
        { settingkey: 'noticeManageGroups', jsonkey: 'notice_manage_groups' },
        { settingkey: 'forward_call_mention', jsonkey: 'forward_call_mention' },
        { settingkey: 'callThruPrefix', jsonkey: 'call_thru_prefix', default: '' },
        { settingkey: 'profile_used', jsonkey: 'profile_used' },
        { settingkey: 'default_profile', jsonkey: 'default_profile' },
        { settingkey: 'etcNo', jsonkey: 'etc_no' }  // etcNo 세팅 추가
    ];

    keyset.map(item => {
        if (jsonData[item.jsonkey] !== undefined) {
            settingData[item.settingkey] = jsonData[item.jsonkey];
        } else if (item.default !== undefined) {
            settingData[item.settingkey] = item.default;
        }
    });

    // CM 연동 여부 플래그 설정
    const cmMode = jsonData.request_cm_through_astro === true || jsonData.request_cm_through_astro === "Y";
    settingData.cmMode = cmMode;

    // prefixEx 정리
    if (!nullcheck(settingData.prefixNumber)) {
        let dn = settingData.prefixNumber;
        dn = dn.substring(dn.length - Number(settingData.cidLength), dn.length);

        let prefixEx = '';
        if (settingData.pbxType === "FS") {
            prefixEx = settingData.svcPrefixNo + settingData.fsSvcNo;
        } else if (settingData.pbxType === "CM" && cmMode) {
            prefixEx = settingData.etcNo || '';
        } else {
            prefixEx = settingData.svcPrefixNo + dn;
        }

        window.localStorage.setItem("prefixEx", prefixEx);
        settingData.prefixEx = prefixEx;
    }

    // OTP 관련 설정도 settingData에 저장 (추가적인 활용 시 대비)
    settingData.otp_used = jsonData.otp_used;
    settingData.otp_type = jsonData.otp_type;

    window.localStorage.setArray("settingData", settingData);
};


// 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;

$(()=>{
    if(typeof company_logo0 !=="undefined"){
        $(".company_logo0").attr("src", company_logo0);
    }

    if(typeof title !== "undefined"){
        $(".title").text(title);
    }
})