(function () {
    'use strict';

    
    $(()=>{
        $(`.call_cont ul.tree`).off('click');
        //그룹 노드 클릭 - 그룹명(label)
        $(`ul.tree`).on('click', 'label', function(){
            $(this).siblings('.arrow:first').trigger('click'); 
        });
        
        //그룹노드 확장아이콘 클릭 - arrow클래스는 그룹노드에만 존재함
        $(`ul.tree`).on('click', '.arrow', function(){
            if($(this).closest('li').hasClass('fav')){
                $(this)
                    .toggleClass('expanded')
                    .toggleClass('collapsed')
                    .siblings("ul")
                    .toggleClass('none')
                ;
            }else{
                let current_group_code = $(this).closest('li').data('deptcode');
                let current_group_info = group_map[current_group_code];
                if(current_group_info == undefined){
                    return;
                }
                if(!$(this).parent().is(':has(li)')
                    && $(this).hasClass('collapsed')
                    && ((current_group_info.user_id_list||[]).length != 0 || (current_group_info.child_groups||[]).length != 0))
                {
                    //draw user
                    (current_group_info.user_id_list||[]).map((user_id, idx)=>{
                        drawOrgTreeUser($(this).siblings(`ul[data-deptcode=${current_group_code}]`), user_map[user_id], $(this).closest('li.fav').length == 0);
                    });
                    //draw child dept
                    (current_group_info.child_groups||[]).map((dept_id, idx)=>{
                        drawOrgTreeDept($(this).siblings(`ul[data-deptcode=${current_group_code}]`), group_map[dept_id].info, $(this).closest('li.fav').length == 0);
                    });
                }
                $(this)
                    .toggleClass('expanded')
                    .toggleClass('collapsed')
                    .siblings("ul:first")
                    .toggleClass('none')
                ;
            }
        });

        //즐겨찾기 추가/제거
        $(`ul.tree`).on('click', '.checktree.checkbox', function(e){
            e.stopPropagation();
            
            let fav_map = JSON.parse(localStorage.getItem('fav_map')||'{"user" : [], "dept" : []}');
            let li_element = $(this).closest('li');
            let type = li_element.data('type'), 
                target = type=='dept'?li_element.data('deptcode'):li_element.data('userid')
                ;
            if(type != undefined && target != undefined){
                target = target.toString();
                $(this).toggleClass('checked');
                if($(this).hasClass('checked')){
                    if(fav_map[type].includes(target)) return;
                    fav_map[type].push(target);
                    if(type == 'user'){
                        drawOrgTreeUser($('.fav_users_ul'), user_map[target], true, 'checked');
                    }else{
                        drawOrgTreeDept($('.fav_groups_ul'), group_map[target].info, true, 'checked');
                    }
                }else{
                    fav_map[type].splice(fav_map[type].indexOf(target), 1);
                    $(`ul.tree>li.fav li[data-${type=='user'?'userid':'deptcode'}=${target}]`).remove();
                    $(`ul.tree>li:not(.fav) li[data-${type=='user'?'userid':'deptcode'}=${target}] .fav_icon`).removeClass('checked');
                }
                localStorage.setArray('fav_map', fav_map);
            }
        });

        //사용자 상세 오픈
        $('ul.tree').on('click', 'label.detail_info_open', (e) =>{
            openUserDetail($(e.currentTarget).closest('li').data('userid'));
        });

        checkOrganization();
    });


    function checkOrganization(callback){
        let savedLastOrgUpdate = localStorage.getItem("lastOrgUpdate");
        requestAstro('base/v1/corp/updatetime/' + serverData.corp_code, {}, 'get')
        .then(function (res) {
            let data = res.data || {};
            let lastOrgUpdateTime = data.update_time || "";

            function afterLoad(umap) {
                drawInitOrganization();
                if (isIOS()) generateCallExtension(umap);
                localStorage.setItem("lastOrgUpdate", lastOrgUpdateTime);
            }

            if (savedLastOrgUpdate === lastOrgUpdateTime) {
                if ($.isEmptyObject(user_map)) {
                    readFile('user_map.json', function (txt) {
                        try { user_map = JSON.parse(txt || '{}'); } catch (e) { user_map = {}; }
                        if ($.isEmptyObject(user_map)) getOrganization(afterLoad);
                        else drawInitOrganization();
                    });
                } else {
                    drawInitOrganization();
                }
            } else {
                getOrganization(afterLoad);
            }
        })
        .catch(function (err) {
            console.error('checkOrganization', err);
            if (!$.isEmptyObject(organization_group_map) && (dept1_group || []).length > 0) drawInitOrganization();
        });
    }

    function getOrganization(callback) {
        if (serverData.rootGroupcode == undefined || serverData.rootGroupcode == '') {
            return popAlert("조직최상위 코드 설정이 필요합니다 관리자에게 문의하세요.");
        }

        Promise.all([
            requestAstro(`base/v1/users/${serverData.rootGroupcode}`, {}, 'get'),
            requestAstro(`base/v1/corps/withdept/${serverData.rootGroupcode}`, {}, 'get')
        ])
        .then(([uRes, gRes]) => {
            let users = uRes?.data || [];
            let groups = gRes?.data || [];

            group_map = {}; user_map = {};
            let mindepth = 9999;

            for (let idx = 0; idx < groups.length; idx++) {
                let group = groups[idx];
                group_map[group.code] = { info: group, child_groups: [], user_id_list: [], 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 g = group_map[user.dept_code];
                if (!g) continue;
                g.user_id_list.push(user.user_id);
                g.user_cnt++;
                user_map[user.user_id] = user;
                try {
                    if (typeof mcid_tel_no_format !== 'undefined' && user.cid_no) { user.mcid_tel_no = eval(mcid_tel_no_format); }
                    if (typeof mcid_tel_name_format !== 'undefined') { user.mcid_tel_name = eval(mcid_tel_name_format); }
                    if (typeof mcid_mobile_no_format !== 'undefined' && user.mobile_no) { user.mcid_mobile_no = eval(mcid_mobile_no_format); }
                } catch (error) { }
            }

            // 하위 합산/트리링크
            for (let oidx = 0; oidx < groups.length; oidx++) {
                let group = groups[oidx];
                let user_cnt = 0;
                let relationed_groups = groups.filter(item => item.relation_code && (item.relation_code + '.').startsWith(group.relation_code + '.'));
                if (relationed_groups) {
                    for (let idx = 0; idx < relationed_groups.length; idx++) {
                        user_cnt += (group_map[relationed_groups[idx].code] || {}).user_cnt || 0;
                    }
                }
                group.user_cnt = user_cnt;
                if (group.prnt_code && group_map[group.prnt_code]) {
                    group_map[group.prnt_code].child_groups.push(group.code);
                }
                group.haschild = ($.isEmptyObject(relationed_groups) && group.user_cnt <= 0) ? '0' : '1';
            }

            let dept1_group = groups.filter(item => item.relation_depth == mindepth);

            if(window.device != undefined){
                writeFile("user_map.json", JSON.stringify(user_map), function () {
                    localStorage.setArray("group_map", group_map);
                    localStorage.setArray("dept1_group", dept1_group);
                    if (callback) { callback(user_map); }
                });
            }else{
                localStorage.setArray("group_map", group_map);
                localStorage.setArray("dept1_group", dept1_group);
                if (callback) { callback(user_map); }
            }
        })
        .catch((err) => {
            console.log('getOrganization fail', err.message, err.stack);
            if (callback) { callback({ error: true }); }
        });
    }

    function generateCallExtension(userMapJson) {
        let groupSaveDateLocal = window.localStorage.getItem("setGroupLastDate");
        window.plugins?.gntel?.checkMIddleDBFileExist((iExists) => {
            if (!iExists) {
                window.plugins.gntel.middleDBGenerator(() => { }, () => { }, 'user_map.json');
            } else {
                let params = [];
                let list = Object.values(userMapJson).filter(item => item.create_time > (groupSaveDateLocal || ''));
                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 > (groupSaveDateLocal || ''));
                list.forEach(item => { if (item.mcid_tel_no != '') params.push({ 'name': (item.mcid_tel_name || ''), 'number': item.mcid_tel_no, 'status': 'u' }); });
                if (params && !$.isEmptyObject(params)) {
                    window.plugins.gntel.updateMiddleDB(() => { }, () => { }, params);
                }
            }
        }, (r) => { console.log('checkMIddleDBFileExist fail', r); });
    }

    function drawInitOrganization() {
        let dept1_group = localStorage.getArray("dept1_group"),
            fav_map = JSON.parse(localStorage.getItem('fav_map')||'{"user" : [], "dept" : []}')
            ;
        $('ul.tree>li.fav>ul').empty();
        $('ul.tree>li:not(.fav)').remove();

        //즐겨찾기 구성
        fav_map.user.map((user_id, idx)=>{
            drawOrgTreeUser($('.fav_users_ul'), user_map[user_id]);
        });
        fav_map.dept.map((group_code, idx)=>{
            drawOrgTreeDept($('.fav_groups_ul'), group_map[group_code].info)
        });
        //------즐겨찾기 구성 끝

        (dept1_group||[]).forEach((dept)=>{

            drawOrgTreeDept($('.call_cont ul.tree'), dept, false);

            let child_user_list = group_map[dept.code].user_id_list;
            if(child_user_list.length >0){
                for(let idx in child_user_list){
                    drawOrgTreeUser($(`#ul_org_tree .ul[data-deptcode=${dept.code}]`), user_map[child_user_list[idx]]);
                }
            }
        });
    }

    function drawOrgTreeUser($element, user, show_fav, fav_checked){
        let fav_map = JSON.parse(localStorage.getItem('fav_map')||'{"user" : [], "dept" : []}'),
            noticeManageGroups = String(serverData.notice_manage_groups || '').split(',').filter(x => x !== null && x !== undefined && x !== "")
        ;
        if(user == null || user == undefined) return;
        if(show_fav == undefined) show_fav = true;
        if(fav_checked == undefined){
            if(fav_map.user.indexOf(user.user_id)>=0){
                fav_checked = 'checked'
            }else{
                fav_checked = '';
            }
        }

        if(noticeManageGroups.includes(user.dept_code)){
            return ;
        }
        //".list_org_srch"
        $element.append(
            $('#tree_group_person_template').text()
            .replace(/{{user_name}}/g, `${(user.position != '' && user.position != undefined)?'['+user.position+'] ':''}${user.name}`)
            .replace(/{{user_id}}/g, user.user_id)
            .replace(/{{fav_checked}}/g, fav_checked)
            .replace(/{{show_fav}}/g, show_fav?'':'none')
            .replace(/{{nocheckbox}}/g, show_fav?'':'nocheckbox')
            .replace(/{{label_none_fav}}/g, show_fav?'':'label_none_fav')
            .replace(/{{user_photo}}/,`background-image:url('${server_host}${user.photo_path_url}'),url('images/thumb.png')`)
        )
    }

    function drawOrgTreeDept($element, dept, show_fav, fav_checked){
        let fav_map = JSON.parse(localStorage.getItem('fav_map')||'{"user" : [], "dept" : []}'),
            noticeManageGroups = String(serverData.notice_manage_groups || '').split(',').filter(x => x !== null && x !== undefined && x !== "")
        ;

        if(show_fav == undefined) show_fav = true;
        if(fav_checked == undefined){
            if(fav_map.dept.indexOf(dept.code)>=0){
                fav_checked = "checked";
            }else{
                fav_checked = "";
            }
        }

        if(noticeManageGroups.includes(dept.code)){
            return ;
        }

        $element.append(
            $('#tree_group_template').text()
            .replace(/{{dept_name}}/g, dept.name+ " ("+dept.user_cnt +")")
            .replace(/{{dept_code}}/g, dept.code)
            .replace(/{{fav_checked}}/g, fav_checked)
            .replace(/{{show_fav}}/g, show_fav?'':'none')
            .replace(/{{nocheckbox}}/g, show_fav?'':'nocheckbox')
            .replace(/{{label_none_fav}}/g, show_fav?'':'label_none_fav')
        )
    }

    window.G = {
        ...window.G||{},
        checkOrganization : checkOrganization,
        drawInitOrganization : drawInitOrganization
    }
})();