
//설정
document.addEventListener('deviceready', ()=>{
    cordova.exec((r)=>{
        let json = null;
        try{
            json = JSON.parse(r);
        }catch(e){
            json = r;
        }

        $(`.panel_namecard_setting [name=namecard_use][value=${json.is_show?true:false}]`).prop('checked', true)

        let namecard_dir_path ='www/namecard';
        cordova.exec((filelist)=>{
                let idx = 0;
                try {
                    filelist.split(',').map(filename => {
                        $('#div_setting_namecards').append(
                            $('#template_namecard_preview').text()
                            .replace(/{{idx}}/g, idx)
                            .replace(/{{displayName}}/g, `선택${++idx}`)
                            .replace(/{{fileName}}/g, `${namecard_dir_path.replace('www/','')}/${filename}`)
                            .replace(/{{checked}}/g, json.namecard_default.indexOf(filename)>-1?'checked':'')
                        )
                    });
                } catch (error) {
                    console.error('cannot display namecards',error);
                }

                try {
                    if(settingData.profile_used == 'Y' && (devicePlatform||'').toUpperCase() == "ANDROID"){
                        $('#setting .setting_conts>.menu_tab>button.btn_namecard_setting').show();
                        $('#setting .setting_conts>.menu_tab').removeClass('two');

                        $('input[type=radio][name=namecard_use][value=true]').prop('checked', true);

                        if($('input[type=radio][name=namecard]:checked').length == 0){
                            if((settingData.default_profile||'') == ''){
                                $('input[type=radio][name=namecard]:eq(0)').prop('checked', true).trigger('click');
                            }else{
                                $(`input[type=radio][name=namecard][value*="${settingData.default_profile}"]`).prop('checked', true).trigger('click');
                            }
                        }
                        
                    }else{
                        $('#setting .setting_conts>.menu_tab>button.btn_namecard_setting').hide();
                        $('#setting .setting_conts>.menu_tab').addClass('two');
                        $('input[name=namecard_use][value=false]').prop('checked', true).trigger('click');
                    }
                } catch (error) {
                    
                }

        }, (f) =>{
            console.error('can not exec getNameCardsList', f );
        }, "GntelPlugin", "getNameCardsList", [namecard_dir_path]);

    }, (f)=>{
        console.error('can not exec getNamecardSettings', f )
    }, "GntelPlugin", "getNamecardSettings", null);


});


