import { defaultEvent } from './default.js';

let minuteID = 0;
let fileList = [];

$(() => {
    attachModifyEvent();
    attachSubmitEvent();
    attachFiletEvent();
    defaultEvent();
});

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);
    },
});

const attachModifyEvent = () => {
    let oldMinuteData = {};
    //點擊叉叉
    $(document).on('click', '.close', function () {
        const form = $(this).parent();
        //取得當前表單資料
        const currentData = new FormData(form[0]);
        //判斷是否有修改
        let isChange = false;
        //將表單資料與原資料進行比對
        Comparison: for (let [key, value] of Object.entries(oldMinuteData)) {
            //判斷檔案是否更動
            if (fileList.length !== 0) {
                isChange = true;
                break Comparison;
            }
            key = key.split('_').pop().toLowerCase();
            if (['date', 'time', 'venue', 'charperson', 'participant', 'minute', 'tags'].indexOf(key) > -1) {
                //格式化日期以進行比對
                value = key == 'date' ? dateFormat(value) : value;
                //如果對比有相異則break
                if (value !== currentData.get(key)) {
                    isChange = true;
                    break Comparison;
                }
            }
        }

        if (isChange) {
            swal.fire({
                title: '想要保存這次的更改嗎',
                showDenyButton: true,
                showCancelButton: true,
                confirmButtonText: '儲存',
                confirmButtonColor: '#24a0ed',
                denyButtonText: `不要儲存`,
                cancelButtonText: '取消',
            }).then((result) => {
                if (result.isConfirmed) {
                    currentData.delete('content');
                    currentData.delete('attach');
                    if (notEmpty()) {
                        handleFormData(currentData);
                        $('#modal-bg-modify').removeClass('background-active');
                    } else {
                        swal.fire({
                            title: '欄位不可為空',
                            icon: 'warning',
                        });
                    }
                } else if (result.isDenied) {
                    swal.fire('修改未保存', '', 'info');
                    $('#modal-bg-modify').removeClass('background-active');
                }
            });
        } else {
            $('#modal-bg-modify').removeClass('background-active');
        }
    });

    //點擊修改按鈕
    $(document).on('click', 'i[id^="minute-modify"]', function () {
        minuteID = $(this).attr('id').replace('minute-modify', '');
        axios
            .get(`./api/minutes/${minuteID}`)
            .then((response) => {
                const { minuteData } = response.data;
                oldMinuteData = minuteData;
                fillInputData(oldMinuteData);
                $('#modal-bg-modify').addClass('background-active');
            })
            .catch((err) => {
                swal.fire({
                    title: '您所試圖查看的紀錄已經移除',
                    icon: 'error',
                }).then(() => {
                    location.reload();
                });
            });
    });
};

//資料自動填入input
const fillInputData = async (minute) => {
    //欄位填入會議資料
    $('#file-content').val('');
    $('#file-attach').val('');
    $('#input-title').val(minute.MEETING_TITLE);
    $('#input-charperson').val(minute.MEETING_CHARPERSON);
    $('#input-minute').val(minute.MEETING_MINUTE);
    $('#input-venue').val(minute.MEETING_VENUE);
    $('#input-participant').val(minute.MEETING_PARTICIPANT);
    $('#input-tag').val(minute.MEETING_TAGS);
    const date = dateFormat(minute.MEETING_DATE);

    $('#input-date').val(date);
    $('#input-time').val(minute.MEETING_TIME);

    //填入檔案資料
    $('#upload-area-content').empty();
    $('#upload-area-attach').empty();
    let contentTag = '';
    contentTag = `
        <li class="row">
        <i class="fas fa-file-alt"></i>
        <div class="file-content">
            <label class="upload-content-${minute.MEETING_TITLE}">${minute.MEETING_DOC_NAME}</label>
        </div>
        <i class="fas fa-trash-alt del"></i>
        </li>`;
    $('#upload-area-content').append(contentTag);

    minute.MEETING_ATTACH_NAME.split(',').forEach((attach) => {
        if (attach) {
            let attachTag = `
            <li class="row">
            <i class="fas fa-file-alt"></i>
            <div class="file-content">
            <label class="upload-content-${minute.MEETING_TITLE}">${attach}</label>
            </div>
            <i class="fas fa-trash-alt del"></i>
            </li>`;
            $('#upload-area-attach').append(attachTag);
        }
    });
};

