(function () {
    'use strict';
    let history_pageinsize = 10 , draw_list = false;
    let finded_users = {};
    let init = () => {
        // call_history_list
        current_history_tab = 'outGoingCall';

        historySwiperDraw();
        drawOutGoingCallHistory();

        $(`.historySwiper .history a.tab[data-id=${'outGoingCall'}]`).addClass('on');

        // 통화이력 공통 콜 팝업
        $(document)
        .off('click.historyCall', '.call_cont ul.recent .call')
        .on('click.historyCall', '.call_cont ul.recent .call', function (e) {
            e.preventDefault();

            var $a = $(this);
            var $li = $a.closest('li');

            var rawNum = $a.data('to') || '';
            var cleanNum = cleanPhoneNumber(rawNum);
            if (!cleanNum) return;

            // 표시용 번호
            var displayNum = getKoreanNumber(cleanNum);

            var name = $.trim($li.find('.who .name').text()) || displayNum;


            // 팝업 호출 (단일 번호)
            openCallPopupByNumbers(name, [{
                id: 'history_' + cleanNum,
                number: cleanNum,
                display: displayNum
            }]);
        });

        // 착발신 클릭 이벤트
        $('.historySwiper .history a.tab').on('click', function (e) {
            const historyId = $(this).data('id');
            
            $('.historySwiper .history a.tab.on').removeClass('on');
            $(`.historySwiper .history a.tab[data-id=${historyId}]`).addClass('on');


            // 발신 클릭 시 기존 네이티브 로직 실행
            if(historyId === 'outGoingCall'){
                $('.call_cont ul.recent').empty();
                current_history_tab = "outGoingCall"
                drawOutGoingCallHistory(0);
            } else if (historyId === 'inComingCall'){
                $('.call_cont ul.recent').empty();
                current_history_tab = "inComingCall";
                callHistory();
            } else if (historyId === 'missedCall'){
                $('.call_cont ul.recent').empty();
                current_history_tab = "missedCall";
                callHistory();
            }
        })

        //검색
		$('#btn_search_history').off('click').on('click', ()=>{
			if (current_history_tab == 'outGoingCall') {
                drawOutGoingCallHistory();
            } else {
                drawCallHistory();
            }
		});
		$('#inp_board_search_history').off('keyup').on('keyup', (e)=>{
			if(e.keyCode == 13)	{$('#btn_search_history').trigger('click')}
		});

        $('.call_cont').off('scroll').bind('scroll', () => {
            const itemCount = $('.call_cont').find('ul.recent > li').length;
            if (itemCount < history_pageinsize) return;

            const threshold = 12;
            const remaining = $('.call_cont')[0].scrollHeight - $('.call_cont')[0].scrollTop - $('.call_cont')[0].clientHeight;

            if (!draw_list && remaining <= threshold) {
                draw_list = true;
                if(current_history_tab == "outGoingCall"){
                    Promise.resolve(drawOutGoingCallHistory(itemCount))
                    .finally(() => { draw_list = false; });
                }else {
                    Promise.resolve(drawCallHistory(itemCount))
                    .finally(() => { draw_list = false; });
                }
            }
        });
    };

    // 발신 이력
    function drawOutGoingCallHistory(offset = 0){
        if(offset >= call_history_list.length) return;

        if(offset == 0){
            $('.call_cont ul.recent').empty();
        }

        let searchval = $('#inp_board_search_history').val();
        let sublist = null;


        function getUser(number){
            let finduser = Object.values(user_map).find(user => { // 수정: userMapArray에서 번호를 찾음
                return user.cid_no == nomalizeNumber(number) 
                || `${serverData.svcPrefixNo}${user.cid_no}` == nomalizeNumber(number) 
                || user.mobile_no == nomalizeNumber(number)
                || user.etc_no == nomalizeNumber(number)
                ;
            })

            if (!user_map || Object.keys(user_map).length === 0) {
                return null;
            }

            if (finduser == undefined) {
                let contacts = localStorage.getArray("contact");

                if (!Array.isArray(contacts)) contacts = [];

                finduser = contacts.find(contact => {
                    let phoneNumbers = contact.phoneNumbers;
                    let isFind = false;
                    for (let pnumber of phoneNumbers) {
                        if (pnumber.normalizedNumber == nomalizeNumber(number)) {
                            isFind = true;
                            contact.name = contact.displayName;
                            break;
                        }
                    }
                    return isFind;
                });
            }
            return finduser;
        }
        
        if($.trim(searchval) == ''){
            sublist = call_history_list.slice(offset, offset+history_pageinsize);
        }else{
                sublist = call_history_list.filter(item => {
                let findUser = getUser(item.number);
                return gformatter.number(item.number).indexOf(searchval)>-1 || ( findUser!= undefined && (findUser.name.indexOf(searchval)>-1 || getCho(findUser.name).indexOf(searchval)>-1 ) ) ;
            }).slice(offset, offset+history_pageinsize);
        }

        sublist.forEach((callhistory, idx) => {
            let finduser = getUser(callhistory.number);
            let displayName = finduser?.name || "확인되지 않은 번호";
            let photourl = '';
            let roles = [];

            if (finduser) {
                photourl = finduser.photo_path_url ? `${server_host}${finduser.photo_path_url}` : '';
                roles = finduser.full_group_names ? finduser.full_group_names.split("@@") : [];
            }

            $('.call_cont ul.recent').append(
                $('#li_call_history_template').text()
                .replace(/{{name}}/g, displayName)
                .replace(/{{number}}/g, gformatter.tel(callhistory.number))
                .replace(/{{nomalizedNumber}}/g, callhistory.number)
                .replace(/{{date_time}}/g, callhistory.date_time)
                .replace(/{{user_photo}}/g, 
                    photourl == ''?
                    `url('images/thumb.png')`
                    :`background-image:url('${server_host}${finduser?.photo_path_url}'),url('images/thumb.png')`)
                .replace(/{{role1}}/g, roles[1] || "")
                .replace(/{{role2}}/g, roles[2] || "")
            );
        });
    }

    // 착신, 부재중
    function drawCallHistory(offset = 0){

        let draw_call_list = {};

        if (current_history_tab == "outGoingCall") {
            draw_call_list = call_history_list;
        } else {
            draw_call_list = history_list;
        }

        if(offset >= draw_call_list.length) return;
        if(offset == 0){
            $('.call_cont ul.recent').empty();
        }

        let searchval = $('#inp_board_search_history').val();
        let sublist = null;


        function getUser(number){
            if (!user_map || Object.keys(user_map).length === 0) {
                return null;
            }

            let n = "";

            if(( number.startsWith('010') || number.startsWith('+82') ) && number.length >= 11) {
                n = nomalizeNumber(number);
            } else if (number.startsWith(serverData.accCode + '010')){
                n = number.slice(serverData.accCode?.length ?? 0);
            } else if (nomalizeNumber(number) == ""){
                n = number;
            } else {
                n = getCidNumber(number);;
            }

            let finduser = Object.values(user_map).find(user => {
                return user.cid_no == n
                    || `${serverData.svcPrefixNo}${user.cid_no}` == n
                    || user.mobile_no == n
                    || user.etc_no == nomalizeNumber(number)
                    ;
            });

            if (!finduser) {
                let contacts = localStorage.getArray("contact");

                if (!Array.isArray(contacts)) contacts = [];

                finduser = contacts.find(contact => {
                    const phoneNumbers = Array.isArray(contact.phoneNumbers) ? contact.phoneNumbers : [];
                    return phoneNumbers.some(p => p.normalizedNumber == n);
                });
            }
            return finduser || null;
        }
        
        if($.trim(searchval) == ''){
            sublist = draw_call_list.slice(offset, offset+history_pageinsize);
        }else{
            sublist = draw_call_list.filter(item => {
                let findUser = getUser(item.number);
                return gformatter.number(item.number).indexOf(searchval)>-1 || ( findUser!= undefined && (findUser.name.indexOf(searchval)>-1 || getCho(findUser.name).indexOf(searchval)>-1 ) ) ;
            }).slice(offset, offset+history_pageinsize);
        }

        sublist.forEach((callhistory, idx) => {
            let finduser = getUser(callhistory.number);
            
            let displayNumber = callhistory.number;

            if((displayNumber.startsWith('010') || displayNumber.startsWith('+82') ) && displayNumber.length >= 11) {
                displayNumber = gformatter.tel(nomalizeNumber(displayNumber));
            } else if (displayNumber.startsWith(serverData.accCode + '010')){
                displayNumber = gformatter.tel(nomalizeNumber(displayNumber.slice(serverData.accCode?.length ?? 0)));
            } else if (nomalizeNumber(displayNumber) == "") {
                displayNumber = gformatter.tel(displayNumber);
            }else {
                displayNumber = gformatter.tel(getCidNumber(displayNumber));
            }

            const displayName = finduser?.name || "확인되지 않은 번호";

            let photourl = '';
            let roles = [];

            if (finduser) {
                photourl = finduser.photo_path_url ? `${server_host}${finduser.photo_path_url}` : '';
                roles = finduser.full_group_names ? finduser.full_group_names.split("@@") : [];
            }

            $('.call_cont ul.recent').append(
                $('#li_call_history_template').text()
                .replace(/{{name}}/g, displayName)
                .replace(/{{number}}/g, displayNumber)
                .replace(/{{nomalizedNumber}}/g, displayNumber)
                .replace(/{{date_time}}/g, callhistory.date_time)
                .replace(/{{user_photo}}/g, 
                    photourl == ''?
                    `url('images/thumb.png')`
                    :`background-image:url('${server_host}${finduser?.photo_path_url}'),url('images/thumb.png')`)
                .replace(/{{role1}}/g, roles[1] || "")
                .replace(/{{role2}}/g, roles[2] || "")
            );
        });
    }

    const callHistory = () => {

        let userData = JSON.parse(localStorage.getItem("userData"));
        let user_dn = userData.dn;

        let url = current_history_tab == "inComingCall" ? "rsv_hist" : "missed_hist";

        // requestAstro(`mdial/v1/hist/${url}/{user_dn}`,{},'get')
        requestAstro(`mdial/v1/hist/${url}/${user_dn}`,{},'get')
        .then(response => {
            if(response.code == '0000'){
                history_list = response.data;
                drawCallHistory();
            } else {
                console.log("astro Fail");
            }
        })
        .catch(error => {
            console.error(error);
        })
    }

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

// 착발신 탭 그리기
const historySwiperDraw = () => {

    let hisTab = [
        {'id': 'outGoingCall', 'name': '발신'},
        {'id': 'inComingCall', 'name': '착신'}, 
        {'id': 'missedCall', 'name': '부재중'}
    ];

    hisTab.forEach((item, index) => {
        //boardswiper
        $('.historySwiper .swiper-wrapper').append(
            substituteVariables($('#template_history_swiper').text(), item)
        )
    })

    //반드시 6배수이여야함 모자르는 수는 <div class="swiper-slide"></div> <!-- 메뉴가 없어도 빈레이어 유지 필수 -->
    // <!-- 
    // 	[중요] <div class="swiper-slide"></div>는 6의 배수 만큼 존재해야 함. (6개 이하인 경우 6개, 7~12개 경우 12개...)
    // -->
    if (hisTab.length % 6 != 0) {
        let count = hisTab.length % 6;
        for (let idx = 0; idx < (6 - count); idx++) {
            $('.historySwiper>.swiper-wrapper').append(
                '<div class="swiper-slide"></div>'
            )
        }
    }

    new Swiper(".historySwiper", {
        slidesPerView: "auto",
        spaceBetween: 20,
        freeMode: true
    });

}

const getCidNumber = (number) => {
    return number.slice(-serverData.cidLength);
}



