/**
* 打印pdf
*
* @param ele
*/
function printPdf(ele){
var e = $(ele),
src = e.data('src');
if (!src){
return;
}
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src=src;
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
iframe.contentWindow.print();
});
} else {
iframe.onload = function(){
iframe.contentWindow.print();
};
}
e.append(iframe);
}
/*
*
require(['/assets/js/common/exportButton.js']);
*
<a href="javascript:;" class="btn btn-warning"
title="{:__('Export')}" id="exportFileByAjax">
<i class="fa fa-download"></i> {:__('Export')}
</a>
*
* <!--导出|导出成功进度条-->
<div id="progressBar" style="display: none;">
<div class="btn btn-success progressRate" style="margin: 1.5rem 1.5rem 0 1.5rem; font-size: 1.5rem;">
数据导出进行中.... 0 / 0
</div>
</div>
<div id="errProgressBar" style="display: none;">
<div class="btn btn-warning progressRate" style="margin: 1.5rem 1.5rem 0 1.5rem; font-size: 1.5rem;">
错误数据导出进行中.... 0 / 0
</div>
</div>*
*
*
*
*
* */
require(
['jquery', 'js-xlsx', 'file-saver'],
function ($) {
var onOnce = 1;
var tempExport = 1;
/**
* 导出订单数据 --- 同步Ajax
*/
$('#exportFileByAjax').on('click', function () {
let url = location['request-path'] + location.search;
/**
* 获取总数
* @returns {Promise<unknown>}
*/
// const getTotal = () => {
// return new Promise((resolve, reject) => {
// $.ajax({
// url: `${url}&get_total=1`,
// method: 'GET',
// dataType: 'Json',
// success: res => {
// resolve(1 === res.code ? res.data.total : 0);
// },
// error: err => {
// reject(err);
// }
// });
// });
// };
/**
* 计算并显示百分比
* @param percentage
* @param show
*/
const changePercentage = (percentage, show = true) => {
let progressBar = $('#progressBar');
if (show) {
percentage = (percentage * 100).toFixed(2);
progressBar.find('.progressRate').text(`数据导出进行中.... ${percentage}`);
// progressBar.find('.progressbarPercentage').css('width', `${percentage}%`).text(`${percentage}%`);
progressBar.show(); // 显示进度条
} else {
progressBar.hide(); // 隐藏进度条
progressBar.find('.progressRate').text('0 / 0');
// progressBar.find('.progressbarPercentage').css('width', '0%').text('0%');
}
};
{
// table = table.clone();
var queryParams = {};
// 计算分页请求
let pageSize = $('.page-size').html(), // 每页数量
totalPage = $('.page-last>a').html(), // 总页数(总请求数)
completeCount = 0, // 成功的数量
promiseList = [], // promise对象集合
progressBar = $('#progressBar');
if (onOnce) {
onOnce = 0;
var table = $('#table');
table.on('pre-body.bs.table', function (){
totalPage = table.data('bootstrap.table').totalPages;
pageSize = table.data('bootstrap.table').pageTo;
if (tempExport) {
tempExport = 0;
doExport()
}
});
table.on('common-search.bs.table', function (event, table, params, query) {
//这里可以对params值进行修改,从而影响搜索条件
queryParams.filter = encodeURI(JSON.stringify(params.filter));
queryParams.op = encodeURI(JSON.stringify(params.op));
pageSize = table.pageTo;
totalPage = table.totalPages;
// debugger;
return false;
});
}
// 拿到请求参数
function refresh(){
$(".commonsearch-table form").submit()
}
tempExport = 1;
refresh()
// table.bootstrapTable('refresh');
// listTotal = 999999;
// if (listTotal < 1) {
// layer.msg('暂无可导出的数据,请筛选其他导出条件', {anim: 2, time: 1500});
// return;
// }
function doExport(){
if (totalPage < 1) {
layer.msg('暂无可导出的数据,请筛选其他导出条件', {anim: 2, time: 1500});
return;
}
progressBar.show(); // 显示进度条
// 批量请求
for (let i = 1; i <= totalPage; i++) {
let promiseItem = new Promise((resolve, reject) => {
$.ajax({
url: `${url}&page=${i}&exportButton=1&limit=${pageSize}`,
method: 'GET',
data: queryParams,
dataType: 'Json',
success: res => {
let data = [];
data = res.data || res.rows;
if ((1 === res.code || res.total > 0) && data.length > 0) {
completeCount += data.length;
changePercentage(i, true); // 显示百分比
}
res = null;
resolve(data);
},
error: err => {
reject(err);
}
});
});
promiseList.push(promiseItem);
}
let workBook = null,
workBookOut = null,
workSheet = null;
// 收集并合并数据,使用js-xlsx生成Excel
let excelDataTitle = [];
// $.ajax({
// url: `${url}&get_header=1`,
// method: 'GET',
// dataType: 'Json',
// async: false,
// success: res => {
// if (1 === res.code) {
// excelDataTitle = [res.data];
// }
// }
// });
Promise.all(promiseList).then(values => {
console.log(values);
if (completeCount < 1) {
Toastr.error('未能查询到可导出的数据');
return;
}
var append = [];
$.each(values, function (i, list){
$.each(list, function (i, item){
append.push(item);
});
});
table.bootstrapTable('removeAll');
table.bootstrapTable('append', append);
var tempOne = [];
var ignoreI = [];
table.find('thead > tr > th').each(function (i){
var text = $(this).text();
if (!text){
ignoreI.push(i);
}else{
tempOne.push(text)
}
});
excelDataTitle = [tempOne];
console.log(excelDataTitle);
values = [];
tempOne = [];
table.find('tbody > tr').each(function (){
var temp = [];
$(this).find('td').each(function (i){
if (ignoreI.indexOf(i) < 0) {
temp.push($(this).text())
}
});
tempOne.push(temp);
});
refresh();
console.log(tempOne);
values = [tempOne];
// 创建 excel表格对象
workBook = XLSX.utils.book_new();
workSheet = XLSX.utils.aoa_to_sheet(excelDataTitle, {raw: true}); // 设置原生格式
XLSX.utils.book_append_sheet(workBook, workSheet, 'sheet1');
// 写入表格数据
for (let i = 0; i < values.length; i++) {
if (values[i].length > 0) {
XLSX.utils.sheet_add_aoa(workSheet, values[i], {origin: -1, raw: true}); // 设置原生格式,不添加excel格式化
}
}
let workOptions = {bookType: 'xlsx', bookSST: false, type: 'array'}; // 定义选项
// let workBookOut = XLSX.writeFile(workBook, `data${Math.round(new Date() / 1000)}.xlsx`, workOptions); // 直接保存文件输出
workBookOut = XLSX.write(workBook, workOptions);
// 使用 Blob 的方式输出浏览器
saveAs(new Blob([workBookOut], {type: 'application/octet-stream'}), `导出-${new Date().Format('yyyyMMddHHmmssS')}.xlsx`);
}).catch(err => {
Toastr.error('网络繁忙,请稍后再试');
console.log(err);
}).finally(() => {
// 资源回收,释放内存
let timeoutMillisecond = 3800;
// if (listTotal > 12000 && listTotal <= 27000) {
// timeoutMillisecond = 2200;
// } else if (listTotal > 27000 && listTotal <= 35000) {
// timeoutMillisecond = 3000;
// } else if (listTotal > 35000) {
// timeoutMillisecond = 3800;
// }
let timeout = setTimeout(() => {
workBook = null;
workBookOut = null;
workSheet = null;
changePercentage(0, 0, false);
clearTimeout(timeout);
}, timeoutMillisecond);
});
}
}
});
});
getIframeByElement: function(element){
var iframe;
$("iframe").each(function(){
if(element.ownerDocument === this.contentWindow.document) {
iframe = this;
}
return !iframe;
});
return iframe;
},
/**
* 请求下载
*
* @param url
* @param downloadName
* @param postObj
*/
function request_down(url, downloadName, postObj){
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
//定义responseType='blob', 是读取文件成功的关键,这样设置可以解决下载文件乱码的问题
xhr.responseType = "blob";
xhr.setRequestHeader('X-Requested-With', 'xmlhttprequest')
xhr.setRequestHeader("Content-Type","application/json");//提交的数据为json格式
xhr.onload = () => {
// 创建一个URL对象并将返回的二进制数据传递给它
var downloadUrl = URL.createObjectURL(xhr.response);
// 创建一个a标签并设置其href属性为URL对象的值
var a = document.createElement('a');
a.href = downloadUrl;
// 设置a标签的download属性以及文本内容(可选)
a.download = downloadName;
a.textContent = downloadName;
// 将a标签添加到文档中,并模拟点击它以启动下载
document.body.appendChild(a);
a.click();
}
xhr.send(JSON.stringify(postObj));
}
function get_now_date () {
var date = new Date();
var sign2 = ":";
var year = date.getFullYear() // 年
var month = date.getMonth() + 1; // 月
var day = date.getDate(); // 日
var hour = date.getHours(); // 时
var minutes = date.getMinutes(); // 分
var seconds = date.getSeconds() //秒
// 给一位数的数据前面加 “0”
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (day >= 0 && day <= 9) {
day = "0" + day;
}
if (hour >= 0 && hour <= 9) {
hour = "0" + hour;
}
if (minutes >= 0 && minutes <= 9) {
minutes = "0" + minutes;
}
if (seconds >= 0 && seconds <= 9) {
seconds = "0" + seconds;
}
return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
}
export const select_options_yes_no = () => {
return [
{
value: 0,
label: '否'
},
{
value: 1,
label: '是'
},
];
}
export const handle_arr_key_to_string = (arr) => {
let result = {};
for (const arrKey in arr) {
result[arrKey + ''] = arr[arrKey];
}
return result;
}
export const download_url = function (url, filename = '') {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
if (filename) {
link.setAttribute('download', filename); // 设置下载文件名
}
document.body.appendChild(link); // 将链接添加到 DOM
link.click(); // 模拟点击
document.body.removeChild(link); // 下载后移除链接
}
/**
*
* @example await sleep_wait(1000);
* @param ms
*/
export const sleep_wait = async (ms: number) => {
return new Promise(resolve => setTimeout(resolve, ms)); // 等待 1 秒
}
/**
* 多个多语言
*
* @param arr
*/
export const intl_format_message_arr = (...arr) => {
const intl = useIntl();
return intl_format_message_arr_intl(intl, ...arr);
}
/**
* 多个多语言
*
* 类似ProFormDependency下使用
*
* @param arr
*/
export const intl_format_message_arr_intl = (intl, ...arr) => {
// const intl = useIntl();
let str = '';
let lang = getLocale();
// console.log('lang', lang)
// 有空格分割的语言
let langSpace = [
'es-ES',
];
let langSpaceBool = langSpace.includes(lang);
for (const val of arr) {
if (str.length > 0 && langSpaceBool) {
str += ' ';
}
str += intl.formatMessage({id: val});
}
return str;
}
window['trans_arr_fast'] = function (...nameArr){
// 这里假设 __ 是一个翻译函数,类似于 PHP 中的 __()
const str = nameArr.map(item => __(item));
// 假设 request().langset() 是获取当前语言环境的函数
const langset = Config.language; // 需要实现这个函数来获取当前语言
let joinStr = '';
if (['espanol', 'vietname'].includes(langset)) {
joinStr = ' ';
}
return str.join(joinStr);
}
/**
* 铺平json里的key
*
* @param data
* @param prefix
*/
export const handle_json_pave_key = (data, prefix = '')=>{
function isPlainObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
if (!data) {
return {};
}
prefix = prefix?(prefix + '__'):'';
let result = {};
for (const arrKey in data) {
if (isPlainObject(data[arrKey])) {
handle_json_pave_key(data[arrKey], prefix + arrKey)
}else{
result[prefix + arrKey] = data[arrKey];
}
}
return result;
}
/**
* 讲通过__铺平的数据,重新折叠
*
* @param data
*/
export const handle_json_pave_un_key = (data)=>{
let result = {};
for (const arrKey in data) {
data_set(result, arrKey, data[arrKey], '__')
}
return result;
}
async function getHash(input) {
const encoder = new TextEncoder();
let hashBuffer;
if (crypto.subtle) {
// 只有localhost和https
const data = encoder.encode(input);
hashBuffer = await crypto.subtle.digest('SHA-256', data);
}else {
// <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
return CryptoJS.SHA256(input).toString(CryptoJS.enc.Hex);
}
return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');
}
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function document_loaded(func){
document.addEventListener('DOMContentLoaded', func);
}
$(document).ready(function() {
// 添加 CSS 样式
$("head").append(`
<style>
*{
font-family: "Roboto", sans-serif;
}
.custom-alert {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
background-color: #f8d7da;
color: #721c24;
padding: 12px 20px;
border-radius: 5px;
border: 1px solid #f5c6cb;
display: none; /* 初始隐藏 */
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
z-index: 9999;
min-width: 280px;
font-size: 14px;
font-family: Arial, sans-serif;
align-items: center;
justify-content: space-between;
}
.custom-alert.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.custom-alert.warning {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeeba;
}
.custom-alert.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.custom-alert .close-btn {
background: none;
border: none;
font-size: 16px;
font-weight: bold;
cursor: pointer;
color: inherit;
margin-left: 15px;
}
</style>
`);
// 创建警告框 HTML 并添加到 body
$("body").append(`
<div id="customAlert" class="custom-alert">
<span class="alert-message">提示内容</span>
<button class="close-btn">×</button>
</div>
`);
// 关闭按钮
$(".close-btn").click(function() {
hideAlert();
});
// 显示警告框
window.showAlert = function(message, type = "error", duration = 3000) {
let $alert = $("#customAlert");
$alert.css({
display: "flex"
});
$alert.removeClass("success warning error").addClass(type); // 根据类型设置样式 (error, success, warning)
$alert.find(".alert-message").text(message); // 设置消息内容
$alert.fadeIn();
if (duration > 0) {
setTimeout(() => {
hideAlert();
}, duration);
}
};
// 隐藏警告框
window.hideAlert = function() {
$("#customAlert").fadeOut();
};
});
function setLocalData(name, data) {
let localData = null
let mergedObj = data
if (sessionStorage.getItem(name)) {
localData = JSON.parse(sessionStorage.getItem(name))
sessionStorage.removeItem(name)
mergedObj = Object.assign({}, localData, data);
}
sessionStorage.setItem(name, JSON.stringify(mergedObj))
}
function getLocalData(name, mergeObject = null, mergeObjectKey = null) {
let localData = null
if (sessionStorage.getItem(name)) {
localData = JSON.parse(sessionStorage.getItem(name))
// sessionStorage.removeItem(name)
if (mergeObject) {
if (mergeObjectKey) {
localData[mergeObjectKey] = Object.assign(localData[mergeObjectKey] || {}, mergeObject)
}else{
localData = Object.assign(localData, mergeObject);
}
}
}
return localData
}
/**
* 获取 URL 中的查询参数(支持哈希路由模式)
* @param {string} paramName - 可选,要获取的参数名。若未提供,则返回所有参数对象
* @param {string} url - 可选,要解析的 URL 字符串。默认为当前页面 URL
* @returns {string|Object} - 若提供 paramName,返回对应参数值;否则返回包含所有参数的对象
*/
function getUrlParams(paramName, url = window.location.href) {
// 处理哈希路由模式(如 https://example.com/#/page?param=value)
const queryString = url.includes('?')
? url.slice(url.indexOf('?') + 1).split('#')[0]
: '';
if (!queryString) {
return paramName ? undefined : {};
}
const params = {};
const pairs = queryString.split('&');
for (const pair of pairs) {
const [key, value] = pair.split('=').map(decodeURIComponent);
if (key) {
// 处理重复参数(如 ?a=1&a=2)为数组
if (params[key] !== undefined) {
params[key] = Array.isArray(params[key])
? [...params[key], value]
: [params[key], value];
} else {
params[key] = value;
}
}
}
return paramName ? params[paramName] : params;
}
var [run_by_many_success] = (function () {
let cache = {};
/**
* 多个地方都成功才会允许func
*
* @param func
* @param cacheKey
* @param key
* @param num
* @returns {(function(): void)|*}
*/
function run_by_many_success(func, cacheKey, key, num) {
if (!cache[cacheKey]) {
cache[cacheKey] = {};
}
return function () {
console.log({'run_by_many_success': '成功一个', cacheKey, key, num});
cache[cacheKey][key] = 1;
let i = 0;
for (const cacheElement in cache[cacheKey]) {
++i;
}
if (i >= num) {
console.log({'run_by_many_success': '运行', cacheKey, key, num});
func();
}
}
}
return [run_by_many_success];
})();