$(()=>{
    //통화목록 이름 및 전화 클릭시
    $("#address,#history,#history_search").on("click", ".history_cell", function(){
        let telHistory = $(this).parents("li").children(".others_history");

        let historyOne = $(this).parents("li").children(".history_one");

        if(telHistory.find("li").length == 0){
            return;
        }
        telHistory.slideToggle("fast");
        historyOne.toggleClass("on");
    });

    //통화목록 정렬
    $('.search_wrap_03>.sort_tool>button.btn_sort').on('click', function(){
        $('.search_wrap_03>.sort_tool>button.btn_sort.on').removeClass('on');
        $(this).addClass('on');
        historyOrder = $(this).hasClass('sort_desc_history')?true:false;
        
        $(".list_history").empty();
        printHistory();
    });

    $("#history").on("taphold", ".history_cell_box", function(){
        let thisID = $(this).data("historyid");
        //alert(thisID);
        popConfirm("해당 통화목록을 삭제 하시겠습니까?", function() {
            deleteHistory(thisID);
        });
    });
});

function printHistory() {

    let listFavo = window.localStorage.getArray("favorite");
    let callHistory = window.localStorage.getArray("callHistory");
    console.log('callHistory = ' + JSON.stringify(callHistory));

    let data = new Array();
    // userMap을 배열로 변환하고, 필요한 형태로 가공
    let userMapArray = [];
    for (let key in user_map) {
        let user = user_map[key];
        let phoneNumberType = "기타"; // 기본값은 "기타"로 설정
        let phoneNumber = user.mobile_no; // 예시로 휴대폰 번호를 사용했다고 가정
        let cidNumberType = "기타";
        let cidNumber = user.cid_no;

        // 전화번호의 길이에 따라 타입을 지정
        if (phoneNumber.length === 11) {
            phoneNumberType = "휴대폰";
        }

        // 전화번호의 길이에 따라 타입을 지정
        if (cidNumber.length === 4) {
            cidNumberType = "사무실";
        }

        let userObj = {
            id: user.uid,
            displayName: user.name,
            phoneNumbers: [{ number: user.cid_no, normalizedNumber: user.cid_no, type: cidNumberType }, { number: user.mobile_no, normalizedNumber: user.mobile_no, type: phoneNumberType }],
            thumbnail: "" // 적절한 썸네일 정보가 있다면 여기에 추가
        };
        userMapArray.push(userObj);
    }

    if (nullcheck(callHistory)) {
        return;
    }
    if (!historyOrder) {
        callHistory.reverse();
    }

    $(".list_history").empty();
    historyContact = [];

    for (let i = 0; i < callHistory.length; i++) {
        let callHistoryNum = callHistory[i]["num"];
        console.log('callHistoryNum = ' + callHistoryNum);

        let contactArray = [];
        if (!nullcheck(newContact)) {
            contactArray = contactArray.concat(newContact);
        }
        if (!nullcheck(userMapArray)) {
            contactArray = contactArray.concat(userMapArray);
        }

        contactArray = contactArray.filter(contact => {
            if (nullcheck(contact.phoneNumbers)) {
                return false;
            }
            return contact.phoneNumbers.some(item => callHistoryNum === getRemovePlusEightTwo(item.normalizedNumber));
        });

        if (!nullcheck(contactArray)) {
            let contact = contactArray[0];
            historyContact.push(contact);
            let callHistoryTime = callHistory[i]["time"];
            let callHistoryTimeHtml = "";
            let callHistoryTimeHtmlOthers = "";

            if ($.trim(callHistory[i]["id"]).startsWith("-1")) {
                callHistory[i]["id"] = String(contact.id);

                let phoneNumber = contact.phoneNumbers.find(item => $.trim(callHistory[i]["num"]) === getRemovePlusEightTwo(item.normalizedNumber));
                let type = phoneNumber.type;

                callHistory[i]["type"] = type;
            }
            console.log('callHistoryTime.length = ' + callHistoryTime.length);
            let callCount = 0;
            for (let j = 0; j < callHistoryTime.length; j++) {
                console.log('callHistoryTime[j] = ' + callHistoryTime[j]);
                if (j == 0) {
                    callHistoryTimeHtml += "<li>" + callHistoryTime[j] + "</li>";
                } else {
                    callHistoryTimeHtmlOthers += "<li>" + callHistoryTime[j] + "</li>";
                }
                callCount++;
            }
            let callCountHtml = "";
            let historyOneHtml = "";
            if (callCount > 1) {
                callCountHtml += " (" + callCount + ")";
                historyOneHtml = "history_one";
            } else {
                historyOneHtml = "history_one none";
            }
            if (contact.phoneNumbers != null && contact.displayName != null) {
                let favoHtml = "";
                console.log("즐찾" + contact.phoneNumbers);

                let liEl = "";
                if (listFavo.indexOf($.trim(contact.id)) >= 0) {
                    favoHtml = "<a href='javascript:;' onclick='toggleFavorite(" + contact.id + ")' class='btn_favo'></a>"
                } else {
                    favoHtml = "<a href='javascript:;' onclick='toggleFavorite(" + contact.id + ")' class='btn_favo_no'></a>"
                }
                let callHistoryTimeFirst = getYear(callHistoryTime[0]);
                console.log("callHistoryTimeFirst" + callHistoryTimeFirst);
                console.log("imsitime" + imsitime);
                if (imsitime != callHistoryTimeFirst) {
                    liEl += "<li class='year'>" + callHistoryTimeFirst + "</li>";

                    imsitime = callHistoryTimeFirst;
                    console.log("추가");
                }
                liEl += "<li class='history_cell_box' data-id='" + contact.id + "'data-historyid='" + callHistory[i]["historyId"] + "' data-contact='" + JSON.stringify(contact) + "'>";
                liEl += "<span class='portrait'><img src='" + getThumbImage(contact.thumbnail) + "'></span>";
                liEl += favoHtml;
                liEl += "<h4 class='history_cell'>" + contact.displayName + callCountHtml + "</h4>";
                liEl += "<p class='history_cell " + historyOneHtml + "'>" + callHistory[i]["type"] + " " + callHistory[i]["num"] + "</p><button type='button' class='btn_call'></button>";
                liEl += "<ul class='history_call'>";
                liEl += callHistoryTimeHtml;
                liEl += "</ul>";
                liEl += "<ul class='history_call others_history'>";
                liEl += callHistoryTimeHtmlOthers;
                liEl += "</ul>";
                liEl += "</li>";
                if (isIOS12()) {
                    $(".list_history").append(liEl);
                } else {
                    data.push(liEl);
                }
            }
        } else {
            callHistory[i]["id"] = "-1" + callHistory[i].num;
            callHistory[i]["type"] = "기타";
            let anonymousLiEl = printHistoryAnonymous(callHistory[i]);

            if (isIOS12()) {
                $(".list_history").append(anonymousLiEl);
            } else {
                data.push(anonymousLiEl);
            }
        }
    }

    if (!isIOS12()) {
        if (!nullcheck(clusterizeHistory)) {
            clusterizeHistory.destroy(true);
        }
        clusterizeHistory = new Clusterize({
            rows_in_block: 50,
            blocks_in_cluster: 5,
            offset: 31 + 61,
            rows: data,
            scrollId: 'scrollAreaHistory',
            contentId: 'contentAreaHistory'
        });
    }

    if (!historyOrder) {
        callHistory.reverse();
    }
    console.log('callHistory 1 = ' + JSON.stringify(callHistory));
    console.log("historyContact" + JSON.stringify(historyContact));
    window.localStorage.setArray("callHistory", callHistory);
    imsitime = "";
    
};

