// 节流
function throttle(fn, time) {
    let canRun = true;
    return function () {
        if (!canRun) {
            return;
        }
        canRun = false;
        const rst = fn.apply(this, arguments);
        // 事件返回错误，说明没有发起请求，允许直接继续触发事件，不进行节流处理
        if (rst === false) {
            canRun = true;
            return;
        }
        setTimeout(() => canRun = true, time);
    }
}

const periodReg = /\d{4}-((0[1-9])|(1[0-2]))$/;
function createLib() {
    const name = $('#name').val();
    if (!name) {
        $('#name-error').show();
        return false;
    }
    const period = $('#period').val();
    if (!period || !periodReg.test(period)) {
        $('#period-error').show();
        return false;
    }
    $('#add-lib-form').submit();
}

let curLib = {};

//设置当前库
function setCurLib(libID) {
    curLib.id = libID;
    curLib.name = $(`#${libID}`).text();
}

// 点击编辑按钮
function handleEditClick(libID) {
    setCurLib(libID);
    $('#edit').modal('show');
}

// 点击确认编辑
function handleEditConfirm() {
    const rename = $('#rename-text').val();
    if (!rename) {
        $('#rename-error').show();
        return false;
    }
    $('#edit').modal('hide');
    ajaxPost('/priceInfo/renameLib', { libID: curLib.id, name: rename })
        .then(() => $(`#${curLib.id} a`).text(rename));
}

// 删除需要连需点击三次才可删除
let curDelCount = 0;
// 点击删除按钮
function handleDeleteClick(libID) {
    setCurLib(libID);
    curDelCount = 0;
    $('#del').modal('show');
}

// 删除确认
function handleDeleteConfirm() {
    curDelCount++;
    if (curDelCount === 3) {
        $.bootstrapLoading.start();
        curDelCount = -10; // 由于需要连续点击，因此没有对此事件进行节流，为防止多次请求，一旦连续点击到三次，马上清空次数。
        $('#del').modal('hide');
        ajaxPost('/priceInfo/deleteLib', { libID: curLib.id })
            .then(() => $(`#${curLib.id}`).parent().remove())
            .finally(() => $.bootstrapLoading.end());
    }
}

// 点击导入按钮
function handleImportClick(libID) {
    setCurLib(libID);
    $('#import').modal('show');
}

// 导入确认
function handleImportConfirm() {
    $.bootstrapLoading.start();
    const self = $(this);
    try {
        const formData = new FormData();
        const file = $("input[name='import_data']")[0];
        if (file.files.length <= 0) {
            throw '请选择文件!';
        }
        formData.append('file', file.files[0]);
        formData.append('libID', curLib.id);
        $.ajax({
            url: '/priceInfo/importExcel',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function () {
                self.attr('disabled', 'disabled');
                self.text('上传中...');
            },
            success: function (response) {
                self.removeAttr('disabled');
                self.text('确定导入');
                if (response.err === 0) {
                    $.bootstrapLoading.end();
                    const message = response.msg !== undefined ? response.msg : '';
                    if (message !== '') {
                        alert(message);
                    }
                    // 成功则关闭窗体
                    $('#import').modal("hide");
                } else {
                    $.bootstrapLoading.end();
                    const message = response.msg !== undefined ? response.msg : '上传失败!';
                    alert(message);
                }
            },
            error: function () {
                $.bootstrapLoading.end();
                alert("与服务器通信发生错误");
                self.removeAttr('disabled');
                self.text('确定导入');
            }
        });
    } catch (error) {
        alert(error);
        $.bootstrapLoading.end();
    }
}

const { ProcessStatus, CRAWL_LOG_KEY } = window.PRICE_INFO_CONST;

const CHECKING_TIME = 5000;
// 检测爬取、导入是否完成
function processChecking(key, cb) {
    checking();

    function checking() {
        ajaxPost('/priceInfo/processChecking', { key })
            .then(handleResolve)
            .catch(handleReject)
    }

    let timer;
    function handleResolve({ key, status, errorMsg }) {
        if (status === ProcessStatus.START) {
            if (!$('#progressModal').is(':visible')) {
                const title = key === CRAWL_LOG_KEY ? '爬取数据' : '导入数据';
                const text = key === CRAWL_LOG_KEY ? '正在爬取数据，请稍候……' : '正在导入数据，请稍候……';
                $.bootstrapLoading.progressStart(title, true);
                $("#progress_modal_body").text(text);
            }
            timer = setTimeout(checking, CHECKING_TIME);
        } else if (status === ProcessStatus.FINISH) {
            if (timer) {
                clearTimeout(timer);
            }
            $.bootstrapLoading.progressEnd();
            if (cb) {
                cb();
            }
        } else {
            if (timer) {
                clearTimeout(timer);
            }
            if (errorMsg) {
                alert(errorMsg);
            }
            if (cb) {
                cb();
            }
            $.bootstrapLoading.progressEnd();
        }
    }
    function handleReject(err) {
        if (timer) {
            clearInterval(timer);
        }
        alert(err);
        $.bootstrapLoading.progressEnd();
    }
}

const matched = window.location.search.match(/filter=(.+)/);
const compilationID = matched && matched[1] || '';
// 爬取数据确认
function handleCrawlConfirm() {
    const from = $('#period-start').val();
    const to = $('#period-end').val();
    if (!periodReg.test(from) || !periodReg.test(to)) {
        $('#crawl-error').show();
        return false;
    }
    $('#crawl').modal('hide');
    ajaxPost('/priceInfo/crawlData', { from, to, compilationID }, 0) // 没有timeout
        .then(() => {
            processChecking(CRAWL_LOG_KEY, () => window.location.reload());
        })
}
/* function handleCrawlConfirm() {
    const from = $('#period-start').val();
    const to = $('#period-end').val();
    if (!periodReg.test(from) || !periodReg.test(to)) {
        $('#crawl-error').show();
        return false;
    }
    $('#crawl').modal('hide');
    $.bootstrapLoading.progressStart('爬取数据', true);
    $("#progress_modal_body").text('正在爬取数据，请稍候……');
    // 不用定时器的话，可能finally处理完后，进度条界面才显示，导致进度条界面没有被隐藏
    const time = setInterval(() => {
        if ($('#progressModal').is(':visible')) {
            clearInterval(time);
            ajaxPost('/priceInfo/crawlData', { from, to, compilationID }, 0) // 没有timeout
                .then(() => {
                    window.location.reload();
                })
                .finally(() => $.bootstrapLoading.progressEnd());
        }
    }, 500);
} */

const throttleTime = 1000;
$(document).ready(function () {
    processChecking();

    // 锁定、解锁
    $('.lock').click(function () {
        lockUtil.handleLockClick($(this));
    });
    // 新增
    $('#add-lib').click(throttle(createLib, throttleTime));
    // 重命名
    $('#rename').click(throttle(handleEditConfirm, throttleTime));
    // 删除
    $('#delete').click(handleDeleteConfirm);
    // 爬取数据
    $('#crawl-confirm').click(throttle(handleCrawlConfirm, throttleTime));
    // 导入excel
    $('#import-confirm').click(throttle(handleImportConfirm, throttleTime));

    $('#add').on('hidden.bs.modal', () => {
        $('#name-error').hide();
        $('#period-error').hide();
    });
    $('#edit').on('hidden.bs.modal', () => $('#rename-error').hide());
    $('#crawl').on('hidden.bs.modal', () => $('#crawl-error').hide());
});

$.ajax({
    url: 'http://api.zjtcn.com/user/dyn_code',
    type: 'post',
    data: { service_id: '2020090003' },
    contentType: 'application/x-www-form-urlencoded',
})