(()=>{
    '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(typeof 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)
                );
            });
        })
        
        // -----------------------메뉴설정 끝
    
        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;
            }
    
            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 (typeof 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);
        }
    }
})()