function printHistoryAnonymous(callHistoryAnonymous){
    let callHistoryTime = callHistoryAnonymous["time"];
    let callHistoryTimeHtml = "";
    let callHistoryTimeHtmlOthers = "";
    console.log('callHistoryTime.length = ' + callHistoryTime.length);
    let anonymousPhoneNumber = {
        number:callHistoryAnonymous["num"],
        normalizedNumber:callHistoryAnonymous["num"],
        type:"기타"
    };
    let anonymousPhoneNumbers = [anonymousPhoneNumber];
    let anonymousContact = {
        displayName:"알수없음",
        phoneNumbers:anonymousPhoneNumbers,
        id:"-1"+callHistoryAnonymous["num"]
    };
    historyContact.push(anonymousContact);
    let callCount = 0;
    for (let j = 0; j < callHistoryTime.length; j++) {
        console.log('callHistoryTime[j] = ' + callHistoryTime[j]);
        if(j==0){
            callHistoryTimeHtml += "<li>"+callHistoryTime[j]+"</li>";
        }else{
            callHistoryTimeHtmlOthers += "<li>"+callHistoryTime[j]+"</li>";
        }
        callCount++;
    }
    let callCountHtml = "";
    let historyOneHtml = "";
    if(callCount>1){
        callCountHtml += " ("+callCount+")";
        historyOneHtml = "history_one";
    }else{
        historyOneHtml = "history_one none";
    }
    let idHtml = "-1"+callHistoryAnonymous["num"];
    let liEl ="";

    let callHistoryTimeFirst = getYear(callHistoryTime[0]);
    console.log("callHistoryTimeFirst"+ callHistoryTimeFirst);
    console.log("imsitime"+ imsitime);
    if(imsitime!=callHistoryTimeFirst) {
        liEl += "<li class='year'>"+callHistoryTimeFirst+"</li>";

        imsitime=callHistoryTimeFirst;
        console.log("추가");
    }

    liEl += "<li class='history_cell_box' data-id='"+ anonymousContact.id + "'data-historyid='"+ callHistoryAnonymous["historyId"] + "' data-contact='"+JSON.stringify(anonymousContact) +"'>";
    //liEl += "<li data-id='"+ anonymousContact.id +"' data-contact='"+JSON.stringify(anonymousContact) +"'>";
    liEl += "<span class='portrait'><img src='img/blank_gray_2.png'></span>";
    liEl += "<h4 class='history_cell'>알수없음"+callCountHtml+"</h4>";
    liEl += "<p class='history_cell "+historyOneHtml+"'>"+callHistoryAnonymous["type"]+" "+callHistoryAnonymous["num"]+"</p><button type='button' class='btn_call'></button>";
    liEl += "<ul class='history_call'>";
    liEl += callHistoryTimeHtml;
    liEl += "</ul>";
    liEl += "<ul class='history_call others_history'>";
    liEl += callHistoryTimeHtmlOthers;
    liEl += "</ul>";
    liEl += "</li>";

    return liEl;
    //$(".list_history").append(liEl);

}
//통화목록 검색
function searchHistory(){

    let listFavo = window.localStorage.getArray("favorite");
    let keyword = $(".btn_sch_history").val();
    let callHistory = window.localStorage.getArray("callHistory");

    if(keyword.length>0){
        let data = new Array();
        let newContact = new Array(); //빈배열
        newContact = historyContact;

        /**
         * IOS 통화목록 검색시 이름검색 이슈 있어서 주소록과 동일한 필터 반영함
         */
        // let searchContactName = newContact.filter(item => new RegExp(keyword).test(item.displayName));
        let searchContactName = newContact.filter(item => new RegExp(keyword).test((typeof item.lastName == "undefined" ? "" : item.lastName)
                                                                                                + (typeof item.middleName == "undefined" ? "" : item.middleName)
                                                                                                + (typeof item.firstName == "undefined" ? "" : item.firstName)));
                                                                                                
        let searchContactChoName = newContact.filter(item => new RegExp(keyword).test(item.nameCho));

        let searchContactPlus = searchContactName.concat(searchContactChoName);

        searchContactByNumber = newContact.filter(({phoneNumbers}) => {
            if( nullcheck(phoneNumbers)){
                return
            }else{
                return phoneNumbers.some(item => new RegExp(keyword).test(item.normalizedNumber))
            }

        })
        let  searchContact = searchContactPlus.concat(searchContactByNumber);
        favoriteContact = window.localStorage.getArray("favorite");

        $(".list_sch_history").empty();
        for (let i = 0; i < callHistory.length; i++) {

            let callHistoryNum = callHistory[i]["num"];

            let contactArray = searchContact.filter(({phoneNumbers}) => {
                if( nullcheck(phoneNumbers)){
                    return
                }else{
                    return phoneNumbers.find(item => callHistoryNum === getRemovePlusEightTwo(item.normalizedNumber));
                }
            })
            if(!nullcheck(contactArray)){
                let contact = contactArray[0];
                let callHistoryTime = callHistory[i]["time"];
                let callHistoryTimeHtml = "";
                let callHistoryTimeHtmlOthers = "";
                console.log('callHistoryTime.length = ' + callHistoryTime.length);

                let callCount = 0;
                for (let j = 0; j < callHistoryTime.length; j++) {
                    if(j==0){
                        callHistoryTimeHtml += "<li>"+callHistoryTime[j]+"</li>";
                    }else{
                        callHistoryTimeHtmlOthers += "<li>"+callHistoryTime[j]+"</li>";
                    }
                    callCount++;
                }
                let callCountHtml = "";
                let historyOneHtml = "";
                if(callCount>1){
                    callCountHtml += " ("+callCount+")";
                    historyOneHtml = "history_one";
                }else{
                    historyOneHtml = "history_one none";
                }
                if(contact.phoneNumbers != null && contact.displayName != null){
                    let favoHtml = "";
                    let liEl = "";

                    if(listFavo.indexOf($.trim(contact.id)) >=0 ) {
                        //즐겨찾기 된애
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo'></a>"
                    }else{
                        //즐겨찾기 안된애
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo_no'></a>"
                    }

                    let callHistoryTimeFirst = getYear(callHistoryTime[0]);
                    console.log("callHistoryTimeFirst"+ callHistoryTimeFirst);
                    console.log("imsitime"+ imsitime);
                    if(searchImsitime!=callHistoryTimeFirst) {
                        liEl += "<li class='year'>"+callHistoryTimeFirst+"</li>";

                        searchImsitime=callHistoryTimeFirst;
                        console.log("추가");
                    }

                    liEl += "<li data-id='"+ contact.id +"' data-contact='"+JSON.stringify(contact) +"'>";
                    liEl += "<span class='portrait'><img src='"+getThumbImage(contact.thumbnail)+"'></span>";
                    liEl += favoHtml;
                    liEl += "<h4 class='history_cell'>"+contact.displayName+callCountHtml+"</h4>";
                    liEl += "<p class='history_cell "+historyOneHtml+"'>"+callHistory[i]["type"]+" "+callHistory[i]["num"]+"</p><button type='button' class='btn_call'></button>";
                    liEl += "<ul class='history_call'>";
                    liEl += callHistoryTimeHtml;
                    liEl += "</ul>";
                    liEl += "<ul class='history_call others_history'>";
                    liEl += callHistoryTimeHtmlOthers;
                    liEl += "</ul>";
                    liEl += "</li>";

                    if(isIOS12()){
                        $(".list_sch_history").append(liEl);
                    }else{
                        data.push(liEl);
                    }
                }
            }
        }
        if(!isIOS12()){

            let offset = 31+61;
            //alert("Not ios12");
            if(!nullcheck(clusterizeHistorySearch)){
                clusterizeHistorySearch.destroy(true);
            }
            clusterizeHistorySearch = new Clusterize({
                rows_in_block: 50,
                blocks_in_cluster: 5,
                offset: offset,
                rows: data,
                scrollId: 'scrollAreaSearchHistory',
                contentId: 'contentAreaSearchHistory'
            });
        }
        searchImsitime="";
    }else{
        $(".list_sch_history").empty();
    }
}

