$(() => {
    getUser()
    domEvent()
})
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 dateFormat = date => {
    let today = new Date(date)
    let dd = today.getDate()
    let mm = today.getMonth() + 1

    let yyyy = today.getFullYear()
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    today = yyyy + '-' + mm + '-' + dd
    return today
}

const makeUsersTag = pageData => {
    let tableTag = ''
    pageData.forEach(user => {
        //判斷是否為管理者
        let admin = '使用者'
        if (user.USER_ADMIN == 1) {
            admin = '管理者'
        }
        //格式化日期
        let registerDateTime = dateFormat(user.USER_REGISTERATIONTIME)
        tableTag += `<tr>
                    <td>
                    ${user.USER_NAME}
                    </td>
                    <td>
                    ${user.USER_USERNAME}
                    </td>
                    <td>
                    ${admin}
                    </td>
                    <td>
                    ${registerDateTime}
                    </td>
                    <td class="minutes-btns">
                    <i class="fas fa-pen" id="user-edit${user.USER_ID}"></i>
                    ${user.USER_ADMIN ? '' : `<i class="fas fa-trash" id="user-delete${user.USER_ID}"></i>`}
                    </td>
                    </tr>`
    })
    return tableTag
}

const domEvent = () => {
    //翻頁
    $(document).on('click', 'li[id^="page"]', function () {
        //取得該頁碼
        let currentPage = this.id.replace('page', '')
        getUser(currentPage)
    })
    //刪除
    $(document).on('click', 'i[id^="user-delete"]', function () {
        const userName = $(this).parents('tr').children()[0].innerText
        swal.fire({
            title: '確定刪除該使用者?',
            icon: 'warning',
            text: userName,
            showCancelButton: true,
            confirmButtonText: '刪除',
            confirmButtonColor: '#EA5455',
            cancelButtonText: '取消',
        }).then(result => {
            if (result.isConfirmed) {
                let userid = $(this).attr('id').replace('user-delete', '')
                try {
                    axios.delete(`./api/users/${userid}`)
                    Toast.fire({
                        icon: 'error',
                        title: '刪除成功',
                        text: userName,
                        timer: 2000,
                        timerProgressBar: true,
                    }).then(() => {
                        location.reload()
                    })
                } catch (err) {
                    swal.fire({
                        title: '刪除時發生錯誤',
                        icon: 'error',
                    }).then(() => {
                        location.reload()
                    })
                }
            }
        })
    })
    //編輯
    $(document).on('click', 'i[id^="user-edit"]', function () {
        let userid = $(this).attr('id').replace('user-edit', '')
        swal.fire({
            title: '輸入新密碼',
            input: 'password',
            inputAttributes: {
                autocapitalize: 'off',
                autocorrect: 'off',
            },
            showCancelButton: true,
            confirmButtonText: '確定',
            showLoaderOnConfirm: true,
            cancelButtonText: '取消',
            preConfirm: async password => {
                return await axios.patch(`./api/users/${userid}`, { password })
            },
        }).then(result => {
            if (result.isConfirmed) {
                try {
                    Toast.fire({
                        icon: 'success',
                        title: '修改成功',
                        timer: 2000,
                        timerProgressBar: true,
                    }).then(() => {
                        location.replace('./logout')
                    })
                } catch (err) {
                    swal.fire({
                        title: '修改時發生錯誤',
                        icon: 'error',
                    }).then(() => {
                        location.reload()
                    })
                }
            }
        })
    })
}

const getUser = async (currentPage = 1) => {
    axios
        .get('./api/users', { params: { currentPage, limit: 10 } })
        .then(response => {
            const { totalPages, pageData } = response.data
            const pageTag = createPagination(totalPages, parseInt(currentPage))
            const tableTag = makeUsersTag(pageData)
            $('#tbody-admin').html(tableTag)
            $('#pagination-admin').html(pageTag)
        })
        .catch(err => {
            swal.fire({
                title: '取得使用者發生錯誤，請稍後再試',
                icon: 'error',
            }).then(() => {
                location.replace('./')
            })
        })
}