//預設值事件
const attachFiletEvent = () => {
    //檔案刪除
    $(document).on('click', '.del', function () {
        //取得會議內容的檔案數量
        const contentFileLength = $('#upload-area-content').children().length;
        //取得檔案類型
        const fileType = $(this).parents('[id^=upload-area]').prop('id').replace('upload-area-', '');

        //判斷會議內容是否唯一
        if (contentFileLength == 1 && fileType == 'content') {
            swal.fire({
                title: '會議記錄為必要檔案，無法刪除',
                icon: 'warning',
            });
            return;
        } else {
            //取得當前刪除的label Node
            const label = $(this).siblings('.file-content').find('label');
            //取得檔案名稱
            const fileName = label.text();
            swal.fire({
                title: '確定刪除檔案?',
                text: fileName,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#EA5455',
                confirmButtonText: '刪除',
                cancelButtonText: '取消',
            }).then((result) => {
                if (result.isConfirmed) {
                    //刪除的是否為此次上傳檔案
                    const removeIndex = fileList.findIndex((file) => file.name == fileName && file.action == 'upload');
                    if (removeIndex > -1) fileList.splice(removeIndex, 1);
                    else fileList.push({ action: 'delete', type: fileType, name: fileName });
                    $(this).parent().remove();
                    Toast.fire({
                        icon: 'error',
                        title: '已刪除檔案',
                        text: fileName,
                        timer: 2000,
                        timerProgressBar: true,
                    });
                }
            });
        }
    });

    //上傳會議內容
    $(document).on('change', '#file-content', function () {
        //取得會議標題
        const minuteTitle = $(this).parents('section').siblings('.meeting-title').find('#input-title').val();
        const file = $(this)[0].files[0];
        let liTag = `
            <li class="row">
            <i class="fas fa-file-alt"></i>
            <div class="file-content">
                <label class="upload-content-${minuteTitle}">${file.name}</label>
            </div>
            <i class="fas fa-trash-alt del"></i>
            </li>`;

        const contentFiles = $('#upload-area-content').children('li');
        let isExist = false;
        for (let key in contentFiles) {
            if (contentFiles[key].innerText == file.name) {
                isExist = true;
                break;
            }
        }
        if (isExist) {
            swal.fire({
                title: '上傳相同名稱的檔案，是否覆蓋當前檔案',
                text: file.name,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '覆蓋',
                cancelButtonText: '取消',
            }).then((result) => {
                if (result.isConfirmed) {
                    //查詢是否fileList是否有已上傳紀錄
                    const removeIndex = fileList.findIndex(
                        (e) => e.name == file.name && e.action == 'upload' && e.type == 'attach'
                    );
                    if (removeIndex > -1) fileList.splice(removeIndex, 1);
                    fileList.push({
                        action: 'upload',
                        type: 'content',
                        file: file,
                        name: file.name,
                    });
                    Toast.fire({
                        icon: 'success',
                        title: '上傳成功',
                        text: file.name,
                        timer: 2000,
                        timerProgressBar: true,
                    });
                }
            });
        } else {
            $('#upload-area-content').append(liTag);
            fileList.push({
                action: 'upload',
                type: 'content',
                file: file,
                name: file.name,
            });
            Toast.fire({
                icon: 'success',
                title: '上傳成功',
                text: file.name,
                timer: 2000,
                timerProgressBar: true,
            });
        }
    });

    //上傳會議附件
    $(document).on('change', '#file-attach', function () {
        //取得會議標題
        const minuteTitle = $(this).parents('section').siblings('.meeting-title').find('#input-title').val();
        const file = $(this)[0].files[0];
        let liTag = `
            <li class="row">
            <i class="fas fa-file-alt"></i>
            <div class="file-content">
                <label class="upload-content-${minuteTitle}">${file.name}</label>
            </div>
            <i class="fas fa-trash-alt del"></i>
            </li>`;

        const attachFiles = $('#upload-area-attach').children('li');
        let isExist = false;
        for (let key in attachFiles) {
            if (attachFiles[key].innerText == file.name) {
                isExist = true;
                break;
            }
        }
        if (isExist) {
            swal.fire({
                title: '上傳相同名稱的檔案，是否覆蓋當前檔案',
                icon: 'warning',
                text: file.name,
                showCancelButton: true,
                confirmButtonText: '覆蓋',
                cancelButtonText: '取消',
            }).then((result) => {
                if (result.isConfirmed) {
                    //查詢是否fileList是否有已上傳紀錄
                    const removeIndex = fileList.findIndex(
                        (e) => e.name == file.name && e.action == 'upload' && e.type == 'attach'
                    );
                    if (removeIndex > -1) fileList.splice(removeIndex, 1);
                    fileList.push({ action: 'upload', type: 'attach', file: file, name: file.name });
                    Toast.fire({
                        icon: 'success',
                        title: '上傳成功',
                        text: file.name,
                        timer: 2000,
                        timerProgressBar: true,
                    });
                }
            });
        } else {
            $('#upload-area-attach').append(liTag);
            fileList.push({ action: 'upload', type: 'attach', file: file, name: file.name });
            Toast.fire({
                icon: 'success',
                title: '上傳成功',
                text: file.name,
                timer: 2000,
                timerProgressBar: true,
            });
        }
    });
};

