|
|
const _ = require('lodash');
|
|
|
|
|
|
/**
|
|
|
* 处理用于筛选的 URL , 拼接 URL 参数
|
|
|
* @param originParam 当前 URL 中的参数
|
|
|
* @param newParam 要拼接的 参数
|
|
|
* @returns {string}
|
|
|
*/
|
|
|
const handleFilterUrl = (originParam, newParam, delParam) => {
|
|
|
let dest = '?';
|
|
|
let tempOriginParam = {};
|
|
|
|
|
|
delParam = delParam || {};
|
|
|
|
|
|
tempOriginParam = Object.assign(tempOriginParam, originParam, newParam);
|
|
|
delete tempOriginParam.uid;
|
|
|
|
|
|
_.forEach(tempOriginParam, info => {
|
|
|
if (!delParam[info.key] && info.value) {
|
|
|
// NOTE: 这里会对 query 进行编码,因为 query 有可以能是中文
|
|
|
if (info.key === 'query') {
|
|
|
info.value = encodeURIComponent(info.value);
|
|
|
}
|
|
|
dest += `${info.key}=${info.value}&`;
|
|
|
}
|
|
|
});
|
|
|
|
|
|
return _.trim(dest, '&');
|
|
|
};
|
|
|
|
|
|
module.exports = (total, params = {}, baseUrl = '') => {
|
|
|
const curPage = _.parseInt(params.page || 1);
|
|
|
const pageSize = _.parseInt(params.limit) || 10;
|
|
|
const totalPage = _.ceil(total / pageSize);
|
|
|
const tip = {
|
|
|
start: (curPage - 1) * pageSize + 1,
|
|
|
end: curPage * pageSize > total ? total : curPage * pageSize,
|
|
|
total
|
|
|
};
|
|
|
let prePage, nextPage;
|
|
|
const pageUrl = handleFilterUrl(baseUrl, params, {page: '${page}'});
|
|
|
|
|
|
if (curPage > 1) {
|
|
|
prePage = {
|
|
|
url: pageUrl.replace('${page}', curPage - 1)
|
|
|
};
|
|
|
}
|
|
|
if (curPage < totalPage) {
|
|
|
nextPage = {
|
|
|
url: pageUrl.replace('${page}', curPage + 1)
|
|
|
};
|
|
|
}
|
|
|
let pages = [];
|
|
|
let pagesNums = totalPage > 5 ? 5 : totalPage;
|
|
|
let offsetPage = curPage + _.round(0 - pagesNums / 2); // 遍历页码左侧数字
|
|
|
|
|
|
if (offsetPage <= 0) {
|
|
|
offsetPage = 1;
|
|
|
} else if (offsetPage + pagesNums > totalPage) {
|
|
|
offsetPage = totalPage - pagesNums + 1;
|
|
|
}
|
|
|
const preLimit = offsetPage - 1; // 页码1和遍历页码左侧的距离
|
|
|
const nextLimit = totalPage - (offsetPage - 1 + pagesNums); // 总页码和遍历页码右侧的距离
|
|
|
|
|
|
if (preLimit === 1) { // 如果左侧间距为1则显示这个页码
|
|
|
pagesNums++;
|
|
|
offsetPage--;
|
|
|
}
|
|
|
if (nextLimit === 1) { // 如果右侧间距为1则显示这个页码
|
|
|
pagesNums++;
|
|
|
}
|
|
|
|
|
|
if (preLimit >= 2) {
|
|
|
pages = _.concat(pages, {
|
|
|
num: 1,
|
|
|
url: pageUrl.replace('${page}', 1),
|
|
|
}, {
|
|
|
num: '...'
|
|
|
});
|
|
|
}
|
|
|
if (offsetPage <= 0) {
|
|
|
offsetPage = 1;
|
|
|
} else if (offsetPage + pagesNums > totalPage) {
|
|
|
offsetPage = totalPage - pagesNums + 1;
|
|
|
}
|
|
|
|
|
|
for (let i = 0; i < pagesNums; i++) {
|
|
|
pages.push({
|
|
|
num: offsetPage,
|
|
|
url: pageUrl.replace('${page}', offsetPage),
|
|
|
cur: curPage === offsetPage
|
|
|
});
|
|
|
offsetPage++;
|
|
|
}
|
|
|
if (nextLimit >= 2) {
|
|
|
pages = _.concat(pages, {
|
|
|
num: '...'
|
|
|
}, {
|
|
|
num: totalPage,
|
|
|
url: pageUrl.replace('${page}', totalPage),
|
|
|
});
|
|
|
}
|
|
|
return {tip, prePage, nextPage, pages};
|
|
|
}; |
...
|
...
|
|