import { defaultEvent } from './default.js';
$(() => {
    //取得會議編號
    axios.get('./api/minutes/latest').then((response) => {
        const data = response.data;
        $('#minute-title-label').text(`標題（第${data.number}次）`);
    });
    attachSubmitEvent();
    defaultEvent();
});

//右上彈出
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);
    },
});

//提交與檔案上傳
const attachSubmitEvent = () => {
    //container of content & attach
    let contentFile;
    let attachFiles = [];

    //提交
    $(document).on('submit', '#form-create', function () {
        if ($('#upload-area-content').children().length == 0) {
            swal.fire({ title: '會議檔案缺失', text: '請上傳會議內容', icon: 'error' });
            return;
        }
        //讀入formData
        let formData = new FormData(this);
        //將檔案讀入formData，並刪除input file欄位
        formData.delete('content');
        formData.delete('attach');
        formData.append('content', contentFile);
        attachFiles.map((file) => {
            formData.append('attach', file);
        });

        //data format
        formData.set('title', formData.get('title').replace(/\s/g, ''));
        formData.set('title', formData.get('title').replaceAll('(', '\uff08'));
        formData.set('title', formData.get('title').replaceAll(')', '\uff09'));

        swal.fire({
            title: '正在上傳會議資料...',
            text: formData.get('title'),
            didOpen: () => {
                swal.showLoading();
                axios
                    .post('./api/minutes', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                        },
                    })
                    .then((response) => {
                        swal.close();
                        swal.fire({
                            title: '提交成功',
                            text: formData.get('title'),
                            icon: 'success',
                            timer: 4000,
                            timerProgressBar: true,
                            confirmButtonColor: '#24a0ed',
                        }).then(() => {
                            window.location.href = './';
                        });
                    })
                    .catch((err) => {
                        swal.fire({ title: '新增發生未知錯誤，請重新操作', icon: 'error' }).then(() => {
                            location.reload();
                        });
                    });
            },
        });
    });

    //內容
    $(document).on('change', '#file-content', function () {
        const fileEle = $(this)[0];
        let liTag = `
            <li class="row">
            <i class="fas fa-file-alt"></i> 
            <div class="file-content">
                <label class="upload-content">${fileEle.files[0].name}</label>
            </div>
            <i class="fas fa-trash-alt del"></i>
            </li>`;
        $('#upload-area-content').html(liTag);
        //overwrite content file
        contentFile = fileEle.files[0];
        Toast.fire({
            icon: 'success',
            title: '上傳成功',
            text: fileEle.files[0].name,
        });
    });

    //附件
    $(document).on('change', '#file-attach', function () {
        //append each file
        const fileArr = this.files;
        let fileNames = '';
        $.each(fileArr, (index, file) => {
            let liTag = `
            <li class="row">
            <i class="fas fa-file-alt"></i>
            <div class="file-content">
                <label class="upload-attach">${file.name}</label>
            </div>
            <i class="fas fa-trash-alt del"></i>
            </li>`;
            $('#upload-area-attach').append(liTag);
            //push attach file
            attachFiles.push(file);
            fileNames += file.name + '<br><br>';
        });

        Toast.fire({
            icon: 'success',
            title: '上傳成功',
            html: fileNames,
        });
    });

    //刪除
    $(document).on('click', '.del', function () {
        //取得當前刪除的label Node
        const label = $(this).siblings('.file-content').find('label');
        const fileType = label.prop('class').split('-').pop();
        //取得檔案名稱
        const fileName = label.text();

        swal.fire({
            title: '確定刪除檔案?',
            text: fileName,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '刪除',
            confirmButtonColor: '#EA5455',
            cancelButtonText: '取消',
        }).then((result) => {
            if (result.isConfirmed) {
                if (fileType == 'content') {
                    contentFile = null;
                }
                if (fileType == 'attach') {
                    attachFiles = attachFiles.filter((file) => {
                        return file.name !== fileName;
                    });
                }
                $(this).parent().remove();

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

                Toast.fire({
                    icon: 'error',
                    title: '刪除成功',
                    html: fileName,
                });
            }
        });
    });
};