const attachSubmitEvent = () => {
    //預覽畫面
    $(document).on('click', '#modifyBtn', function () {
        //取得目前的表單
        let formData = new FormData($(this).parents('form')[0]);
        formData.delete('content');
        formData.delete('attach');
        handleFormData(formData);
    });
};

//格式化日期
const dateFormat = (date) => {
    date = new Date(date);
    const yyyy = date.toLocaleDateString().slice(0, 4);
    const mm = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1);
    const dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
    return `${yyyy}-${mm}-${dd}`;
};

const handleFormData = (formData) => {
    //確認會議內容檔案唯一
    if ($('#upload-area-content').children().length == 1 && notEmpty()) {
        const doc_name = $('#upload-area-content').children()[0].innerText;
        formData.append('doc_name', doc_name);

        const attachFiles = $('#upload-area-attach').children();
        let attach_name = [];
        if (attachFiles.length !== 0) {
            $.each(attachFiles, function (key, attach) {
                attach_name.push(attach.innerText);
            });
            formData.append('attach_name', attach_name);
        }

        swal.fire({
            title: '正在處理上傳...',
            text: formData.get('title'),
            didOpen: () => {
                swal.showLoading();
                handleFileList(formData);
                axios
                    .put(`./api/minutes/${minuteID}`, formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                        },
                    })
                    .then((response) => {
                        swal.close();
                        swal.fire({
                            title: '修改成功',
                            text: formData.get('title'),
                            icon: 'success',
                        }).then(() => {
                            location.reload();
                        });
                    });
            },
        });
    } else if ($('#upload-area-content').children().length == 0) {
        swal.fire({
            title: '會議內容為必要檔案，請新增檔案',
            icon: 'warning',
        });
    } else if (!notEmpty()) {
        swal.fire({
            title: '欄位不可為空',
            icon: 'warning',
        });
    } else {
        swal.fire({
            title: '會議內容為單一檔案，請刪除其他檔案',
            icon: 'warning',
        });
    }
};

//處理檔案刪除或修改
const handleFileList = (formData) => {
    fileList.forEach((file, index, array) => {
        file.type == 'content' && file.action == 'upload'
            ? formData.append('content', file.file)
            : formData.append('attach', file.file);
        if (file.action == 'delete') {
            try {
                axios.delete('./api/files', { data: { folderName: formData.get('title'), fileName: file.name } });
            } catch (err) {
                console.log(err);
            }
        }
    });
};

//判斷輸入是否有為空
const notEmpty = () => {
    const charperson = $('#input-charperson').val();
    const minute = $('#input-minute').val();
    const venue = $('#input-venue').val();
    const participant = $('#input-participant').val();
    const date = $('#input-date').val();
    const time = $('#input-time').val();
    return charperson && minute && venue && participant && date && time;
};
