(()=>{
    'use strict';
    
    let init = () => {
        initFooter('hide');

        const isNotUseMobileExtension = (typeof useMobileExtension !== 'undefined' && useMobileExtension === false);

        const isNotUseForwardCall = (typeof useForwardCall !== 'undefined' && useForwardCall === false);

        // 변수가 false일 경우에만 "모바일 내선" 탭을 숨깁니다.
        if (isNotUseMobileExtension) {
            $('#tab_mobile_extension').parent('li').addClass("none");
        }

        // 변수가 false일 경우에만 "착신 전환" 탭을 숨깁니다.
        if (isNotUseForwardCall) {
            $('#tab_forward_call').parent('li').addClass("none");
        }

        $('#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);
    
        //착신전환
        if (!isNotUseForwardCall && !$.isEmptyObject(userData.dn)) {
            setForwardEvent();
            getForward();
        }
        
    //---------------테마설정 시작
    
        $('.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;

            if(e.target.name == 'profile' && localStorage.getItem("isDefaultNameCard") == "Y"){
                localStorage.setItem("isDefaultNameCard", "N");
            }
    
            cordova.exec((r)=>{
                console.log('success - content-setting - 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)
                );
            });
        })
        
    // -----------------------메뉴설정 끝

    // -----------------------기본설정 시작
        
        // 대표번호 사용여부 설정
        // $('#main_num_used').on('change', () =>{
        //     if($('#main_num_used').is(':checked')) {
        //         $('.main_num').show();
        //     } else {
        //         $('.main_num').hide();
        //     }
        // });

        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":

                        let isDefaultNameCard = localStorage.getItem("isDefaultNameCard");

                        response = {
                            ...response,
                            profile_used: response.profile_used == 'Y' ? true : false
                        }

                        if(
                            serverData.profile_used != response.profile_used ||
                            (isDefaultNameCard == 'Y' && serverData.default_profile != response.default_profile)
                        ){
                            profileSetting(response);
                        }

                        syncServerData(
                            {
                                ...response,
                                companyId: `${serverData.companyId}`,
                                companyPw: `${serverData.companyPw}`
                            }
                        );

                        try {
                            window.plugins.gntel.putPreferences([
                                'forward_call_mention', response.forward_call_mention
                            ], (r) => {console.log('success put putPreferences forward_call_mention', r);});
                        } catch (error) {
                            console.warn(error);
                        }

                        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 apiRequests = [];

                // '착신전환 사용' 버전일 때만, 내선 해제 API 요청을 배열에 추가합니다.
                if (!isNotUseForwardCall) {
                    // 착신전환 해제
                    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 setForwardParams ={
                        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
                    };
                    apiRequests.push(requestAstro(`ipecscm/v1/rest/callrequest`, setForwardParams, 'post')); 
                }

                // '모바일 내선 사용' 버전일 때만, 내선 해제 API 요청을 배열에 추가합니다.
                if (!isNotUseMobileExtension) {
                    let setMexParams = {
                        url: `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/mex?mex1_enable=0&mex1_number=11`,
                        method: 'POST',
                        token: window.localStorage.getArray('userData').token
                    };
                    apiRequests.push(requestAstro(`ipecscm/v1/rest/callrequest`, setMexParams, 'post')); 
                }

                // 서비스 탈퇴
                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);

                apiRequests.push(requestAstro(`mdial/v1/unregdevice`, params, 'post')); // 서비스 탈퇴 (필수)

                //패스워드 초기화 - 탈퇴완료시
                let initParams ={
                    url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/password?password=${app_init_pw}`
                    ,token : userData.token
                };

                Promise.all(apiRequests) 
                .then((results) => {
                    let unregResult = results[results.length - 1]; 
                    let code = unregResult.code || unregResult.errcode;
                    switch (code) {
                        case '0':
                        case '0000':
                            if(typeof app_init_pw != undefined){
                                // 비밀번호 초기화
                                requestAstro(`ipecscm/v1/rest/callrequest`, initParams, 'post')
                                .then(r=>{
                                    switch (r.code) {
                                        case '0000':
                                            if(r.data.data){
                                                withdrawal();
                                                break;
                                            } else{
                                                throw new Error('토큰 저장 실패');
                                            }
                                    
                                        default:
                                            throw new Error('토큰 갱신 응답 비정상');
                                    }
                                });
                            }else{
                                logout(true);
                            }
                            break;
                        case '100':
                            popAlert("비밀번호를 확인해 주세요");
                        default:
                            popAlert("오류가 발생했습니다.<br/>관리자에게 문의하세요.");
                            break;
                    }
                })
            });
        });

        //통화목록보관일수
        $('#inp_setting_call_history_exp').on('keyup', function(){
            if($.trim($(this).val()).length > 4 ){
                $(this).val('9999');
            }
        })
        ;

        //저장버튼
        $('#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();
                }
            }

            Promise.all([
                requestAstro(`mdial/v1/device/${serverData.corp_code}/${userData.mobileNumber}/${userData.device_uuid||''}/${userData.dn||''}`, params, 'put')
            ]).then(([res2]) =>{
                
                if(res2.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'
                    });

                    syncUserData({
                        call_history_exp : $.trim($('#inp_setting_call_history_exp').val()) == '' ? 30 : $.trim($('#inp_setting_call_history_exp').val())
                    });

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

                }
            });
        });

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

    // -----------------------기본설정 끝

        //모바일 내선
        if (!isNotUseMobileExtension && !$.isEmptyObject(userData.dn)) {
            setMobileExtentionEvent();
        }

        if(!$.isEmptyObject(userData.dn)){
            $('.tab_btn_setting .only-cid').removeClass('none');
        }
    };
    
    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 setForwardEvent = () => {
        for(let idx = 0;idx<24;idx++){
            $('.select-hour').append(
                `<option ${idx==0?'selected':''}>${idx>9?idx:('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);
                }
            });
        });
    }
    
    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 == true && 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;
                }

                // $('input[name=profile_use][value=false]').prop('checked', (r.is_show||true)).trigger('click');

                let is_show = (json.is_show !== undefined) ? json.is_show : true;

                if (is_show) {
                    $('input[name=profile_use][value=true]').prop('checked', true);
                } else {
                    $('input[name=profile_use][value=false]').prop('checked', true);
                }

                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);
        $('#main_num').val(serverData.main_num||'');
        $('#main_num_used').prop('checked', (serverData.main_num_used||'N') == 'Y');
        $('#mobile_extension_num').val(userData.mobile_extension_num ||'');
        $('#mobile_extension_used').prop('checked', (userData?.mobile_extension_used ||'N') == 'Y');
        $('#mobile_extension_used').trigger('change');

        $('#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>`
            )
        }
        
        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);
            $('#select_setting_push_end_time').val(userData.push_end_time);
        }else{
            $('[name=push_time][value=allday]').prop('checked', true).trigger('change');
            $('#select_setting_push_start_time').val('');
            $('#select_setting_push_end_time').val('');
        }

        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||'');
        $('#inp_setting_call_history_exp').val(userData.call_history_exp||'30');
    }

    let drawMobileExtension = (mobile_extension_info) => {
        $('#mobile_extension_num').val(userData.mobile_extension_num ||'');
        $('#mobile_extension_used').prop('checked', (userData?.mobile_extension_used ||'N') == 'Y');
        $('#mobile_extension_used').trigger('change');
        $('#mobile_extension_schedule_used').prop('checked', mobile_extension_info?.data?.used ?? false);
        $('#mobile_extension_schedule_used').trigger('change');

        try {
            if(typeof mobile_extension_info.data.error == 'undefined'){
                let dayofweek = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                for(var day of dayofweek){
                    $(`#mobile_extension_${day}`).prop('checked', mobile_extension_info?.data?.[day] ?? false);
                }

                $('#mobile_extension_start_time').val(mobile_extension_info?.data?.start_time ?? '');
                $('#mobile_extension_end_time').val(mobile_extension_info?.data?.end_time ?? '');
            }
        } catch (error) {  }
    }

    //모바일내선 버튼이벤트 세팅
    let setMobileExtentionEvent = () => {
        for(let idx = 0;idx<24;idx++){
            $('#mobile_extension_start_time, #mobile_extension_end_time').append(
                `<option value="${idx>9?idx:('0'+idx)}:00">${idx>9?idx:('0'+idx)}:00</option>`
            );
        }
    
        // 모바일 내선번호 사용여부 설정
        $('#mobile_extension_used').on('change', () =>{
            if($('#mobile_extension_used').is(':checked')) {
                $('.mobile_extension_num').show();
            } else {
                $('.mobile_extension_num').hide();
            }
        });

        // 모바일 내선번호 스케줄 사용여부 설정
        $('#mobile_extension_schedule_used').on('change', () =>{
            if($('#mobile_extension_schedule_used').is(':checked')) {
                $('.mobile_extension_schedule').show();
            } else {
                $('.mobile_extension_schedule').hide();
            }
        });

        $('#tab_mobile_extension').on('click', function(){
            // 모바일 내선번호 사용유무 조회
            let params ={
                url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/mex`,
                method :'GET',
                token : window.localStorage.getArray('userData').token
            };


            Promise.all([
                requestAstro(`ipecscm/v1/rest/callrequest`, params , 'post' ),
                requestAstro(`mdial/v1/device/mobileExtension/${serverData.corp_code}/${userData.id}`, {} , 'get' )
            ]).then(([response, response2]) => {
                console.log('mex조회', 'params', params, 'response',  response);
                if(typeof response.data.error == 'undefined'){
                    syncUserData({
                        mobile_extension_used : response.data.data.mex1_enable == '0'?'N':'Y',
                        mobile_extension_num : response.data.data.mex1_number
                    });
                    drawMobileExtension(response2);
                }else{
                    popAlert(response.data.error.code == 1?"모바일 내선 라이센스가 없습니다.<br/>관리자에 문의하세요.":response.data.error.message);
                }
            });

        });

        //모바일내선 저장
        $('#btn_mobile_extension_save').on('click', (e)=>{

            // 모바일 내선번호 세팅
            let setParams ={
                url : `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/mex?mex1_enable=${$('#mobile_extension_used').is(':checked')?'1':'0'}&mex1_number=${$('#mobile_extension_num').val()}`,
                method :'POST',
                token : window.localStorage.getArray('userData').token
            };

            let mobibe_extension_params = {
                mydn : userData.id,
                mex1_number : $('#mobile_extension_num').val(),
                corp_code : serverData.corp_code,
                monday : $('#mobile_extension_monday').is(':checked'),
                tuesday : $('#mobile_extension_tuesday').is(':checked'),
                wednesday : $('#mobile_extension_wednesday').is(':checked'),
                thursday : $('#mobile_extension_thursday').is(':checked'),
                friday : $('#mobile_extension_friday').is(':checked'),
                saturday : $('#mobile_extension_saturday').is(':checked'),
                sunday : $('#mobile_extension_sunday').is(':checked'),
                start_time : $('#mobile_extension_start_time').val() == $('#mobile_extension_end_time').val()?'':$('#mobile_extension_start_time').val(),
                end_time : $('#mobile_extension_start_time').val() == $('#mobile_extension_end_time').val()?'':$('#mobile_extension_end_time').val(),
                used : $('#mobile_extension_schedule_used').is(':checked')
            }

            requestAstro(`ipecscm/v1/rest/callrequest`, setParams , 'post')
            .then(res1 => {
                syncUserData({
                    mobile_extension_used :$('#mobile_extension_used').is(':checked')?'Y':'N',
                    mobile_extension_num : $('#mobile_extension_num').val()
                });
                if(res1.data.error.code == 1 ){
                    popAlert("모바일 내선 라이센스가 없습니다.<br/>관리자에 문의하세요.");
                }else if(res1.data.error.message!='OK'){
                    popAlert("모바일 내선번호 저장중 오류가 발생했습니다");
                }else{
                    requestAstro(`mdial/v1/device/mobileExtension`, mobibe_extension_params , 'post')
                    .then(res2 => {
                        if(res2.code != '0000'){
                            popAlert("모바일 내선 스케줄 정보 저장중 오류가 발생했습니다");
                        }else{
                            popAlert("저장되었습니다.");
                        }
                    });
                }        

            });

        });
    }

    G.init.setting = init;
})()