(()=>{
    'use strict';
    
    $(()=>{
    
        $('#setting_login_user_name').text(userData.userName);
    
        $(".tab_btn_setting > li").click(function(){
            $(".tab_btn_setting > li.on").removeClass("on");
            $(this).addClass("on");
    
            $(".tab_wrap_setting > li:not(.none)").addClass("none");
            $(".tab_wrap_setting > li").eq($(this).index()).removeClass("none");
        });
    
        //테마설정 탭
        $('#tab_theme').on('click', () => {
            drawNamecards();
        });
    
        new Swiper(".skinSwiper", {
            slidesPerView: 3.5,
            spaceBetween: 10,
            freeMode: true,
        });
        let settings = localStorage.getArray('settings');
    
        $(`.skinSwiper input[type=radio][name=skin][data-theme=${settings.theme||'theme00'}]`).prop('checked', true);
    
        $(`.font-size input[type=radio][name=font][data-font=${settings.font||'font_basic'}]`).prop('checked', true);
    
    // ------------------착신전환 시작
    
        for(let idx = 0;idx<23;idx++){
            $('.select-hour').append(
                `<option ${idx==0?'selected':''}>${idx>8?(idx+1):('0'+idx)}:00</option>`
            );
        }
    
        //착신전화 등록 버튼
        $("#btn_reg_forward").on("click", function(){
            
            let time_type = $('#select_forward_time_type').val();
            let start_time = $("#select_forward_start_time").val();
            let stop_time = $("#select_forward_end_time").val();
            let type = $('input[name="forward_type"]:checked').val();
            let to = $("#inp_forward_number").val();
    
            // 매일이면 시간 강제입력 (어자피 사용하지 않음)
            if ( time_type == 4 && (start_time == "" || stop_time == "" ) ) {
                popAlert("착신전환 동작시간을 입력해주세요.");
                return;
            }
            
            if(!phonenumberValidation(to)){
                popAlert("착신전환 등록전화번호를 확인해 주세요.");
                return;
            }
            let params ={
                url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/cfwd?to=${to}&start_time=${start_time}&type=${type}&time_type=${time_type}&stop_time=${stop_time}`
                ,token : window.localStorage.getArray('userData').token
            };
            requestAstro(`ipecscm/v1/rest/callrequest`, params , 'post' )
            .then((response) => {
                console.log('regist forward', 'params', params, 'response',  response);
                if(response.data.error.message == 'OK'){
                    popAlert("착신전환이 등록 되었습니다.");
                    getForward();
                }else{
                    popAlert(response.data.error.message);
                }
            });
        });
    
        //착신전화 해제 버튼
        $("#btn_release_forward").on("click", function(){
            
            let time_type = $('#select_forward_time_type').val();
            let start_time = $("#select_forward_start_time").val();
            let stop_time = $("#select_forward_end_time").val();
            let type = "0";
            let to = $("#inp_forward_number").val();
    
            let params ={
                url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/cfwd?to=${to}&start_time=${start_time}&type=${type}&time_type=${time_type}&stop_time=${stop_time}`
                ,token : window.localStorage.getArray('userData').token
            };
            requestAstro(`ipecscm/v1/rest/callrequest`, params , 'post')
            .then( (response) => {
                if(response.data.error.message == 'OK'){
                    popAlert("착신전환이 해제 되었습니다.");
                    getForward();
                }else{
                    popAlert(response.data.error.message);
                }
            });
        });
            
    // ------------------착신전환 끝
    
    //---------------테마설정 시작
    
        $('.skinSwiper').on('click', '.swiper-slide', (e)=>{
            $(e.currentTarget).find('input[type=radio][name=skin]').trigger('click');
        });
    
        $('input[type=radio][name=skin]').on('click', (e) => {
            e.stopPropagation();
            localStorage.setArray('settings', {
                ...localStorage.getArray('settings')
                ,theme: $(e.currentTarget).data('theme')
            });
            applySettings();
        })
    
        $('input[type=radio][name=font]').on('click', (e) => {
            e.stopPropagation();
            localStorage.setArray('settings', {
                ...localStorage.getArray('settings')
                ,font: $(e.currentTarget).data('font')
            });
            applySettings();
        });
    
        $('.dl_namecard').on('click', 'input[type=radio][name=profile],input[type=radio][name=profile_use]', (e) => {
            e.stopPropagation();
    
            let json = {
                is_show: ($('.dl_namecard [name=profile_use]:checked').val() === 'true'?true:false)
            };
            
            if($('[name=profile]:checked').val() != undefined){
                json.namecard_default = $('[name=profile]:checked').val();
            }
    
            console.log('setNamecardSettings', json);
            if(window.device == 'undefined') return;
    
            cordova.exec((r)=>{
                console.log('success setNamecardSettings', JSON.stringify(json));
            }, (error) => {
                console.error(error);
            }, "GntelPlugin", "setNamecardSettings", ['www/', JSON.stringify(json)]);
        });
    
    //---------------테마설정 끝
    
    // -----------------------메뉴설정 시작
    
        $('#ul_menu_sort').empty();
        menu_info.map((item, idx) => {
            $('#ul_menu_sort').append(
                substituteVariables($('#template_drop_sort_menu').text(), item)
            );
        });
    
        $(".tab_wrap_setting .num_list").dragsort({ dragSelector: "li", dragEnd: function() { }, dragBetween: false, placeHolderTemplate: "<li></li>" });
    
        $('#btn_save_menu').on('click', (e) =>{
            let sorted_menu_info = [];
            $('#ul_menu_sort p').map((idx, item) => {
                sorted_menu_info.push({
                    id : $(item).data('id'),
                    name : $(item).text(),
                    icon : $(item).data('icon'),
                    filepath : $(item).data('filepath')
                });
            });
            localStorage.setArray('menu_info', sorted_menu_info);
            menu_info = sorted_menu_info;
            popAlert('메인화면 아이콘 순서가<br/>변경되었습니다.');
        });
    
        $('#btn_reset_menu').on('click', (e) => {
            $('#ul_menu_sort').empty();
            menu_info.map((item, idx) => {
                $('#ul_menu_sort').append(
                    substituteVariables($('#template_drop_sort_menu').text(), item)
                );
            });
        })
        
    // -----------------------메뉴설정 끝

    // -----------------------기본설정 시작
        drawSettings();

        $('#btn_setting_privacy').on('click', () =>{
            cordova.InAppBrowser.open(privacy_url, '_blank', 'location=yes,x=0,y=200,width=437,height=650');
        });

        //시스템 설정 동기화
        $('#btn_setting_update_server_data').on('click', () =>{
            let params = new FormData();
            params.append('cust_name',`${serverData.companyId}`);
            params.append('cust_pw', `${serverData.companyPw}`);

            requestAstro(
                `mdial/v1/searchcust`
                , params
                , 'post'
            )
            .then(response => {
                let code = response.code || response.errcode
                switch (code) {
                    case "0000":
                    case "0":

                        syncServerData(
                            {
                                ...response,
                                companyId: `${serverData.companyId}`,
                                companyPw: `${serverData.companyPw}`
                            }
                        );
                        popAlert("시스템 설정 동기화가 완료 되었습니다.", drawSettings);
                        break;

                    default:
                        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
                        break;
                }
            });
        });

        //비밀번호 변경 팝업
        $('#btn_setting_change_password').on('click', () =>{
            $('.password_pop input[type=password]').val('');
            $('.password_pop').removeClass('none');
        });

        //서비스 탈퇴
        $('#btn_setting_unreg_device').on('click', () => {
            popConfirm("서비스 이용을 종료합니다.<br>재로그인이 필요합니다.", function() {
                let params = new FormData();
                params.append('cust_name', serverData.companyId);
                params.append('cust_pw', serverData.companyPw);
                params.append('device_id', userData.device_uuid);
                params.append('device_number', userData.mobileNumber);
                params.append('cid_no', userData.dn);

                requestAstro(`mdial/v1/unregdevice`, params, 'post')
                .then(r => {
                    let code = r.code||r.errcode;

                    switch (code) {
                        case '0':
                        case '0000':
                            logout(true);
                            break;
                        case '100':
                            popAlert("비밀번호를 확인해 주세요");
                        default:
                            popAlert("오류가 발생했습니다.<br/>관리자에게 문의하세요.");
                            break;
                    }
                });
            });
        });

        //저장버튼
        $('#btn_setting_save').on('click', (e)=>{
            let params = {
                allow_push : $('#inp_setting_allow_push').is(':checked')?'Y':'N'
            };

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

            requestAstro(`mdial/v1/device/${serverData.corp_code}/${userData.mobileNumber}/${userData.device_uuid||''}`, params, 'put')
            .then(r =>{
                if(r.data){
                    //자동로그인
                    syncUserData({
                        autoLogin : $("#inp_setting_auto_login").is(':checked')?'true':'false',
                        allow_push : params.allow_push,
                        push_start_time : params.push_start_time,
                        push_end_time : params.push_end_time
                    });
        
                    syncServerData({
                        accCodeUsed : $('#inp_setting_acc_code_used').is(':checked')?'Y':'N'
                    });

                    popAlert("설정이 저장 되었습니다.");
                }else{
                    popAlert(r.error?.message||"오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
                }
            });
        });

        //초기화
        $('#btn_setting_reset').on('click', () => {
            drawSettings();
        });

    // -----------------------기본설정 끝
    
        getForward();
    });
    
    let getForward = () => {
    
        let params ={
            url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/cfwd`
            ,token : window.localStorage.getArray('userData').token
            ,method : 'GET'
        };
        requestAstro(`ipecscm/v1/rest/callrequest`,params , 'post')
        .then(response => { 
            console.log('get forward', 'params', params, 'response',  response);
            if(response.data.error){
                popAlert(response.data.error.message);
            }else{
                localStorage.setArray("forwardData", response.data.data);//저장
                printForward();
            }
        });
    }
    
    let printForward = () => {
    
        let forwardData = localStorage.getArray("forwardData");
    
        //등록/해제 여부
        if(forwardData.type == 0){
            $('#forward_ring_status').removeClass('on');
            $('#forward_ring_status>span').text('착신전환 미등록 상태입니다');
        }else{
            if(forwardData.to == "8888"){
                $("#forward_ring_status>span").text('VMS 착신 중입니다.');
                $("#forward_ring_status").css("background-color","#ef6964");
            }
            $('#forward_ring_status').addClass('on');
            $('#forward_ring_status>span').text('착신전환 기능 동작 중입니다');
        }
        
        $("#inp_forward_number").val(forwardData.to);
    
        //동작시간
        $('#select_forward_time_type').val(forwardData.time_type);
        $("#select_forward_start_time").val(forwardData.start_time);
        $("#select_forward_end_time").val(forwardData.stop_time);
        
        $("input:radio[name='forward_type']:radio[value='"+forwardData.type+"']").prop("checked",true);
    
    }
    
    let drawNamecards = () => {
        $('#div_setting_namecards').empty();
        let namecard_dir_path ='www/namecard';
    
        function draw(filelist, json){
            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);
            }
    
            let device_platform = 'ANDROID';
    
            if(typeof device != 'undefined'){
                device_platform = device.platform;
            }
    
            //namecard파일명이 싹다 바뀌면 그전에 설정된 파일명을 초기화해줘야지...
            if((serverData.default_profile||'') != '' && filelist.indexOf(serverData.default_profile) == -1){
                syncServerData({
                    default_profile : ''
                });
            }

            try {
                if(serverData.profile_used == 'Y' && device_platform.toUpperCase() == "ANDROID"){
                    $('.dl_namecard').removeClass('none');
    
                    if($('input[type=radio][name=profile]:checked').length == 0){
                        if((serverData.default_profile||'') == ''){
                            $('input[type=radio][name=profile]:eq(0)').prop('checked', true).trigger('click');
                        }else{
                            $(`input[type=radio][name=profile][value*="${serverData.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=profile_use][value=false]').prop('checked', true).trigger('click');
                }
            } catch (error) {
                
            }
        }
    
        if (window.device != undefined){
            cordova.exec((r)=>{
                //getNamecardSettings
                let json = null;
                try{
                    json = JSON.parse(r);
                }catch(e){
                    json = r;
                }
    
                cordova.exec((filelist)=>{
                    draw(filelist, json);
                }, (f) =>{
                    console.error('can not exec getNameCardsList', f );
                }, "GntelPlugin", "getNameCardsList", [namecard_dir_path]);
    
            }, (f)=>{
                console.error('can not exec getNamecardSettings', f )
            }, "GntelPlugin", "getNamecardSettings", null);
        } else {
            let filelist = 'namecard5.html,namecard6.html,namecard7.html,namecard8.html';
    
            let json = {
                namecard_default : "namecard5.html"
            };
    
            draw(filelist, json);
        }
    }

    let drawSettings = () => {
        $('#inp_setting_auto_login').prop('checked', userData.autoLogin);
        $('#inp_setting_acc_code_used').prop('checked', (serverData.accCodeUsed||'N') == 'Y');
        $('#inp_setting_acc_code').val(serverData.accCode||'');
        $('#inp_setting_digit_count').val(serverData.digitCount||'');
        $('#inp_setting_mobile_number').val(userData.mobileNumber||'');
        $('#inp_setting_dn').val(userData.dn||'');
        $('#inp_setting_prefix_ex').val(userData.prefixEx||'');
        $('#inp_setting_user_id').val(userData.userId||'');
        $('#inp_setting_user_name').val(userData.userName||'');
        $('#inp_setting_allow_push').prop('checked',userData?.allow_push=='Y'?true:false);

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

        $('#select_setting_push_start_time, #select_setting_push_end_time').empty();
        $('#select_setting_push_start_time, #select_setting_push_end_time').append(`<option value="" selected>선택</option>`);
        for(let time = 0;time<24; time++){
            $('#select_setting_push_start_time, #select_setting_push_end_time').append(
                `<option value="${time>9?time:('0'+time)}:00">${time>9?time:('0'+time)}:00</option>`
            )
        }

        $('#select_setting_push_start_time').val(serverData.push_start_time);
        $('#select_setting_push_end_time').val(serverData.push_end_time);

        cordova.getAppVersion.getVersionNumber().then(function (version) {
            $('#inp_setting_app_version').val(version||'');
        });
        $('#inp_setting_content_version').val(contents_version||'');
        $('#inp_setting_domain').val(serverData.server_host||'');
    }
})()