//初始化值
let value = {
    currentPage: '1',
    order: 'DESC',
    searchQueries: '',
};
//windows onload
$(() => {
    getMinutes(value);
    attachEvent();
});

const Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000,
    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 searchString = searchResultString(minute.MEETING_TEXT);
        // 格式化日期: 依照使用者所在地的時區轉為當地日期
        let date = new Date(minute.MEETING_DATE).toLocaleDateString().split('/');
        // 格式化日期: 西元=>民國
        date[0] = date[0] - 1911;
        let dateTime = date.join('/') + ' ' + minute.MEETING_TIME;

        tableTag += `<tr> 
        <td class="minutes-index minutes-text"> ${minute.MEETING_NUMBER} </td>
        <td class="minutes-title minutes-text" id="minutes-${minute.MEETING_ID}">
        ${minute.MEETING_TITLE} <br> <em>${minute.MEETING_TAGS}</em>
        <p class="search-result">
            ${searchString}
        </p>
        </td>
        <td class="minutes-text">
        ${minute.MEETING_CHARPERSON}
        </td>
        <td class="minutes-text">
        ${minute.MEETING_MINUTE}
        </td>
        <td class="minutes-text">
        ${dateTime}
        
        </td>`;
        tableTag += `<td class="minutes-btns ">
                     <i class="fas fa-edit" id="minute-modify${minute.MEETING_ID}"></i>
                     <i class="fas fa-trash" id="minute-delete${minute.MEETING_ID}"></i>                
                     <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>  
                     </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).clone().children().remove().end().text();

        swal.fire({
            title: '正在開啟PDF....',
            text: minuteTitle,
            timer: 2000,
            timerProgressBar: true,
            showConfirmButton: false,
            willClose: () => {
                window.open(`./api/files/${minuteID}`);
                location.reload();
            },
        });
    });
    //點擊刪除
    $(document).on('click', 'i[id^="minute-delete"]', function () {
        const minuteTitle = $(this).parents('td').siblings('.minutes-title').text();
        swal.fire({
            title: '確定刪除會議記錄?',
            text: minuteTitle,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '刪除',
            confirmButtonColor: '#EA5455',
            cancelButtonText: '取消',
        }).then((result) => {
            if (result.isConfirmed) {
                let minuteid = $(this).attr('id');
                minuteid = minuteid.replace('minute-delete', '');
                axios
                    .delete(`./api/minutes/${minuteid}`)
                    .then((response) => {
                        const { message } = response.data;
                        console.log(response.data);
                        Toast.fire({
                            icon: 'error',
                            title: message,
                            text: minuteTitle,
                            timer: 2000,
                            timerProgressBar: true,
                        }).then(() => {
                            location.reload();
                        });
                    })
                    .catch((err) => {
                        swal.fire({
                            title: '刪除時發生錯誤',
                            icon: 'error',
                        }).then(() => {
                            location.reload();
                        });
                    });
            }
        });
    });
    //下載所有檔案
    $(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) => {
                        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();
                    })
                    .catch((err) => {
                        swal.fire({
                            title: '下載發生錯誤',
                            icon: 'error',
                        }).then(() => {
                            location.reload();
                        });
                    });
            },
        });
    });
    //下載單個檔案
    $(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('');
                })
                .catch((res) => {
                    swal.fire({
                        title: '下載發生錯誤',
                        icon: 'error',
                    }).then(() => {
                        location.reload();
                    });
                });
        }
    });
    //查詢submit
    $(document).on('submit', '#form-search', function () {
        //將form轉成json
        const formData = new FormData(this);
        value.searchQueries = JSON.stringify(Object.fromEntries(formData));
        value.currentPage = '1';
        Toast.fire({
            icon: 'info',
            html: `
            <h2>查詢結果</h2><br><br>
            <h3>主席</h3> ${formData.get('charperson')}<br><br>
            <h3>紀錄</h3> ${formData.get('minute')}<br><br>
            <h3>關鍵字</h3> ${formData.get('keyWord')}<br><br>
            <h3>時間</h3> ${formData.get('startTime')}~${formData.get('endTime')}`,
        });
        getMinutes(value);
    });
    //點擊排序按鈕
    $(document).on('click', '#order-bar', function () {
        if ($(this).prop('checked')) {
            value.order = 'ASC';
            getMinutes(value);
        } else {
            value.order = 'DESC';
            getMinutes(value);
        }
    });
};

const getMinutes = async (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');
            }
        })
        .catch((err) => {
            swal.fire({
                title: '取得會議資料發生錯誤，請稍後再試',
                icon: 'error',
            }).then(() => {
                location.replace('./');
            });
        });
};