function deleteHistory(id){
    //alert('deleteHistory ::'+id);
    console.log('deleteHistory ::'+id);
    let callHistory = window.localStorage.getArray("callHistory"); //빈배열
    console.log('deleteHistory000 ::'+JSON.stringify(callHistory));


    let newCallHistory = callHistory.filter(x => {
        return x.historyId != id;
      })

    console.log('deleteHistory ::'+JSON.stringify(newCallHistory));

    window.localStorage.setArray("callHistory",newCallHistory);

    setTimeout(() => {
        if(newCallHistory.length>0){
            $(".list_history").empty();
            printHistory();
        }else{
            $(".list_history").empty();
        }
    }, 100);

}

function addCallHistory(id, num, type) {
    console.log('addCallHistory ::' + id + "::" + num);

    let callHistory = window.localStorage.getArray("callHistory"); //빈배열

    let currentdate = new Date();
    let datetime = currentdate.getFullYear() + "년 " +
        (currentdate.getMonth() + 1) + "월 " +
        currentdate.getDate() + "일 " +
        (currentdate.getHours() < 10 ? '0' : '') + currentdate.getHours() + ":" +
        (currentdate.getMinutes() < 10 ? '0' : '') + currentdate.getMinutes() + ":" +
        (currentdate.getSeconds() < 10 ? '0' : '') + currentdate.getSeconds();

    let historyId = "" + currentdate.getFullYear() + (currentdate.getMonth() + 1) + currentdate.getDate() + currentdate.getHours() + currentdate.getMinutes() + currentdate.getSeconds();

    let callContact = {};
    callContact["historyId"] = $.trim(historyId);
    callContact["id"] = $.trim(id);
    callContact["num"] = $.trim(num);
    callContact["type"] = $.trim(type);
    callContact["time"] = [datetime];

    if ($.trim(id).startsWith("-1")) {
        searchContactByNumber = newContact.filter(({ phoneNumbers }) => {
            if (nullcheck(phoneNumbers)) {
                return;
            } else {
                return phoneNumbers.find(item => $.trim(num) === getRemovePlusEightTwo(item.normalizedNumber));
            }
        });

        // userMap의 구조를 newContact와 유사하게 변환
        let userMapArray = Object.values(user_map); // 수정: userMap을 배열로 변환
        let userMapContact = userMapArray.find(item => { // 수정: userMapArray에서 번호를 찾음
            if (!nullcheck(item.phoneNumbers)) {
                return item.phoneNumbers.some(phone => $.trim(num) === getRemovePlusEightTwo(phone.normalizedNumber));
            }
        });

        if (searchContactByNumber.length === 0 && userMapContact) { // 수정: userMap에서 번호를 찾았을 경우
            searchContactByNumber = [userMapContact];
        }

        if (searchContactByNumber.length > 0) {
            id = searchContactByNumber[0].id;

            console.log('searchContactByNumber id::' + id);
            let phoneNumber = searchContactByNumber[0].phoneNumbers[0];

            let type = phoneNumber.type;
            console.log('searchContactByNumber ::' + phoneNumber.normalizedNumber);
            console.log('searchContactByNumber ::' + searchContactByNumber[0].displayName);
            callContact["type"] = $.trim(type);

            callContact["id"] = $.trim(id);
        }
    }

    if (nullcheck(callHistory)) {
        callHistory = new Array(); //빈배열

        callHistory.unshift(callContact);
        console.log('addCallHistory1' + callHistory.length);
    } else {

        console.log('addCallHistory2 ::' + id + "::" + num);
        console.log('addCallHistory2' + callHistory.length);
        let firstCallHistory = callHistory[0];
        console.log('firstCallHistory = ' + firstCallHistory);

        let firstCallHistoryId = firstCallHistory["id"];
        let firstCallHistoryNum = firstCallHistory["num"];
        let firstCallHistoryYear = getYear(firstCallHistory["time"][0]);

        let firstCalHistoryTime = firstCallHistory["time"];

        callContactTimeDay = getYear(callContact["time"][0]);

        if (firstCallHistoryNum == $.trim(num) && firstCallHistoryYear == callContactTimeDay) {
            callContact["time"].push.apply(callContact["time"], firstCalHistoryTime);

            for (let i = 0; i < callContact["time"].length; i++) {
                //console.log('firstCalHistoryTime3 = ' + callContact["time"][i]);
            }

            callHistory[0] = callContact;
        } else {
            callHistory.unshift(callContact);
            if (callHistory.length >= 500) {
                callHistory.pop();
            }
        }
    }

    window.localStorage.setArray("callHistory", callHistory);

    if ($('.ui-page-active').attr('id') == "history") {
        setTimeout(() => {
            $(".list_history").empty();
            printHistory();
        }, 5000);
    }
    
}