//初始化值
let value = {
    currentPage: '1',
    order: 'DESC',
    searchQueries: '',
};

//windows onload
$(() => {
    $('body').css('background-color', '#ffffff');
    $('.modal-content').css('width', '80%');
    $('.modal-content').css('height', '90%');
    $('.modal-content').css('overflow', 'hidden');
    getMinutes(value);
    attachEvent();
});

const Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 5000,
    timerProgressBar: true,
    didOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer);
        toast.addEventListener('mouseleave', Swal.resumeTimer);
    },
});
//return關鍵字當前行
const searchResultString = (minuteText) => {
    let keyWordString = '';

    if (value.searchQueries !== '') {
        let { keyWord } = JSON.parse(value.searchQueries);
        if (keyWord !== '') {
            keyWord = keyWord.split(' ');
            keyWord.map((word) => {
                //中文 空白 ； : （ 。 、 ，
                let replace = `[\u4e00-\u9fa5\s\uff1b\uff1a\uff08\u3002\u3001\uff0c\r\n].{0,18}${word}.{0,18}[\u4e00-\u9fa5\s\uff1b\uff1a\uff09\u3002\u3001\uff0c\r\n]`;
                let re = new RegExp(replace, 'gim');
                let myArray;
                while ((myArray = re.exec(minuteText)) !== null) {
                    keyWordString += myArray[0].replace(/_x000D_|\r|\n/g, '');
                    keyWordString += '<br>';
                    // console.log(keyWordString);
                    // console.log('==============================================================');
                }
                keyWordString = keyWordString.replaceAll(word, `<strong class="mark-keyword">${word}</strong>`);
            });
        }
    }
    return keyWordString;
};

//return html tag
const setMinutesTag = (pageData) => {
    let tableTag = '';
    pageData.forEach((minute) => {
        // let dateTime = minute.MEETING_DATE + minute.MEETING_TIME;
        // dateTime = dateTime.replace(/T.*Z/, ' ');
        // 格式化日期: 依照使用者所在地的時區轉為當地日期
        let date = new Date(minute.MEETING_DATE).toLocaleDateString().split('/');
        date[0] = date[0] - 1911;// 格式化日期: 西元=>民國
        let dateTime = date.join('/') + ' ' + minute.MEETING_TIME;
        let searchString = searchResultString(minute.MEETING_TEXT);

        tableTag += `<tr style="border-bottom:1px #444444 solid"> 
                    <td class="minutes-title" id="minutes-${minute.MEETING_ID}" width='50%'>
                        <font face="標楷體"' size="3">${minute.MEETING_TITLE}</font>
                        <p class="search-result">
                            ${searchString}
                        </p>
                    </td>
                    `;
        tableTag += `<td style='text-align: center;'><i class="fas fa-cloud-download-alt" id="minute-download${minute.MEETING_TITLE}"></i>
                        <select class="select-download" id="minute-downloadList${minute.MEETING_TITLE}">
                     <option/>     
                     </select>
                     </td> 
                     <td width='20%'>
                        <font size="3" >${dateTime}</font>
                     </td> 
                     </tr>`;
    });
    return tableTag;
};

//觸發事件
const attachEvent = () => {
    //點擊頁碼
    $(document).on('click', 'li[id^="page"]', function () {
        value.currentPage = this.id.replace('page', '');
        getMinutes(value);
    });
    //點擊標題讀取PDF
    $(document).on('click', '.minutes-title', function () {
        const minuteID = $(this).attr('id').replace('minutes-', '');
        const minuteTitle = this.innerText;
        swal.fire({
            title: '正在開啟PDF....',
            text: minuteTitle,
            timer: 2000,
            timerProgressBar: true,
            showConfirmButton: false,
            willClose: () => {
                window.open(`./api/files/${minuteID}`);
            },
        });
    });
    //下載所有檔案
    $(document).on('click', 'i[id^="minute-download"]', function () {
        //取得會議標題用來尋找檔案
        const minuteTitle = $(this).attr('id').replace('minute-download', '');
        swal.fire({
            title: '正在處理檔案...',
            text: minuteTitle,
            showCloseButton: true,
            didOpen: () => {
                swal.showLoading();
                axios(`./api/files/zip`, {
                    method: 'GET',
                    params: { folder: minuteTitle },
                    responseType: 'blob',
                }).then((response) => {
                    if (response.data.type == 'application/zip') {
                        const url = window.URL.createObjectURL(new Blob([response.data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', `${minuteTitle}.zip`); //or any other extension
                        document.body.appendChild(link);
                        link.click();
                        swal.close();
                    } else {
                        swal.fire({
                            title: '下載發生錯誤',
                            icon: 'error',
                        });
                    }
                });
            },
        });
    });
    //下載單個檔案
    $(document).on('change', 'select', function () {
        const folderName = $(this).attr('id').replace('minute-downloadList', '');
        const fileName = this.value;
        if (fileName !== '') {
            $('body').css('cursor', 'wait');
            Toast.fire({
                icon: 'info',
                title: '開始下載...',
                text: fileName,
            });
            axios(`./api/files/`, {
                method: 'GET',
                params: { folder: folderName, file: fileName },
                responseType: 'blob',
            }).then((response) => {
                $('body').css('cursor', 'default');
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', fileName);
                document.body.appendChild(link);
                link.click();
                $(this).val('');
            });
        }
    });
    //查詢submit
    $(document).on('submit', '#form-search', function () {
        //將form轉成json
        value.searchQueries = JSON.stringify(Object.fromEntries(new FormData(this)));
        value.currentPage = '1';
        getMinutes(value);
    });
    //點擊排序按鈕
    $(document).on('click', '#order-bar', function () {
        if ($(this).prop('checked')) {
            value.order = 'ASC';
            getMinutes(value);
        } else {
            value.order = 'DESC';
            getMinutes(value);
        }
    });
};

//send ajax request for get data
const getMinutes = (value) => {
    axios
        .get('./api/minutes', {
            params: {
                currentPage: value.currentPage,
                limit: 5,
                order: value.order,
                searchQueries: value.searchQueries,
            },
        })
        .then((response) => {
            const data = response.data;
            const pageTag = createPagination(data.totalPages, parseInt(data.currentPage));
            const tableTag = setMinutesTag(data.pageData);
            //寫入會議資料
            $('#tbody-minutes').html(tableTag);
            //寫入頁碼資料
            $('#pagination-minutes').html(pageTag);
            //寫入會議檔案
            data.files.map((fileObj) => {
                fileObj.files.map((file) => {
                    $(`#minute-downloadList${fileObj.folder}`).append(`<option value="${file}">${file}</option>`);
                });
            });
            //關閉modal
            if ($('.modal-background').hasClass('background-active')) {
                $('.modal-background').removeClass('background-active');
            }
        });
};
