const matched = window.location.search.match(/filter=(.+)/);
const compilationID = matched && matched[1] || '';
// 节流
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]))$/;
const quaterReg = /\d{4}年-[一二三四]{1}季度$/;
function createLib() {
const name = $('#name').val();
if (!name) {
$('#name-error').show();
return false;
}
const period = $('#period').val();
if (!period || (!periodReg.test(period) && !quaterReg.test(period))) {
$('#period-error').show();
return false;
}
$('#add-lib-form').submit();
}
let curLib = {};
//设置当前库
function setCurLib(libID) {
curLib.id = libID;
curLib.name = $(`#${libID}`).text();
curLib.compilationID = $(`#${libID}`).data('compilationid');
}
// 点击编辑按钮
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());
}
}
// 获取地区
let curAreas = [];
let curAreaMap = {};
const getAreas = async () => {
const areas = await ajaxPost('/priceInfo/getAreas', { compilationID: curLib.compilationID });
return areas;
}
// 获取地区下拉选项映射,key为父地区、value为子地区
const getAreaMap = async () => {
curAreas = await getAreas();
const areaMap = {};
curAreas.forEach(item => {
const { name } = item;
if (name) {
let [parent, sub] = name.split('-');
if (!sub) {
sub = parent;
}
if (!areaMap[parent]) {
areaMap[parent] = [sub];
} else {
areaMap[parent].push(sub);
}
}
});
return areaMap;
}
// 根据地区选项获取地区ID
const getAreaIDByOption = ($parent, $sub) => {
const parentArea = $parent.val();
const subArea = $sub.val();
const areaItem = curAreas.find(item => [parentArea, `${parentArea}-${subArea}`].includes(item.name));
console.log(areaItem);
return areaItem?.ID;
}
// 设置地区下拉项
const setAreaOption = ($parent, $sub, areaMap) => {
$parent.unbind();
const parentAreas = Object.keys(areaMap);
$parent.empty();
const parentOptionsHtml = parentAreas.map(parentArea => ``).join('');
$parent.append(parentOptionsHtml);
const setSubs = (subsArea) => {
$sub.empty();
const subOptionsHtml = subsArea.map(subArea => ``).join('');
$sub.append(subOptionsHtml);
}
setSubs(areaMap[parentAreas[0]] || []);
$parent.change(() => {
const curParent = $parent.val();
setSubs(areaMap[curParent] || []);
getAreaIDByOption();
});
}
let importType = 'originalData';
const importTitleMap = {
originalData: '原始数据',
mainSub: '主从数据',
keys: '关键字数据',
};
// 点击导入按钮
async function handleImportClick(libID, type) {
try {
setCurLib(libID);
importType = type;
$('#import-title').text(`导入${importTitleMap[type] || '数据'}`);
if (['mainSub', 'keys'].includes(importType)) {
$('#import-area').show();
const areaMap = await getAreaMap();
setAreaOption($('#import-parent-area'), $('#import-sub-area'), areaMap);
} else {
$('#import-area').hide();
}
$('#import').modal('show');
} catch (error) {
alert(error.message);
}
}
// 导入确认
function handleImportConfirm() {
$.bootstrapLoading.start();
const self = $(this);
try {
const areaID = getAreaIDByOption($('#import-parent-area'), $('#import-sub-area'));
if (!areaID) {
throw '请选择地区!';
}
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);
formData.append('areaID', areaID);
formData.append('importType', importType);
$.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();
}
}
// 点击导出按钮
async function handleExportClick(libID) {
try {
setCurLib(libID);
$('#export').modal('show');
const areaMap = await getAreaMap();
setAreaOption($('#export-parent-area'), $('#export-sub-area'), areaMap);
} catch (error) {
alert(error.message);
}
}
// 导出确认
function handleExportConfirm() {
const areaID = getAreaIDByOption($('#export-parent-area'), $('#export-sub-area'));
if (!areaID) {
alert('请选择地区!');
return;
}
$('#export').modal('hide');
window.location.href = `/priceInfo/export?libID=${curLib.id}&areaID=${areaID}`;
}
// 导出信息价库数据
function handleExportInfoPriceByLib(libID) {
setCurLib(libID);
window.location.href = `/priceInfo/exportInfoPriceByLib?libID=${libID}`;
}
// 导出编办信息价数据
function handleExportInfoPriceByCompilation() {
if (!compilationID) {
alert('请选择编办!');
return;
}
window.location.href = `/priceInfo/exportInfoPriceByCompilation?compilationID=${compilationID}`;
}
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();
}
}
// 爬取数据确认
function handleCrawlConfirm() {
const from = $('#period-start').val();
const to = $('#period-end').val();
if (!(periodReg.test(from) && periodReg.test(to)) && !(quaterReg.test(from) && quaterReg.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
$('#export-confirm').click(throttle(handleExportConfirm, 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());
$('#export-compilation-price').click(() => {
handleExportInfoPriceByCompilation();
})
});