/**
* 打印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 obj
* @param path
* @param defaultValue
* @returns {undefined|*}
*/
export const data_get = function (obj, path, defaultValue = '') {
if (!obj) {
return obj;
}
const keys = path.split('.');
let value = obj;
for (const key of keys) {
value = value[key];
if (value === undefined || value === null) {
return defaultValue;
}
}
return value;
}
/**
* 请求下载
*
* @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 handle_select_key_value = (arr) => {
let result = [];
for (const arrKey in arr) {
result.push({
label: arr[arrKey],
value: arrKey + "",
// value: parseInt(arrKey),
})
}
// result[1].checked = true;
// result[1].selected = true;
return result;
};
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);
}
export const data_set = function (obj, path, value, delimiter = '.') {
// 将路径按点分割成数组
const keys = path.split(delimiter);
// 获取最后一个键
const lastKey = keys.pop();
// 遍历路径,逐层创建对象
keys.reduce((acc, key) => {
// 如果当前键不存在,初始化为空对象
if (!acc[key]) {
acc[key] = {};
}
return acc[key];
}, obj)[lastKey] = value; // 设置值
return obj; // 返回修改后的对象
}
/**
* 铺平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;
}