//조직도
let groupSaveDate = window.localStorage.getItem("setGroupLastDate")
    ,lastGroupDateTime = ""
    ,user_map = {}
    ,group_map = window.localStorage.getArray("group_map")||{}
    ,dept1_group = window.localStorage.getArray("dept1_group")||[]
    ,favo_map = {
        favo_user : {}
        , favo_group : {}
    }
    ,favo_template = ''
    ,group_template = ''
    ,person_template = ''
    ;

$(()=>{

    favo_template = $('#tree_favo_template').text();
    group_template = $('#tree_group_template').text();
    person_template = $('#tree_group_person_template').text();

    $(".btn_organ_pop").click(function (e) {
        e.preventDefault();
        getTreeData();
        $(".organ_pop").stop().show();
    });
    $(".organ_pop_close").click(function (e) {
        e.preventDefault();
        $(".organ_pop").stop().hide();
    });

    //조직도 관련 이벤트 - 시작

    /* 검색창 클릭 시 */
    $(".search_wrap_05 .input_search").focus(function(){
        $(".search_wrap_05 .article_srch").css("display","");
        $(".search_wrap_05 .article_favorites").css("display","none");
        $(".search_wrap_05 .article_all").css("display","none");
        $(".search_wrap_05").css("padding-left","102px");

    });

    /* 검색 취소 */
    $(".search_wrap_05 .cancel_search").on("click", function(){
        $(".search_wrap_05 .article_srch").css("display","none");
        $(".search_wrap_05 .article_favorites").css("display","");
        $(".search_wrap_05 .article_all").css("display","");
        $(".search_wrap_05").css("padding-left","16px");

        $(".search_wrap_05 .list_org_srch").empty();
        $(".search_wrap_05 .input_search").val("");
    });

   /* 그룹 click */
    $("#organization .wt_src").on("click", ".all_view_tree", function(event){
        
        event.stopPropagation();
        let $clickedElement = $(this);
        let isExpanded = $clickedElement.hasClass("on");
        let manageGroups = (settingData.noticeManageGroups||'').split(',');
        
        if (!isExpanded) {
            if ($clickedElement.parent().find(".tree").length == 0) {
                let parent_code = $clickedElement.attr("groupcode");
                let child_user_list = group_map[parent_code].user_id_list;
                let favo_flag = "btn_favo_no_org";

                if (child_user_list.length > 0) {
                    $("#" + parent_code).append(
                        "<ul class='list_org ul_person_" + parent_code + "'></ul>"
                    );
                    for (let idx in child_user_list) {
                        let user_code = child_user_list[idx];
                        let user = user_map[user_code];

                        favo_flag = favo_map.favo_user.hasOwnProperty(user_code) ? "btn_favo_org" : "btn_favo_no_org";

                        $(".ul_person_" + parent_code).append(
                            person_template
                            .replace(/{{user_name}}/g, "[" + user.position + "] " + user.name)
                            .replace(/{{comment}}/g, "")
                            .replace(/{{user_class}}/g, user.clss)
                            .replace(/{{phone_number}}/g, user.cid_no)
                            .replace(/{{cell_phone_number}}/g, user.mobile_no)
                            .replace(/{{email}}/g, user.email)
                            .replace(/{{user_position}}/g, user.position)
                            .replace(/{{group_name}}/g, user.group_name)
                            .replace(/{{user_id}}/g, user.user_id)
                            .replace(/{{fav_flag}}/g, favo_flag)
                            .replace(/{{user_id_type}}/g, user.user_id)
                            .replace(/{{user_photo_uri}}/g, (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:setThumbImage())
                            .replace(/{{view_type}}/g, "")
                        );
                    }
                }

                let child_group_list = group_map[parent_code].child_groups;

                $("#" + parent_code).append(
                    "<ul class='tree ul_" + parent_code + "'></ul>"
                );

                for (let idx in child_group_list) {
                    let group_code = child_group_list[idx];
                    let child_user = group_map[group_code].info;
                    let depth = parseInt(child_user.relation_depth) + 1;

                    favo_flag = favo_map.favo_group.hasOwnProperty(group_code) ? "" : "off";

                    if(manageGroups.includes(child_user.code)){
                        continue;
                    }

                    $(".ul_" + parent_code).append(
                        group_template
                        //.replace(/{{group_name}}/g, child_user.name + " (" + child_user.user_cnt + ")")
                        .replace(/{{group_name}}/g, child_user.name)
                        .replace(/{{group_count}}/g, "(" + child_user.user_cnt + ")")
                        .replace(/{{group_code}}/g, child_user.code)
                        .replace(/{{dept_class}}/g, "0" + depth)
                        .replace(/{{fav_flag}}/g, favo_flag)
                    );
                }
            }
        }

        // Toggle 'on' class and slideToggle
        $clickedElement.toggleClass("on", !isExpanded);
        $clickedElement.siblings("ul").slideToggle('fast', function() {
            // Scroll to the clicked element if it has class 'on'
            let scrollTo = $clickedElement.offset().top - 110;
            if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
                scrollTo -= 55; // Adjust as needed
            }
            $('html, body').animate({
                scrollTop: scrollTo
            }, 'fast');
        });
    });

    /* 즐겨찾기 그룹 click */
    $("#organization .wt_src").on("click", ".favo_group", function(event){
        event.stopPropagation();
        if(!$(this).hasClass("on")) {
            if($(this).parent().find(".list_org").length == 0 ){

                let parent_code = $(this).attr("groupcode");
                let child_user_list = group_map[parent_code].user_id_list;
                let favo_flag = "btn_favo_org";

                if(child_user_list.length >0){
                    $("#favo_"+parent_code).append(
                        "<ul class='list_org ul_person_favo_"+parent_code+"'></ul>"
                    );
                    for(let idx in child_user_list){
                        let user_code = child_user_list[idx];
                        let user = user_map[user_code];
                        $(".ul_person_favo_"+parent_code).append(
                            person_template
                            .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
                            .replace(/{{comment}}/g, "")
                            .replace(/{{user_class}}/g, user.clss)
                            .replace(/{{phone_number}}/g, user.cid_no)
                            .replace(/{{cell_phone_number}}/g, user.mobile_no)
                            .replace(/{{email}}/g, user.email)
                            .replace(/{{user_position}}/g, user.position)
                            .replace(/{{group_name}}/g, user.group_name)
                            .replace(/{{user_id}}/g, user.user_id)
                            .replace(/{{fav_flag}}/g, favo_flag)
                            .replace(/{{user_id_type}}/g, "favo_"+user.user_id)
                            .replace(/{{user_photo_uri}}/g, (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:setThumbImage())
                            .replace(/{{view_type}}/g, "favo")
                        )
                    }
                }
            }
        }

        $(this).toggleClass("on");
        $(this).siblings("ul").slideToggle("fast");

    });

    /* 즐겨찾기 메뉴 보기 */
    $("#organization .wt_src").on("click", ".fav_view_tree", function(event){
        event.stopPropagation();
        $(this).toggleClass("on");
        $(this).siblings("ul").slideToggle("fast");
    });

    /* 즐겨찾기 아이콘(유저) click */
    $("#organization .wt_src").on("click", ".favo", function(event){
        event.stopPropagation();
        let fav_info = $(this).attr("user_id");
        if($(this).hasClass("btn_favo_org")) {
            if($(this).attr("view_type") == "favo" ){
                popAlert("그룹 내 사용자는 삭제할 수 없습니다.");
            }else{
                $(this).removeClass("btn_favo_org");
                $(this).addClass("btn_favo_no_org");
                deleteFavorate(fav_info, "user", this)
            }
        } else {
            $(this).removeClass("btn_favo_no_org");
            $(this).addClass("btn_favo_org");
            insertFavorate(fav_info, "user", this)
        }
    });

    /* 즐겨찾기 아이콘(그룹) click */
    $("#organization .wt_src").on("click", ".btn_favo_tree:not(.none)", function(event){
        event.stopPropagation();
        let fav_info = $(this).attr("groupcode");
        let user_cnt = group_map[$(this).attr("groupcode")].user_cnt
        if($(this).hasClass("off")) {
            if(user_cnt > 0){
                insertFavorate(fav_info, "group", this);
            }
        } else {
            deleteFavorate(fav_info, "group", this)
        }
    });

    /* 사용자 상세 */
    $("#organization").on("click", ".view_detail", function(e) {
        e.stopPropagation();
        let user = user_map[$(this).attr("user_id")];

        let group = group_map[user.dept_code].info;
        let img_element = $(this).closest('li').find('img'); // 이미지 요소 선택
        let img_src = img_element.attr('src');

        let user_info = {
            "name": user.name,
            "photo_url": (user.photo_path_url != undefined && user.photo_path_url !== '') 
                ? `${settingData.server_host}${settingData.server_port}${user.photo_path_url}`
                : img_src
        };

        let infos = [
            {"key": "소속", "value": formatDisplayGroup(user.group_names, '@@')},
            {"key": "직책", "value": emptyToSpace(user.position)},
            {"key": "내선번호", "value": format_phone_number(default_setting.region_number + user.cid_no), buttons: (user.cid_no == "" ? [] : ["call"])},
            {"key": "휴대폰", "value": (user.cell_phone_number == "" ? '-' : format_phone_number(user.mobile_no)), buttons: (user.mobile_no == "" ? [] : ["sms", "call"])},
            {"key": "담당업무", "value": emptyToSpace(user.description)}
        ];

        openDetail(user_info, infos, null, 'organization');
    });

    $(document).on("click", ".portrait img", function(event) {
        event.stopPropagation(); 

        let imageUrl = $(this).attr("src"); 

        console.log("클릭한 이미지 URL:" + imageUrl);

        if (!imageUrl || imageUrl.includes("default_image.jpg") || imageUrl === setThumbImage()) {
            console.warn("기본 이미지가 클릭되었습니다. InAppBrowser를 실행하지 않습니다.");
            return;
        }

        if (!imageUrl.startsWith("http")) {
            console.error("🚨 잘못된 이미지 URL:", imageUrl);
            console.log("잘못된 이미지 URL입니다.");
            return;
        }

        // 이미지 URL이 Whitelabel Error Page로 열리는지 확인 (테스트)
        // window.open(imageUrl, '_blank');

        let inAppRef = cordova.InAppBrowser.open(
            imageUrl, 
            '_blank', 
            'location=no,zoom=yes,toolbar=yes,enableViewportScale=yes'
        );

        inAppRef.addEventListener('loadstop', function() {
            inAppRef.executeScript({
                code: `
                    document.addEventListener('dblclick', function() { 
                        window.close(); 
                    });
                    document.addEventListener('keydown', function(event) {
                        if (event.key === 'Escape' || event.keyCode === 27) { 
                            window.close(); 
                        }
                    });
                `
            });
        });

        // 뒤로 가기 버튼 이벤트 (Android 대응)
        inAppRef.addEventListener("backbutton", function() {
            inAppRef.close();
        });

        // InAppBrowser가 닫혔을 때 콘솔 로그 추가 (디버깅용)
        inAppRef.addEventListener('exit', function() {
            console.log("InAppBrowser가 닫혔습니다.");
        });
    });



    //전화걸기 팝업
    $("#organization .wt_src").on("click", ".btn_org_call", function(e){
        let user_info = user_map[$(this).data('user_id')] ,numbers = [];
        console.log('organization .wt_src on click',"calling",numbers, user_info.user_name);
        e.stopPropagation();
        if(user_info.cid_no != undefined && user_info.cid_no != '') numbers.push({"number":(default_setting.region_number + user_info.cid_no), "type":"내선전화"});
        if(user_info.mobile_no != undefined && user_info.mobile_no != '') numbers.push({"number":user_info.mobile_no, "type":"휴대전화"});
        if(user_info.etc_no != undefined && user_info.etc_no != '') numbers.push({"number":user_info.etc_no, "type":"기타전화"});

        for(let idx =0;idx<numbers.length;idx++){
            let item = numbers[idx];
            item.normalizedNumber = item.number.replace(/[^0-9]/gi,'');
        }

        let contact = {
            id : "contant_fake_id"
            ,phoneNumbers : numbers
            ,displayName : user_info.name
        }

        console.log('organization .wt_src on click',"selectCall"+JSON.stringify(contact));

        selectCall(contact,'','');
    });

    /* 조직도 검색창 클릭 시 */
    $(".search_wrap_05 .input_search").focus(function(){
        $("#organization .article_srch").css("display","");
        $("#organization .article_favorites").css("display","none");
        $("#organization .article_all").css("display","none");
        $("#organization .search_wrap").css("padding-left","102px");
    });

    /* 검색 취소 */
    $("#btn_cancel_org_search").on("click", function(){
        $("#organization .article_srch").css("display","none");
        $("#organization .article_favorites").css("display","");
        $("#organization .article_all").css("display","");
        $("#organization .search_wrap").css("padding-left","16px");

        $("#organization .list_org_srch").empty();
        $("#inp_org_srch_name").val("");
    });

    $("#btn_delete_org_search").on("click", function(){
        $("#inp_org_srch_name").val("");
        $("#organization .list_org_srch").empty();
    });

    /* 연락처, 이름 검색 */
    $('.search_wrap_05 .input_search').on('keyup', function(e){
        itcdelay(function () {
            // 비어있거나 bytes로 계산했을때 1글자이면 검색하지 않음
            if($("#inp_org_srch_name").val() != "" && getByteLengthOfString($("#inp_org_srch_name").val().trim()) > 1 ){
                let sch_key = $('#inp_org_srch_name').val();
                $("#organization .list_org_srch").empty();
                for(let key in user_map){
                    let user = user_map[key];
                    try {
                        if(
                            user.name.indexOf(sch_key)>-1 
                            || user.mobile_no.indexOf(sch_key)>-1 
                            || user.etc_no.indexOf(sch_key)>-1 
                            || user.cid_no.indexOf(sch_key)>-1 
                            ||user.cho_name.indexOf(sch_key)>-1
                            || (sch_key.length >=2 && user.dept_name.indexOf(sch_key)>-1)
                            || (sch_key.length >=2 && user.description.indexOf(sch_key)>-1)
                        ){
                            drawUser(user);
                        }
                    } catch (e) {}
                }
            }else{
                $(".list_org_srch").empty();
            }
        }, 500);
    });

    //상세레이어 통화 버튼
    $('.detail_layer').on('click','a.btn_call', function(){
        if(isNaN($(this).data('info')) && $(this).data('info').replace(/\s/g,'') =='' ) return;
        let numbers = [];

        if($(this).data('info')!=undefined && $(this).data('info') != ''){
            numbers.push({"number": ($(this).data('info')+''), "type":($(this).closest('li').find('span.item').text())});
        }
        for(let idx =0;idx<numbers.length;idx++){
            let item = numbers[idx];
            item.normalizedNumber = item.number.replace(/[^0-9]/gi,'');
        }

        let contact = {
            id : "contant_fake_id"
            ,phoneNumbers : numbers
            ,displayName : $('#detail_layer_name').text()
        }

        console.log('detail_layer on click',"selectCall"+JSON.stringify(contact));

        selectCall(contact,'','');
    });

    //상세레이어 문자(SMS) 버튼
    $('.detail_layer').on('click','a.btn_sms', function(){
        if(isNaN($(this).data('info')) && $(this).data('info').replace(/\s/g,'') =='' ) return;
        let numbers = [];

        if($(this).data('info')!=undefined && $(this).data('info') != ''){
            numbers.push({"number": ($(this).data('info')+''), "type":($(this).closest('li').find('span.item').text())});
        }
        for(let idx =0;idx<numbers.length;idx++){
            let item = numbers[idx];
            item.normalizedNumber = item.number.replace(/[^0-9]/gi,'');
        }
        
        if (numbers.length > 0) {
            document.location.href = "sms:" + numbers[0].normalizedNumber;
        }
    });

    $(".gnb_02").on('click', function(){

        //조직도 추가 작업 - 업데이트 시간에 따른 조직도 다시 select 작업임
        try {
            console.log('gnb_02 click',"updatetime");

            let groupSaveDate = window.localStorage.getItem("setGroupLastDate");
            let lastGroupDateTime = "";

            cordova.plugin.http.get(server_host +server_port+ '/astroapi/base/v1/corp/updatetime/' + serverData.corp_code, {}, {
                Authorization: 'Bearer '+userData.astroToken
            }, function(response) {

                let data = JSON.parse(response.data).data;
                lastGroupDateTime = data.update_time;

                console.log('gnb_02 click',"lastGroupDateTime " + lastGroupDateTime);

                if(groupSaveDate == lastGroupDateTime){
                    console.log('gnb_02 click',"같다");
                }else{
                    console.log('gnb_02 click',"다르다");
                    getOrganization((userMap)=>{
                        drawOrganization();
                        
                        if(devicePlatform == "iOS"){
                            generateCallExtension(userMap);
                        }
                        
                        window.localStorage.setItem("setGroupLastDate", lastGroupDateTime);
                    });
                }

            }, function(response) {
                console.error('gnb_02 click',response.error);
            });    
        } catch (error) {
            
        }

        // $(".view_tree").removeClass("on");
        // $(".list_org").css("display","");
        // $(".tree").css("display","");
    });

    //이름 클릭, 상세팝업
    $(document).on("click", ".view_detail", function(){
        $(".detail_layer").show();
        $(".detail_layer").addClass("on");
        setTimeout(() => {
            $(".detail_header").addClass("fixed");
        },200);
    });
    $(document).on("click", ".btn_close_detail", function(){
        $(".detail_layer").removeClass("on");
        $(".detail_header").removeClass("fixed");
    });

    //전화걸기 팝업
    $(".btn_org_call").on("click", function(){
        $(".bg_calling_01").show();
        setTimeout(() => {
            $(".bg_calling_01").addClass("on");
        }, 10);
    });
    $(".close_calling").on("click", function(){
        $(".bg_calling_01").removeClass("on");
        setTimeout(() => {
            $(".bg_calling_01").hide();
        }, 100);
    })

    // 그룹 메뉴 보기
    $(document).on("click", ".view_tree", function(){
        $(this).toggleClass("on");
        $(this).siblings("ul").slideToggle("fast");
    });


    /**
     * 사용자 상세 정보 팝업
     * user_info : {
     *                     name : ''
     *                     ,number : ''
     *                     ,photo_url : ''
     *                  }
     * infos : [
     *      {'key' : 'asd', 'value':'vas', buttons : [call,mail,chat]}
     * ...
     * ]
     * history : [
     *      {'type': 'coming/send/miss', 'time' : 'asdklasd'}
     * ]
     * @returns
     */
    function openDetail(user_info, infos, history, type){
        $('#img_user_detail_photo').attr('src',(user_info.photo_url != undefined && user_info.photo_url != '')?user_info.photo_url:setThumbImage());
        $('#detail_layer_edit_caution').css("display", type=='caution'?'inline':'none');
        $('#detail_layer_add_address').css("display", type=='address'?'none':'inline');
        $('#detail_layer_add_attention').css("display", type=='caution'?'none':'inline');
        $('#detail_layer_name').text(user_info.name||'');
        $('#detail_layer_number').text(user_info.number||'');
        $('.detail_layer ul.detail_conts_list').empty();
        let html = '';
        for(let idx =0;idx<infos.length;idx++){
            let item = infos[idx];
            if(item.buttons){
                let buttons = item.buttons;
                html += '<li><span class="item">'+item.key+'</span><span class="value">'+item.value+'</span><div class="detail_conts_tool">';
                for(let bidx = 0; bidx<buttons.length; bidx++){
                    switch (buttons[bidx]) {
                    case 'call':
                        // TODO: dhlee: 이미지 맞는사이즈가 없어서 다른걸로 바꿈
                        // html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/biz-call_btn_1.png"></a>'
                        html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/icon_call.png"></a>'
                        break;
                    case 'chat':
                    case 'mail':
                        html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/icon_'+buttons[bidx]+'_cc.png"></a>'
                        break;
                    // TODO: dhlee: 문자 넣어달라고해서 임의로 넣음
                    case 'sms':
                        html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/icon_chat_cc.png"></a>'
                        break;
                    }
                }
                html += '</div></li>';
            }else{
                html += '<li><span class="item">'+item.key+'</span><span class="value">'+item.value+'</span></li>'
            }
        }
        if(!$.isEmptyObject(history)){
            for(idx =0; idx< history.length;idx++){
                html += '<li class="'+history[idx].type+'">'+history[idx].time+'</li>';
            }
        }
        $('.detail_layer ul.detail_conts_list').html(html);

        $(".detail_layer").show();
        $(".detail_layer").addClass("on");
        $(".detail_header").addClass("fixed");
    }

    let upinsert = "U";
    
    function getTreeData(){
        //조직도
        let tree;
        
        let tempUrl = server_host + server_port + '/astroapi/base/v1/corps/withdept/tree/' + serverData.corp_code;
    
        cordova.plugin.http.get(tempUrl, { }, {
            Authorization: 'Bearer '+ userData.astroToken
        }, function(response) {
            let jsonData = JSON.parse(response.data);
            try {
                let transformedData = transformData(jsonData.data);
                console.log('getTreeData',jsonData);
                tree = new DinampTreeEditor('.organization').setData(transformedData).set({
                    extended: false,
                    editable: true
                });
            } catch (e) {
                console.error('getTreeData',e);
            }
        }, function(response) {
            // prints 403
            console.log('getTreeData',"response status:"+response.status);
            //prints Permission denied
            console.log('getTreeData',response.error);
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    
        let transformData = function (data) {
            let transformedData = [];
    
            for (let i = 0; i < data.length; i++) {
    
                let item = data[i];
                let transformedItem = {
                    title: item.name,
                    code: item.code,
                    corp_code: item.corp_code,
                    prnt_code: item.prnt_code,
                    group_type: item.group_type,
                    children: [],
                };
    
                if (item.childs && (item.childs).length > 0) {
                    transformedItem.children = transformData(item.childs);
                }
    
                transformedData.push(transformedItem);
            }
    
            return transformedData;
        };
    };

    //클릭시 조직정보 조회
    $(document).on('click', '.jsTree p', function (e) {
        let orgName = $(this).text();
        let grouptype = $(this).attr('group-type');
    
        console.log('jsTree p',grouptype);
    
        upinsert = "U";
    
        if ($(this).data('code') != null && grouptype !== "C") {
            let dept_code = $(this).attr("data-code");
            let corp_code = $(this).attr("corp-code");
    
            $('.jsTree').find('.itemParent').removeClass('selected');
            $(this).closest('.itemParent').addClass('selected');
    
            let tempUrl = server_host + server_port + '/astroapi/base/v1/dept/detail/' + dept_code + '/' + corp_code;
    
            cordova.plugin.http.get(tempUrl, {},{
                Authorization: 'Bearer '+ userData.astroToken
            }, function(response) {
                let jsonData = JSON.parse(response.data);
    
                window.localStorage.setArray("selected_dept_code", jsonData.data.code);
                window.localStorage.setArray("selected_dept_name", jsonData.data.name);
    
            }, function(response) {
                // prints 403
                console.log('jsTree p',"response status:"+response.status);
                //prints Permission denied
                console.log('jsTree p',response.error);
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            });
        }
    });
    
    //--------조직도 관련 이벤트 끝

});

let itcdelay = (function () {
    // Function
    let itcTimer = 0;
    return function (callback, ms) {
        clearTimeout(itcTimer);
        itcTimer = setTimeout(callback, ms);
    };
})();

// 문자열 Bytes로 몇자인지 확인
const getByteLengthOfString = function (s, b, i, c) {
    for (b = i = 0; (c = s.charCodeAt(i++)); b += c >> 11 ? 3 : c >> 7 ? 2 : 1);
    return b;
};

function checkOrganization(){
    cordova.plugin.http.get(settingData.server_host +settingData.server_port+ '/astroapi/base/v1/corp/updatetime/' + serverData.corp_code, {}, {
        Authorization: 'Bearer '+userData.astroToken
    }, function(response) {

        let data = JSON.parse(response.data).data;
        lastGroupDateTime = data.update_time;

        console.log('onDeviceReady lastGroupDateTime' + lastGroupDateTime);

        if(groupSaveDate == lastGroupDateTime){
            console.log('onDeviceReady 같다');
            if($.isEmptyObject(user_map)){
                readFile('user_map.json',(data)=>{
                    try {
                        user_map = JSON.parse(data);
                    } catch (error) {
                        user_map = {};
                    }

                    //한번 readFile했는데 user_map이 구성되어있지않으면 getOrganization을 호출해서 writeFile한후 진행한다.
                    if($.isEmptyObject(user_map)){
                        getOrganization((userMap)=>{
                            // initIntropage();
                            drawOrganization();
                            if(devicePlatform == "iOS"){
                                generateCallExtension(userMap);
                            }
                            window.localStorage.setItem("setGroupLastDate", lastGroupDateTime);
                        });
                    }else{
                        // initIntropage();
                        drawOrganization();
                    }
                });
            }else{
                // initIntropage();
                drawOrganization();
            }

        }else{
            console.log('onDeviceReady 다르다');

            getOrganization((userMap)=>{
                // initIntropage();
                drawOrganization();
                if(devicePlatform == "iOS"){
                    generateCallExtension(userMap);
                }
                window.localStorage.setItem("setGroupLastDate", lastGroupDateTime);
            });
        }

    }, function(response) {
      console.error('onDeviceReady',response.error);
    });
}

//조직도 화면구성
function drawOrganization(){
    console.log('drawOrganization start');
    let manageGroups = (settingData.noticeManageGroups||'').split(',');

    $("ul.list_org_favo,ul.favo_tree,ul.all_tree_root").empty();

    //즐겨찾기 구성
    let fav_infos = window.localStorage.getArray('fav_infos');
    for(let idx in fav_infos){
        let favorate_code = fav_infos[idx].favorate_code;
        if(fav_infos[idx].type == "user"){
            favo_map.favo_user[fav_infos[idx].favorate_code] = fav_infos[idx];
            let user = user_map[favorate_code];
            let group_info = group_map[user.dept_code].info

            $(".list_org_favo").append(
                person_template
                .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
                .replace(/{{comment}}/g, formatDisplayGroup(user.group_names, '@@'))
                .replace(/{{user_class}}/g, user.clss)
                .replace(/{{phone_number}}/g, user.cid_no)
                .replace(/{{cell_phone_number}}/g, user.mobile_no)
                .replace(/{{email}}/g, user.email)
                .replace(/{{user_position}}/g, user.position)
                .replace(/{{group_name}}/g, user.group_name)
                .replace(/{{user_id}}/g, user.user_id)
                .replace(/{{fav_flag}}/g, "btn_favo_org")
                .replace(/{{user_id_type}}/g, "favo_"+user.user_id)
                .replace(/{{user_photo_uri}}/g, (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:setThumbImage())
                .replace(/{{view_type}}/g, "")
            )
        }else{
            favo_map.favo_group[fav_infos[idx].favorate_code] = fav_infos[idx];
            let group = group_map[favorate_code].info;
            if(manageGroups.includes(group.code)){
                continue;
            }

            $(".favo_tree").append(
                favo_template
                .replace(/{{group_name}}/g, group.name)
                .replace(/{{group_code}}/g, group.code)
            )
        }
    };
    //------즐겨찾기 구성 끝

    //let dept1_group = localStorage.getArray('dept1_group')||[];
    dept1_group.forEach((group)=>{
        let favo_flag = "btn_favo_no_org";

        if(favo_map.favo_group.hasOwnProperty(group.code)){
            favo_flag = "";
        }else{
            favo_flag = "off";
        }

        if(manageGroups.includes(group.code)){
            return ;
        }

        $(".all_tree_root").append(
            group_template
            //.replace(/{{group_name}}/g, group.name+ " ("+group.user_cnt +")")
            .replace(/{{group_name}}/g, group.name)
            .replace(/{{group_count}}/g, "("+group.user_cnt +")")
            .replace(/{{group_code}}/g, group.code)
            .replace(/{{haschild}}/g, group.haschild)
            .replace(/{{dept_class}}/g, "01")
            .replace(/{{fav_flag}}/g, favo_flag)
        )

        let parent_code = group.code;
        let child_user_list = group_map[parent_code].user_id_list;
        if(child_user_list.length >0){

            $("#"+parent_code).append(
                "<ul class='list_org ul_person_"+parent_code+"'></ul>"
            );

            for(let idx in child_user_list){
                let user_code = child_user_list[idx];
                let user = user_map[user_code];

                if ( user === undefined ) {
                    continue ;
                }

                if(favo_map.favo_user.hasOwnProperty(user_code)){
                    favo_flag = "btn_favo_org";
                }else{
                    favo_flag = "btn_favo_no_org";
                }

                $(".ul_person_"+parent_code).append(
                    person_template
                    .replace(/{{user_name}}/g, "["+user.clss+"] "+user.name)
                    .replace(/{{comment}}/g, "")
                    .replace(/{{user_class}}/g, user.clss)
                    .replace(/{{phone_number}}/g, user.cid_no)
                    .replace(/{{cell_phone_number}}/g, user.mobile_no)
                    .replace(/{{email}}/g, user.email)
                    .replace(/{{user_position}}/g, user.position)
                    .replace(/{{group_name}}/g, user.group_name)
                    .replace(/{{user_id}}/g, user.user_id)
                    .replace(/{{fav_flag}}/g, favo_flag)
                    .replace(/{{user_id_type}}/g, user.user_id)
                    .replace(/{{user_photo_uri}}/g, (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:setThumbImage())
                    .replace(/{{view_type}}/g, "")
                );
            }
        }

        let child_group_list = group_map[parent_code].child_groups;

        $("#"+parent_code).append(
            "<ul class='tree ul_"+parent_code+"'></ul>"
        );

        for(let idx in child_group_list){
            let group_code = child_group_list[idx];
            let child_user = group_map[group_code].info;
            let depth = parseInt(child_user.relation_depth)+1;

            if(favo_map.favo_group.hasOwnProperty(group_code)){
                favo_flag = "";
            }else{
                favo_flag = "off";
            }

            if(manageGroups.includes(child_user.code)){
                continue;
            }

            $(".ul_"+parent_code).append(
                group_template
                //.replace(/{{group_name}}/g, child_user.name+ " ("+child_user.user_cnt +")")
                .replace(/{{group_name}}/g, child_user.name)
                .replace(/{{group_count}}/g, "("+child_user.user_cnt +")")
                .replace(/{{group_code}}/g, child_user.code)
                .replace(/{{dept_class}}/g, "0"+depth)
                .replace(/{{fav_flag}}/g, favo_flag)
            )
        }
    });

    $(".dpt_01:last").trigger('click');

    console.log('drawOrganization end');
    
}

/* 즐겨찾기 추가 */
function insertFavorate(fav_info, type, obj){

    let info = window.localStorage.getArray('fav_infos')||[];

    info.push({
        favorate_code : fav_info
        ,type : type
    });

    window.localStorage.setArray('fav_infos',info);
    $(obj).removeClass('off');
    refreshFavoList(type, fav_info);
}

function refreshFavoList(type, fav_info){
    if(type == "user"){
        favo_map.favo_user[fav_info] = {"favorate_code" :fav_info, "type":type}
        let user = user_map[fav_info];
        let group_info = group_map[user.dept_code].info;

        $(".list_org_favo").append(
            person_template
            .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
            .replace(/{{comment}}/g, formatDisplayGroup(user.group_names, '@@'))
            .replace(/{{user_class}}/g, user.clss)
            .replace(/{{phone_number}}/g, user.cid_no)
            .replace(/{{cell_phone_number}}/g, user.mobile_no)
            .replace(/{{email}}/g, user.email)
            .replace(/{{user_position}}/g, user.position)
            .replace(/{{group_name}}/g, user.group_name)
            .replace(/{{user_id}}/g, user.user_id)
            .replace(/{{fav_flag}}/g, "btn_favo_org")
            .replace(/{{user_id_type}}/g, "favo_"+user.user_id)
            .replace(/{{user_photo_uri}}/g, (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:setThumbImage())
            .replace(/{{view_type}}/g, "")
        )
    }else{
        favo_map.favo_group[fav_info] = { "favorate_code" :fav_info, "type":type}
        let group = group_map[fav_info].info;
        $(".favo_tree").append(
            favo_template
            .replace(/{{group_name}}/g, group.name)
            .replace(/{{group_code}}/g, group.code)
            .replace(/{{group_count}}/g, "("+group.user_cnt +")")
        )
    }
}


/* 즐겨찾기삭제 */
function deleteFavorate(fav_info, type, obj){
    let info = window.localStorage.getArray('fav_infos')||[];

    let sinfo = info.filter(item => (item.favorate_code != fav_info && item.type != type));

    window.localStorage.setArray('fav_infos',sinfo);

    if($(obj).parents().find(".fav_tree_root").length > 0){
        if(type == "user"){
            $("#"+fav_info).find(".favo").removeClass("btn_favo_org")
            $("#"+fav_info).find(".favo").addClass("btn_favo_no_org");
        }else{
            let obj_root = $("#"+fav_info).find(".btn_favo_tree")[0];
            $(obj_root).addClass("off");
        }
    }

    if(type == "user"){
        delete favo_map.favo_user[fav_info];
    }else{
        delete favo_map.favo_group[fav_info];
    }

    $(obj).addClass("off");
    $("#favo_"+fav_info).remove();

    console.log('deleteFavorate',favo_map);
}

function formatDisplayGroup(group_names, parser){

    console.log('formatDisplayGroup',"group_names : " + group_names);

    let disp_exp;
    if(group_names == undefined || group_names == null) return "";
    try{
        disp_exp = '${g-2}/${g-1}';
    }catch(e){
        disp_exp = undefined;
    }
    let $opener = opener;
    let group_arr = group_names.split(parser);
    // TODO: dhlee: 회사 이름을 제거했었나?.... 일단 뺌
//        group_arr.splice(0,1);
    if($.isEmptyObject(group_arr)) return "";

    let to_convert_str = "";
    let group_name = "";
    let head_index,end_index;
    while((head_index = disp_exp.indexOf("${"))>=0 && (end_index = disp_exp.indexOf("}"))>head_index ){
        to_convert_str = disp_exp.substring(head_index, end_index+1);
        try{
            let group_depth = parseInt(to_convert_str.replace(/[$ { } g]/g,''));
            if(group_depth >0){
                group_name = group_arr[group_depth]?group_arr[group_depth]:"";
            }else if(group_depth < 0){
                group_name = group_arr[group_arr.length + group_depth]?group_arr[group_arr.length + group_depth]:"";
            }else{
                group_name = "";
            }

            console.log('formatDisplayGroup',"group_name : " + group_name);
            disp_exp = disp_exp.replace(to_convert_str, group_name);
        }catch(e){
            return popAlert("그룹표시 형식이 잘못되었습니다.");
        }
    }
    if(disp_exp.startsWith("/"))disp_exp = disp_exp.substring(1);
    return disp_exp;
}

function drawUser(user){
    let favo_flag = "btn_favo_no_org";
    if(favo_map.favo_user.hasOwnProperty(user.user_id)){
        favo_flag = "btn_favo_org"
    }else{
        favo_flag = "btn_favo_no_org"
    }
    let group_info = group_map[user.dept_code].info

    $(".list_org_srch").append(
        person_template
        .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
        .replace(/{{comment}}/g, formatDisplayGroup(user.group_names, '@@'))
        .replace(/{{user_class}}/g, user.clss)
        .replace(/{{phone_number}}/g, user.cid_no)
        .replace(/{{cell_phone_number}}/g, user.mobile_no)
        .replace(/{{email}}/g, user.email)
        .replace(/{{user_position}}/g, user.position)
        .replace(/{{group_name}}/g, user.group_name)
        .replace(/{{user_id}}/g, user.user_id)
        .replace(/{{fav_flag}}/g, favo_flag)
        .replace(/{{user_id_type}}/g, user.user_id)
        .replace(/{{user_photo_uri}}/g, (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:setThumbImage())
        .replace(/{{view_type}}/g, "")
    )
}

//조직도 구성에 필요한 데이터 가져오기
function getOrganization(callback){
    console.log('getOrganization start');
    //alert("다시 호출");
    if(settingData.rootGroupcode == undefined || settingData.rootGroupcode == ''){
        return popAlert("조직최상위 코드 설정이 필요합니다 관리자에게 문의하세요.");
    }

    let groups =[];
    let users = [];
    cordova.plugin.http.get(server_host + server_port + '/astroapi/base/v1/users/'+ settingData.rootGroupcode, {}, {
        Authorization: 'Bearer '+userData.astroToken
     }
    ,function(result){
        
        try{
            users = JSON.parse(result.data).data;
        }catch(e){
            users= [];
        }

        // console.log("userfilter");
        // console.log(users);
        cordova.plugin.http.get(server_host +server_port+ '/astroapi/base/v1/corps/withdept/'+ settingData.rootGroupcode, {}, {
            Authorization: 'Bearer '+userData.astroToken
        }
        ,function(gresult){
            try{
               // alert(gresult);
                groups = JSON.parse(gresult.data).data;
            }catch(e){
               // alert('여기3');
                groups = [];
            }

            group_map = {};
            user_map ={};
            let mindepth = 999;
            for(let idx = 0; idx<groups.length; idx++){
                let group = groups[idx];
                group_map[group['code']] = {};
                group_map[group['code']].info =group;
                group_map[group['code']].child_groups =[];
                group_map[group['code']].user_id_list = [];
                group_map[group['code']].user_cnt = 0;
                if(group.relation_depth < mindepth){
                    mindepth = group.relation_depth;
                }
            }

            for(let idx=0; idx<users.length;idx++){
                let user = users[idx];
                let group = group_map[user.dept_code];
                if(group == undefined) continue;
                group['user_id_list'].push(user.user_id);
                group['user_cnt'] =group['user_cnt']+1;
                //모바일mcid용필드 추가
                try {
                    if(mcid_tel_no_format != undefined){
                        user.mcid_tel_no = (user.cid_no != undefined && user.cid_no != '')?eval(mcid_tel_no_format):'';
                    }
                    if(mcid_tel_name_format != undefined){
                        user.mcid_tel_name = eval(mcid_tel_name_format);
                    }
                    if(mcid_mobile_no_format != undefined){
                        user.mcid_mobile_no = (user.mobile_no != undefined && user.mobile_no != '')?eval(mcid_mobile_no_format):'';
                    }
                } catch (error) {}
                user_map[user.user_id] =  user;
            }
            
            for(let idx =0;idx<groups.length;idx++){
                let group = groups[idx];
                let sg = groups.filter(function(item){
                    return item.relation_code.startsWith(group.relation_code);
                });

                let sg_codes = [];
                for(let sidx =0;sidx<sg.length;sidx++){
                    sg_codes.push(sg[sidx].code);
                }

                let su = users.filter(function(item){
                    return  sg_codes.includes(item.dept_code);
                });
                let user_cnt = $.isEmptyObject(su)?0:su.length;
                group['user_cnt'] = user_cnt;
            }
            //각그룹별 하위그룹 유저 총합
            for(let oidx = 0; oidx<groups.length; oidx++){
                let group = groups[oidx];
                let user_cnt = 0;
                let relationed_groups = groups.filter(function(item){
                    return item.relation_code && (item.relation_code+'.').startsWith(group.relation_code+'.');
                });
                if(relationed_groups != undefined){
                    for(let idx=0;idx<relationed_groups.length; idx++){
                        user_cnt+= group_map[relationed_groups[idx].code].user_cnt;
                    }
                }
                group.user_cnt = user_cnt;
                if(group.prnt_code && group.prnt_code != '' && group_map[group.prnt_code] != undefined){
                    group_map[group.prnt_code].child_groups.push(group.code);
                }

                group['haschild'] = ($.isEmptyObject(relationed_groups) && group.user_cnt<=0 )?'0':'1';
            }
            //alert(JSON.stringify(groups));
            dept1_group = groups.filter(function(item){
               // alert(JSON.stringify(item.relation_depth));
                return item.relation_depth==mindepth;
            });

            writeFile("user_map.json", JSON.stringify(user_map), function () {
                window.localStorage.setArray("group_map", group_map);
                window.localStorage.setArray("dept1_group", dept1_group);
                window.localStorage.setItem("groupok", "1");
                console.log('getOrganization end');
                if(callback){
                    callback(user_map);
                }
            });

            
        }
        ,function(fresult){
            console.log('getOrganization fail withdept',fresult);
            if(callback){
                callback(fresult);
            }
        });

    }
    ,function(fresult){
        //fail
        console.log('getOrganization fail users',fresult);
        if(callback){
            callback(fresult);
        }
    });
}

//ios의 경우 calldirectoryxtension데이터를 이용하여 통화상대의 정보를 보여준다
function generateCallExtension(userMapJson){

    //window.plugins.gntel.getGLog(function(log))
    let groupSaveDate = window.localStorage.getItem("setGroupLastDate");
    window.plugins.gntel.checkMIddleDBFileExist((iExists)=>{
        console.log('checkMIddleDBFileExist success', iExists, 'groupSaveDate', groupSaveDate);

        if(!iExists){
            window.plugins.gntel.middleDBGenerator((r)=>{
                console.log('middleDBGenerator success', r);
            },(r)=>{
                console.log('middleDBGenerator fail', r);
            },'user_map.json');
        }else{
            //[{number,name,status}]
            let params = [];
            let list = Object.values(userMapJson).filter(item => item.create_time > (groupSaveDate||''));
            list.forEach(item =>{
                if(item.mcid_tel_no != ''){
                    params.push({
                        'name' : (item.mcid_tel_name||'')
                        ,'number' : item.mcid_tel_no
                        ,'status' : 'c'
                    });
                }
            });
    
            list = Object.values(userMapJson).filter(item => item.update_time > (groupSaveDate||''));
            list.forEach(item =>{
                if(item.mcid_tel_no == ''){
                    return;
                }
                params.push({
                    'name' : (item.mcid_tel_name||'')
                    ,'number' : item.mcid_tel_no
                    ,'status' : 'u'
                });
            });

            try {
                console.log('updateMiddleDB params', params.legnth , 'params[0]', JSON.stringify(params[0]));
            } catch (error) {
                console.log('updateMiddleDB params err', error);
            }
            if(params != undefined & !$.isEmptyObject(params)){
                window.plugins.gntel.updateMiddleDB((r)=>{
                    console.log('updateMiddleDB success', r);
                },(r)=>{
                    console.log('updateMiddleDB fail', r);
                },params);
            }else{
                console.log('updateMiddleDB params empty', params);
            }
        }
        
    },(r)=>{
        console.log('checkMIddleDBFileExist fail', r);
    })

}