(function () {
    'use strict';

    
    $(()=>{
       
    });

    function init() {
        console.log("organization init start");
        $(`.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], $(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 org_fav_map = JSON.parse(localStorage.getItem('org_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(org_fav_map[type].includes(target)) return;
                    org_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], true, 'checked');
                    }
                }else{
                    org_fav_map[type].splice(org_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('org_fav_map', org_fav_map);
            }
        });

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

            let detailInfo = $('.dim_bg.detail_info');

            if(detailInfo[0].style['font-size'] == ''){
                detailInfo[0].style['font-size'] = detailInfo.css('font-size');
            }
        });

        //search
        $('#inp_board_search_organization').on('keyup', (e) => {
            if(e.keyCode == 13){
                $('#btn_search_organization').trigger('click');
            }
        });

        $('#btn_search_organization').on('click', function() {
            let query = $.trim($('#inp_board_search_organization').val() || '');
            
            let $resultList = $('.list_org_srch');

            if(query.length == 0){
                $resultList.empty();
                $('.article_srch').addClass('none')
                $('.org_tree').removeClass('none');
                $(`.org_empty-person`).addClass('none');
                return;
            }
            
            $resultList.empty();

            let queryLower = query.toLowerCase();
            let queryDigits = query.replace(/\D+/g, '');

            // 매칭
            let matchCount = 0;
            for (let userKey in user_map) {
                if (!user_map.hasOwnProperty(userKey)) continue;
                let user = user_map[userKey];

                let nameLower = gformatter.string(user.name).toLowerCase();
                let choLower = gformatter.string(user.cho_name).toLowerCase();
                let deptLower = gformatter.string(user.dept_name).toLowerCase();
                let descLower = gformatter.string(user.description).toLowerCase();

                let mobileDigits = gformatter.number(user.mobile_no);
                let etcDigits = gformatter.number(user.etc_no);
                let cidDigits = gformatter.number(user.cid_no);

                let isHit =
                    (nameLower.indexOf(queryLower) > -1) ||
                    (choLower.indexOf(queryLower) > -1) ||
                    (query.length >= 2 && deptLower.indexOf(queryLower) > -1) ||
                    (query.length >= 2 && descLower.indexOf(queryLower) > -1) ||
                    (queryDigits !== '' && (
                        mobileDigits.indexOf(queryDigits) > -1 ||
                        etcDigits.indexOf(queryDigits) > -1 ||
                        cidDigits.indexOf(queryDigits) > -1
                    ));

                if (isHit) { 
                    // appendResultUser(user); 
                    drawOrgTreeSearchUser($resultList, user)
                    matchCount++; 
                }
            }

            if (matchCount > 0) {
                $('.org_tree').addClass('none');
                $('.article_srch').removeClass('none');
                $(`.org_empty-person`).addClass('none');
            } else {
                $resultList.empty();
                $('.article_srch').addClass('none')
                $('.org_tree').addClass('none');
                $(`.org_empty-person`).removeClass('none');
            }
        });

        checkOrganization();
        console.log("organization init end");
    }


    function checkOrganization(callback){
        console.log("check organization start");
        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);
            }
            console.log("check organization end")
        })
        .catch(function (err) {
            console.error('checkOrganization', err);
            if (!$.isEmptyObject(organization_group_map) && (dept1_group || []).length > 0) drawInitOrganization();
        });
    }

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

        let users_request_url = `base/v1/users/${serverData.rootGroupcode}`;
        checkLoaderWrap('plus');
        Promise.all([
            requestAstro(users_request_url, {}, 'get'),
            requestAstro(`base/v1/corps/withdept/${serverData.rootGroupcode}`, {}, 'get'),
            requestAstro(`base/v1/dept/users/${serverData.rootGroupcode}`, {}, 'get')
        ])
        .then(([uRes, gRes, gUsers]) => {
            
            console.log('process start', new Date());
            let users = uRes?.data || [];
            let groups = gRes?.data || [];
            let mindepth = 9999;

            group_map = {}; user_map = {};

            let g_user_cnt_map = (gUsers?.data||[]).reduce((acc, item) =>{
                acc[item.code] = item;
                return acc;
            }, {});

            group_map = groups.reduce((acc, item) =>{
                acc[item.code] = {...item, user_cnt : (g_user_cnt_map[item.code]?.user_cnt||0)};
                if (item.relation_depth < mindepth) mindepth = item.relation_depth;
                return acc;
            }, {});

            user_map = users.reduce((acc, item) =>{
                acc[item.user_id] = item;
                return acc;
            }, {});

            let dept1_group = Object.values(group_map).filter(item => item.relation_depth == mindepth);
            
            console.log('callback start', new Date());
            localStorage.setArray("group_map", group_map);
            localStorage.setArray("dept1_group", dept1_group);
            if (callback) { callback(user_map); }
            console.log('callback end', new Date());

            for (let idx = 0; idx < users.length; idx++) {
                let user = users[idx];
                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 = (isIOS() == true && user.user_id == userData.userId)?"":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) { }
            }
            checkLoaderWrap('minus');
            if(window.device != undefined){
                writeFile("user_map.json", JSON.stringify(user_map), function () {
                    console.log("writeFile success");
                    try {
                        //native에서 namecard.json파일 갱신
                        cordova.exec(() =>{
                            console.log("upDateUserData success");
                        }, () =>{
                            console.log("upDateUserData fail");
                        }, "GntelPlugin", "upDateUserData", []);
                    } catch (error) {
                        console.warn("upDateUserData ::", error);
                    }finally{
                        console.log("write file ended", new Date());
                    }
                });
            }
            console.log('process end', new Date());
        })
        .catch((err) => {
            console.log('getOrganization fail', err.message, err.stack);
            if (callback) { callback({ error: true }); }
        });
    }

    function generateCallExtension(userMapJson) {
        console.log("generate call extension start", new Date());
        let groupSaveDateLocal = window.localStorage.getItem("lastOrgUpdate");
        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.user_id != userData.userId)?(item.mcid_tel_name || ''):''), 
                            'number': item.mcid_tel_no, 
                            'status': 'c' }); 
                    }
                    if(item.mcid_mobile_no != ''){
                        params.push({ 
                            'name': ((item.user_id != userData.userId)?(item.mcid_tel_name || ''):''), 
                            'number': item.mcid_mobile_no, 
                            'status': 'c' 
                        }); 
                    }
                });
                list = Object.values(userMapJson).filter(item => item.update_time > (groupSaveDateLocal || ''));

                let set_params = new Set(params.map(item => item.number));

                list = list.filter(item => !set_params.has(item.mcid_tel_no));

                list.forEach(item => { 
                    if (item.mcid_tel_no != '') {
                        params.push({ 
                            'name': ((item.user_id != userData.userId)?(item.mcid_tel_name || ''):''), 
                            'number': item.mcid_tel_no, 
                            'status': 'u' 
                        }); 
                    }
                    if (item.mcid_mobile_no != '') {
                        params.push({ 
                            'name': ((item.user_id != userData.userId)?(item.mcid_tel_name || ''):''), 
                            'number': item.mcid_mobile_no, 
                            'status': 'u' 
                        }); 
                    }
                });

                if (params && !$.isEmptyObject(params)) {
                    window.plugins.gntel.updateMiddleDB(() => { 
                        console.log("generate call extension success", new Date());
                    }, () => { 
                        console.log("generate call extension fail", new Date());
                    }, params);
                }
            }
        }, (r) => { console.log('checkMIddleDBFileExist fail', r); });
    }

    function drawInitOrganization() {
        console.log("draw organization start", new Date());
        let dept1_group = localStorage.getArray("dept1_group"),
            org_fav_map = JSON.parse(localStorage.getItem('org_fav_map')||'{"user" : [], "dept" : []}')
            ;
        $('ul.tree.org_tree>li.fav>ul').empty();
        $('ul.tree.org_tree>li:not(.fav)').remove();

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

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

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

            let child_user_list = group_map[dept.code].user_id_list;
            if(child_user_list != undefined && child_user_list.length >0){
                for(let idx in child_user_list){
                    drawOrgTreeUser($(`ul.tree.org_tree .ul[data-deptcode=${dept.code}]`), user_map[child_user_list[idx]]);
                }
            }
        });
        console.log("draw organization end", new Date());
    }

    function drawOrgTreeUser($element, user, show_fav, fav_checked){
        let org_fav_map = JSON.parse(localStorage.getItem('org_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(org_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 drawOrgTreeSearchUser($element, user, show_fav, fav_checked){
        let org_fav_map = JSON.parse(localStorage.getItem('org_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(org_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_search_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')`)
            .replace(/{{clss}}/g, user.clss)
            .replace(/{{user_group}}/g, user.full_group_names.split('@@').splice(-3).join(' '))
        )
    }

    function drawOrgTreeDept($element, dept, show_fav, fav_checked){
        let org_fav_map = JSON.parse(localStorage.getItem('org_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(org_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')
        )
    }

    G.checkOrganization = checkOrganization;
    G.drawInitOrganization = drawInitOrganization;
    G.drawOrgTreeDept = drawOrgTreeDept;
    G.drawOrgTreeUser = drawOrgTreeUser;
    G.drawOrgTreeSearchUser = drawOrgTreeSearchUser;
    G.init.organization = init;

})();