$(()=>{

    cordova.getAppVersion.getVersionNumber().then(function (version) {
        $('.info_app_version').val(version);
        $('.info_contents_version').val(contents_version);
        $('.info_domain').val(server_debug_description);
    });
    
    $(".privacy").on("click",function(){
        // let ref = cordova.InAppBrowser.open(href="./privacy.html", '_blank', 'location=yes');
        let ref = cordova.InAppBrowser.open(privacy_url, '_blank', 'location=yes,x=0,y=200,width=437,height=650');
    });

    ////////////////////////////////////////////
    /////////////////설정 페이지/////////////////
    ////////////////////////////////////////////

    $('.panel_namecard_setting').on('click', 'input[type=radio][name=namecard],input[type=radio][name=namecard_use]', function(){
        let json = {
            is_show: ($('[name=namecard_use]:checked').val() === 'true'?true:false)
        };
        
        if($('[name=namecard]:checked').val() != undefined){
            json.namecard_default = $('[name=namecard]:checked').val();
        }

        cordova.exec((r)=>{
            console.log('success setNamecardSettings', JSON.stringify(json));
        }, null, "GntelPlugin", "setNamecardSettings", ['www/', JSON.stringify(json)]);
    });

    $('.setting_conts>.menu_tab button').on('click', function(){
        $('.setting_conts>.menu_tab button.selected').removeClass('selected');
        $(this).addClass('selected');
        if($(this).hasClass('btn_basic_setting')){
            $(".panel_basic_setting").show();
            $(".panel_rev_info").hide();
            $(".panel_namecard_setting").hide();
            $(".save_setting").show();
        }else if($(this).hasClass('btn_rev_info')){
            $(".panel_rev_info").show();
            $(".panel_basic_setting").hide();
            $(".panel_namecard_setting").hide();
            $(".save_setting").hide();
        }else if($(this).hasClass('btn_namecard_setting')){
            $(".panel_rev_info").hide();
            $(".panel_basic_setting").hide();
            $(".panel_namecard_setting").show();
            $(".save_setting").hide();
        }
    })

    //로그아웃 버튼
    $(".btn_logout").click(function(){
        popConfirm("로그아웃 하시겠습니까?", function() {
            logOut()
        });
    });
    //설정 서버 업데이트 버튼
    $(".update_setting").click(function(){
        popConfirm("설정 값을 서버로부터\n새로 업데이트합니다.", function() {
            serverUpdate()
        });
    })
    //설정 서비스 탈퇴 버튼
    $(".ser_sc").click(function(){
        popConfirm("서비스 이용을 종료합니다.<br>다시 이용하실 경우는 처음부터 재 설치 절차를 수행하셔야 합니다.", function() {
            serviceSecession()
        });
    });

    //설정 중계선 호출코드 스위치 버튼
    $("#set_relay").on("change", function(){
        if($("#set_relay").is(':checked')){
            $(".set_code").prop("readonly",true);
            $(".set_digit").prop("readonly",true);
        }else{
            $(".set_code").prop("readonly",true);
            $(".set_digit").prop("readonly",true);
        }
    });

    //설정 저장 버튼
    $(".save_setting").click(function(){

        let dataSerializer = cordova.plugin.http.getDataSerializer();

        cordova.plugin.http.setDataSerializer('utf8');
    
        let params = {
            allow_push : $('#set_allow_push').is(':checked')?'Y':'N'
        };

        if($('[name=set_push_duration]:checked').val() == 'spec' ){
            if($('#set_push_start_time').val() == '' || $('#set_push_end_time').val() == ''){
                return popAlert('푸시 수신시간을 정확히 입력하세요.');
            }else{
                params.push_start_time = $('#set_push_start_time').val();
                params.push_end_time = $('#set_push_end_time').val();
            }
        } 

        let tempUrl = `${server_host}${server_port}/astroapi/mdial/v1/device/${serverData.corp_code}/${settingData.mobileNumber}/${device.uuid}`;

        // mdialer service 백엔드 보완패치 반영시 변경 필요.
        // let tempUrl = `${server_host}${server_port}/astroapi/mdial/v1/device/${serverData.corp_code}/${settingData.mobileNumber}/${device.uuid}/${settingData.prefixNumber}`;
        console.log(tempUrl);
        cordova.plugin.http.put(tempUrl, JSON.stringify(params), {
            Authorization: 'Bearer '+ userData.astroToken,
            'Content-Type': 'application/json'
        }, function(response) {
            let jsonData = JSON.parse(response.data);
            console.log('changePassword',"jsonData:"+JSON.stringify(jsonData));
            if(!nullcheck(jsonData.data)){
                //자동로그인
                if($("#set_auto").is(':checked')){
                    settingData.autoLogin = "true";
                }else{
                    settingData.autoLogin = "";
                }
                //중계선호출코드
                if($("#set_relay").is(':checked')){
                    settingData.accCodeUsed = "Y";
                }else{
                    settingData.accCodeUsed = "N";
                }

                settingData.accCode = $(".set_code").val();
                settingData.digitCount = $(".set_digit").val();
                settingData.mobileNumber = $(".myMobileNumber").val();
                settingData.prefixNumber = $(".myPrefixNumber").val();
                settingData.prefixEx = $(".prefixEx").val();
                settingData.method_callback = $('#method_callback').prop("checked");
                settingData.method_callthrough = $('#method_callthrough').prop("checked");
                settingData.method_click_to_call = $('#method_click_to_call').prop("checked");
                settingData.allow_push = params.allow_push;
                settingData.push_start_time = params.push_start_time;
                settingData.push_end_time = params.push_end_time;
                window.localStorage.setItem("prefixEx",$(".prefixEx").val());
                window.localStorage.setArray("settingData", settingData);
                popAlert("설정이 저장 되었습니다.");
            }else if(!nullcheck(jsonData.error)){
                popAlert(jsonData.error.message);
            }else{
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            }
            return;
        }, function(response) {
            // prints 403
            console.log('changePassword',"response status:"+response.status);
            //prints Permission denied
            console.log('changePassword',response.error);
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    
        cordova.plugin.http.setDataSerializer(dataSerializer);
    });

    //비밀번호 변경 띄우기
    $(".rev_pw").on("click", function(){
        $(".bg_rev_pw").show();
        setTimeout(() => {
            $(".bg_rev_pw").addClass("on");
        }, 50);

    });
    //닫기
    $(".close_rev_pw").on("click", function(){
        $(".new_password").val('');
        $(".re_password").val('');
        $(".bg_rev_pw").removeClass("on");
        setTimeout(() => {
            $(".bg_rev_pw").hide();
        }, 200);
    });
    //비밀번호 변경 확인
    $(".confirm_rev_pw").on("click", function(){
        changePassword();
    });

    //푸시서비스 설정
    $('input[name=set_push_duration]').on('change', function(){
        $('#set_push_start_time,#set_push_end_time').prop('readonly', ($(this).val() == 'spec'?false:true));
    });
});

//서비스 탈퇴
function serviceSecession(){
    $(".loaderWrap").removeClass("hide");
    let data = {
        cust_pw: settingData.companyPw, //test1234
        device_id: device.uuid, // 1234567890
        device_number: settingData.mobileNumber,
        cust_name: settingData.companyId,
        cid_no: settingData.prefixNumber
    };

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('serviceSecession','success!');
    }, function() {
        console.log('serviceSecession','error :(');
    });
    cordova.plugin.http.post(server_host +server_port+ '/astroapi/mdial/v1/unregdevice', data, {
        Authorization: 'Bearer '+userData.astroToken
     }, function(response) {
        let jsonData = JSON.parse(response.data);
        let chkJsonData = jsonData["errcode"];
        console.log('serviceSecession',"jsonData:"+JSON.stringify(jsonData));
        $(".loaderWrap").addClass("hide");
        switch (chkJsonData) {
            case "0":
                let androidPhoneNumber = window.localStorage.getItem("androidPhoneNumber");//저장
                //let permissionChecked = window.localStorage.getItem("permissionChecked");//저장
                window.localStorage.clear();
                //window.localStorage.setItem("permissionChecked", permissionChecked);//저장
                window.localStorage.setItem("androidPhoneNumber", androidPhoneNumber);//저장

                //permissionChecked
                location.href = "server.html";
                break;
            case "100":
                popAlert("비밀번호를 확인해 주세요");
                break;
            default:
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }
    }, function(response) {
        $(".loaderWrap").addClass("hide");
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function logOut(){
    window.localStorage.setArray("userData", []);//저장
    window.localStorage.setItem("autoLoginSave", "");//저장
    location.href = "login.html";
}

function serverUpdate(){
    $(".loaderWrap").removeClass("hide");

    console.log('serverUpdate',"app_ver_string:"+app_ver_string);
    let data = {
        cust_name: settingData.companyId, //지엔텔
        cust_pw: settingData.companyPw, //test1234
        device_id: device.uuid, // 1EBB6196-7830-46D5-83CC-93359F57CFDA
        device_number: settingData.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
    };


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

    console.log('serverUpdate',"data:"+JSON.stringify(data));

    cordova.plugin.http.post(server_host +server_port+ '/astroapi/mdial/v1/searchcust', data, { 
        Authorization: 'Bearer '+userData.astroToken
    }, function(response) {
        let jsonData = JSON.parse(response.data);
        let chkJsonData = jsonData["errcode"]||jsonData.code;
        console.log('serverUpdate',"jsonData:"+JSON.stringify(jsonData));
        $(".loaderWrap").addClass("hide");

        switch (chkJsonData) {
            case "0":
            case "0000":
                searchCustSuccessCallback(settingData, jsonData);
                settingRefresh();
                refreshButtuons();
                popAlert("시스템 동기화가 완료 되었습니다.");
                break;
            case "100":
                popAlert("비밀번호를 확인해 주세요");
                break;
            default:
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
                break;
        }

    }, function(response) {
        $(".loaderWrap").addClass("hide");
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function settingRefresh(){
    let autoLogin = settingData.autoLogin;
    let method_callback = settingData.method_callback
    let method_callthrough = settingData.method_callthrough
    let method_click_to_call = settingData.method_click_to_call

    if(method_callback == true){
        $("#method_callback").prop("checked", true).checkboxradio("refresh");
    }
    if(method_callthrough == true){
        $("#method_callthrough").prop("checked", true).checkboxradio("refresh");
    }
    if(method_click_to_call == true){
        $("#method_click_to_call").prop("checked", true).checkboxradio("refresh");
    }

    if(!nullcheck(autoLogin) && autoLogin == 'true'){
        $("#set_auto").prop("checked", true).checkboxradio("refresh");
    }else{
        $("#set_auto").prop("checked", false).checkboxradio("refresh");
    }
    //중계선호출코드 사용여부
    let accCodeUsed = settingData.accCodeUsed;
    if(!nullcheck(accCodeUsed) && accCodeUsed == 'Y'){
        $("#set_relay").prop("checked", true).checkboxradio("refresh");
        $(".set_code").prop("readonly",true);
        $(".set_digit").prop("readonly",true);
    }else{
        //alert("2");
        $("#set_relay").prop("checked", false).checkboxradio("refresh");
        $(".set_code").prop("readonly",true);
        $(".set_digit").prop("readonly",true);
    }


    console.log('settingRefresh',"settingData:"+JSON.stringify(settingData));
    //중계선호출코드
    let accCode = settingData.accCode;
    // if(!nullcheck(accCode)){
        $(".set_code").val(accCode);
    // }
    //중계선호출코드 적용 자리수
    let digitCount = settingData.digitCount;
    if(!nullcheck(digitCount)){
        $(".set_digit").val(digitCount);
    }

    //HP번호
    let mobileNumber = settingData.mobileNumber;
    if(!nullcheck(mobileNumber)){
        $(".myMobileNumber").val(mobileNumber);
    }

    //내선번호
    let prefixNumber = settingData.prefixNumber;
    if(!nullcheck(prefixNumber)){
        $(".myPrefixNumber").val(prefixNumber);
    }

    //내선지역번호
    let prefixEx = settingData.prefixEx;
    if(!nullcheck(prefixEx)){
        $(".prefixEx").val(prefixEx);
    }

    
    // 아이디
    let user_id = userData.userId;
    if(!nullcheck(user_id)){
        $(".setting_userId").val(user_id);
    }

    // 이름
    let name = userData.userName;
    if(!nullcheck(name)){
        $(".setting_userName").val(name);
    }

    //푸시서비스 수신허용
    let allow_push = settingData.allow_push;
    if(!nullcheck(allow_push) && allow_push == 'Y'){
    // if(allow_push == 'Y'){
        $('#set_allow_push').prop('checked', true);
    }else{
        $('#set_allow_push').prop('checked', false);
    }
    $('#set_allow_push').checkboxradio('refresh');

    //푸시서비스 수신 시간설정

    if(!nullcheck(settingData.push_start_time) && !nullcheck(settingData.push_end_time)){
        $('[name=set_push_duration][value=spec]').prop('checked', true).trigger('change');
        $('#set_push_start_time').val(settingData.push_start_time);
        $('#set_push_end_time').val(settingData.push_end_time);
    }else{
        $('[name=set_push_duration][value=allday]').prop('checked', true).trigger('change');
        $('#set_push_start_time').val('');
        $('#set_push_end_time').val('');
    }
}

function passwordCheck(el){
    //alert(el.length);
    if( el.length > 3 && el.length <11){
        //alert("1"+el.length);
        return true;
    } else {
        //alert("2"+el.length);
        return false;
    }
}
function changePassword(){
    
    let new_password = $(".new_password").val();
    let re_password = $(".re_password").val();

    if(!passwordCheck(new_password)){
        popAlert("새로운 비밀번호는 4~10자 입니다.");
        return;
    }else if(!passwordCheck(re_password)){
        popAlert("비밀번호 확인은 4~10자 입니다.");
        return;
    }else if(re_password != new_password){
        popAlert("비밀번호 확인이 일치하지 않습니다.");
        return;
    }

    let params ={
        url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/password?password=${new_password}`
        ,token : window.localStorage.getArray('userData').token
    };

    requestToCm(params , (response) => {
        console.log('changePassword',"jsonData:"+JSON.stringify(response.data));
        if(!nullcheck(response.data.data)){
            window.localStorage.setArray("userData", response.data.data);//저장
            $(".bg_rev_pw").removeClass("on");
            $(".bg_rev_pw").hide();

            $(".new_password").val("");
            $(".re_password").val("");

            popAlert("비밀번호가 변경 되었습니다.");
        }else if(!nullcheck(response.data.error)){
            popAlert(response.data.error.message);
        }
    });
}

const onHtmlObjectLoaded = (item) =>{
    item.height = `${item.contentDocument.body.scrollHeight}px`;
    $(item.contentDocument.body).find('a.close,span.close').remove();
};
