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 attachSearchEvent = () => {
    //slider config
    $('#date-slider').slider({
        range: true,
        min: new Date('2002-12-01').getTime() / 1000,
        max: new Date().getTime() / 1000,
        step: 86400,
        values: [new Date('2002-12-01').getTime() / 1000, new Date().getTime() / 1000],
        slide: function (event, ui) {
            let startTime = dateFormat(new Date(ui.values[0] * 1000).toDateString());
            let endTime = dateFormat(new Date(ui.values[1] * 1000).toDateString());
            $('#time-start').val(startTime);
            $('#time-end').val(endTime);
        },
    });

    //點擊搜尋按鈕跳出搜尋視窗
    $(document).on('click', '#searchBtn', function () {
        $('#modal-bg-search').addClass('background-active');
        $('#time-start').val(dateFormat('2002-12-01'));
        $('#time-end').val(dateFormat(new Date()));
    });

    //點擊叉叉
    $(document).on('click', '.close', function () {
        $('#modal-bg-search').removeClass('background-active');
    });

    //日期變動slider value更動
    $(document).on('change', 'input[id^="time-"]', function () {
        const timeValue = new Date($(this).val()).getTime() / 1000;
        if ($(this).attr('id') == 'time-start') {
            const endTime = $('#date-slider').slider('values')[1];
            $('#date-slider').slider('values', [timeValue, endTime]);
        } else {
            const startTime = $('#date-slider').slider('values')[0];
            $('#date-slider').slider('values', [startTime, timeValue]);
        }
    });
};

$(() => {
    attachSearchEvent();
});
