import puppeteer from "puppeteer";
import fs from "fs-extra";
import path from "path";
import FormData from "form-data";
import axios from "axios"; // 导入 axios
import { colorSchemes } from "../colors.js";
import { text } from "stream/consumers";
export const getYawErrorBarSumCharts = async (
data,
bucketName,
objectName,
analysisTypeCode
) => {
try {
// 提取静态偏航误差值和机组数量
let a = [];
let b = [];
let c = [];
data.map((item) => {
if (item["[0,3]"] != "0.0") {
a.push(item["[0,3]"]);
}
if (item["(3,5]"] != "0.0") {
b.push(item["(3,5]"]);
}
if (item["(5, )"] != "0.0") {
c.push(item["(5, )"]);
}
});
const xData = ["(0,3]", "(3,5]", "(>5]"]; // 偏航误差区间
const yData = [a.length, b.length, c.length]; // 各区间的机组数量
// 每个柱子的颜色
const colors = [
"#8AC8BE", // (0, 3] 蓝色
"#407DB3", // (3, 5] 绿色
"#1B2973", // (5, ∞] 红色
];
const trace = {
x: xData, // 横坐标数据
y: yData, // 纵坐标数据
type: "bar", // 当前图表类型
marker: {
color: colors, // 为每个柱子分配不同的颜色
},
// hovertemplate:
// `偏航误差值:` + ` %{x}
` + `台数:` + "%{y}
",
};
const layout = {
title: {
text: "静态偏航误差的绝对值机组台数分布情况",
font: {
size: 16,
weight: "bold",
},
}, // 图表标题
xaxis: {
title: { text: "静态偏航误差值(度)" }, // 横坐标标题
gridcolor: "rgb(255,255,255)",
tickcolor: "rgb(255,255,255)",
backgroundcolor: "#e5ecf6",
},
yaxis: {
title: {
text: "台数",
}, // 纵坐标标题
gridcolor: "rgb(255,255,255)",
tickcolor: "rgb(255,255,255)",
backgroundcolor: "#e5ecf6",
},
margin: {
l: 50,
r: 50,
t: 50,
b: 50,
},
autosize: true, // 开启自适应
// showlegend: true, // 显示图例
plot_bgcolor: "#e5ecf6",
gridcolor: "#fff",
bgcolor: "#e5ecf6", // 设置背景颜色
};
// 创建临时目录
const tempDir = path.join(process.cwd(), "images");
await fs.ensureDir(tempDir);
const tempFilePath = path.join(
tempDir,
`temp_yaw_error_bar_sum_chart_${Date.now()}.jpeg`
);
// 获取 plotly.js 的绝对路径
const plotlyPath = path.join(
process.cwd(),
"src",
"public",
"js",
"plotly-3.0.1.min.js"
);
const plotlyContent = await fs.readFile(plotlyPath, "utf-8");
// 使用 Puppeteer 生成图表的截图
const browser = await puppeteer.launch({
headless: "new",
// 根据系统改路径
executablePath: `${process.env.CHROME_PATH}`, // 根据系统改路径
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
try {
const page = await browser.newPage();
const htmlContent = `
静态偏航误差值
`;
await page.setContent(htmlContent, { waitUntil: "networkidle0" });
await page.waitForFunction(() => window.chartRendered === true, {
timeout: 60000,
});
// 截图并保存到临时文件
const chartElement = await page.$("#chart");
await chartElement.screenshot({ path: tempFilePath, type: "jpeg" });
// 上传图片到服务器
const formData = new FormData();
formData.append("file", fs.createReadStream(tempFilePath));
const response = await axios.post(
`${process.env.API_BASE_URL}/examples/upload`,
{
filePath: tempFilePath,
bucketName,
objectName,
}
);
return response.data.url;
} catch (error) {
console.error("生成图表失败:", error);
} finally {
await browser.close();
}
} catch (error) {
console.error("发生错误:", error);
}
};