Files
web-Iot/src/lib/utils.ts
2026-05-15 16:28:42 +08:00

198 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import Cookies from 'js-cookie'
import type { MessageInstance } from 'antd/es/message/interface';
import type { ModalStaticFunctions } from 'antd/es/modal/confirm';
import type { NotificationInstance } from 'antd/es/notification/interface';
let message: MessageInstance;
let notification: NotificationInstance;
let modal: Omit<ModalStaticFunctions, 'warn'>;
export default {
get message() {
return message;
},
setMessage(instance: MessageInstance) {
message = instance;
},
get notification() {
return notification;
},
setNotification(instance: NotificationInstance) {
notification = instance;
},
get modal() {
return modal;
},
setModal(instance: Omit<ModalStaticFunctions, 'warn'>) {
modal = instance;
},
};
const TokenKey = 'Admin-Token'
const TokenKeyAi = 'ai-Token'
const UserId = 'userId'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function setTokenAi(token) {
return Cookies.set(TokenKeyAi, token, {
domain: "ai.satabot.com",
path: "/"
});
}
export const buildTreeFromFlat = (data) => {
const map = {};
const tree = [];
data.forEach(item => {
map[item.menuId] = { ...item, children: [] };
});
data.forEach(item => {
if (item.parentId === 0 || !item.parentId) {
tree.push(map[item.menuId]);
} else {
if (map[item.parentId]) {
map[item.parentId].children.push(map[item.menuId]);
}
}
});
return tree;
};
// 菜单数据转 Tree组件
export const buildPermTree = (treeData) => {
const loop = (list) => {
return list.map(item => {
const node = {
title: item.menuName,
key: item.menuId,
};
if (item.children && item.children.length) {
node.children = loop(item.children);
}
return node;
});
};
return loop(treeData);
};
export async function getWeatherData(options = {}) {
// 默认参数配置
const defaultPayload = {
city: "苏州",
adcode: "",
extended: false,
forecast: false,
hourly: false,
minutely: false,
indices: false,
lang: "zh"
};
// 合并用户传入参数与默认参数
const payload = { ...defaultPayload, ...options };
try {
// 动态导入 UapiClient SDK
// @ts-ignore
const { UapiClient } = await import('https://cdn.jsdelivr.net/npm/uapi-browser-sdk@latest/dist/index.js');
// 初始化客户端(注意:需替换为真实有效的 API_KEY)
const client = new UapiClient('https://uapis.cn', 'uapi-qy9ybtxlQ3Pp0JsHl7gXTAX45v0QpIeOoRbOnymq');
// 调用天气接口并返回数据
const weatherData = await client.misc.getMiscWeather(payload);
return weatherData;
} catch (error) {
console.error('[WeatherAPI] 获取天气数据失败:', error);
throw new Error(`天气接口调用失败:${error.message}`);
}
}
/**
* 根据天气文字返回组件用的 type
* 支持:晴 / 晴天 / 晴转多云
* 雨 / 小雨 / 中雨 / 大雨 / 雷阵雨
* 多云 / 阴
*/
export function getWeatherType(weatherText = "") {
if (!weatherText) return "cloudy"; // 兜底
const text = weatherText.trim();
// 晴天
if (text.includes("晴")) {
return "sunny";
}
// 雨天
if (
text.includes("雨") ||
text.includes("雷") ||
text.includes("暴雨")
) {
return "rainy";
}
// 多云 / 阴
if (text.includes("云") || text.includes("阴")) {
return "cloudy";
}
// 兜底
return "cloudy";
}
// ==============================================
// 通用导出表格为 CSV / Excel(通用版,不写死任何字段)
// ==============================================
export const exportTable = (columns, dataSource, fileName = "导出数据") => {
// 1. 从 columns 自动提取表头(过滤掉不显示的列)
const headers = columns
.filter(col => col.title && col.dataIndex) // 只取有标题+有字段的列
.map(col => col.title);
// 2. 自动提取数据(根据 dataIndex 取值)
const data = dataSource.map(item => {
return columns
.filter(col => col.title && col.dataIndex)
.map(col => {
let val = item[col.dataIndex];
// 处理 undefined / null
if (val === undefined || val === null) return "";
return String(val).replace(/"/g, '""'); // 转义CSV引号
});
});
// 3. 拼接CSV内容
const csvContent = [
headers.join(','),
...data.map(row => `"${row.join('","')}"`)
].join('\n');
// 4. 下载文件(解决中文乱码)
const blob = new Blob(["\ufeff" + csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${fileName}_${dayjs().format("YYYY-MM-DD")}.csv`;
a.click();
URL.revokeObjectURL(url);
};