import { saveAs } from "file-saver";
import ExcelJS from "exceljs";

// 用于将图片转换为 Base64 编码
function getBase64Image(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous'; // 允许跨域获取
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png');
resolve(dataURL);
};
img.onerror = (error) => reject(error);
img.src = url;
});
}

export const serviceOrderList = (tableData, downloadUrl) => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Order Details');

// 设置列标题
worksheet.columns = [
{ header: '订单序号', key: 'index', width: 10 },
{ header: '订单编号', key: 'orderNumber', width: 30 },
{ header: '下单时间', key: 'createTime', width: 20 },
{ header: '用户名', key: 'userName', width: 15 },
{ header: '所购买的商品', key: 'goodName', width: 30 },
{ header: '商品图片', key: 'goodImg', width: 20 },
{ header: '商品类别', key: 'type', width: 20 },
{ header: '商品单价', key: 'price', width: 15 },
{ header: '数量', key: 'quantity', width: 10 },
{ header: '总价', key: 'itemTotalAmount', width: 15 },
{ header: '预约日期', key: 'reservationDate', width: 15 },
{ header: '预约时间段', key: 'timeSlot', width: 15 },
{ header: '联系人姓名', key: 'contactName', width: 20 },
{ header: '联系人手机号', key: 'contactPhone', width: 20 },
{ header: '订单实付金额', key: 'totalAmount', width: 20 },
{ header: '订单状态', key: 'orderStatus', width: 20 },
];

// 遍历 tableData 并填充数据
tableData.forEach((order, index) => {
// 展平每个订单的数据
order.orderItemList.forEach(async (item) => {
// 订单每个商品的行
const row = worksheet.addRow({
index: index + 1,
orderNumber: order.orderNumber,
createTime: order.createTime,
userName: order.userName,
goodName: item.goodSnapshot.name,
goodImg: item.goodSnapshot.goodImg.split(';')[0], // 提取商品图片路径
type: item.goodSnapshot.type,
price: item.goodSnapshot.price,
quantity: item.quantity,
itemTotalAmount: item.itemTotalAmount,
reservationDate: item.reservationDate,
timeSlot: item.timeSlot,
contactName: order.contactsSnapshot.name,
contactPhone: order.contactsSnapshot.phone,
totalAmount: order.totalAmount,
orderStatus: order.orderStatus,
});

// 获取商品图片的 Base64 编码
try {
const imageUrl = 'https://www.carboner.cn:8888/api/file/downloadFile?objectKey=' + row.getCell('goodImg').value;
const base64Image = await getBase64Image(imageUrl);

// 将 Base64 图片添加到 Excel
const imageId = workbook.addImage({
base64: base64Image,
extension: 'png',
});

// 设置图片在 Excel 单元格中的显示
worksheet.getRow(row.number).getCell('goodImg').value = { type: 'image', imageId };
worksheet.getRow(row.number).getCell('goodImg').style = {
alignment: { vertical: 'middle', horizontal: 'center' },
};
} catch (error) {
console.error('图片转换失败', error);
}
});
});

// 自适应列宽
worksheet.columns.forEach((column) => {
let maxLength = 0;
column.eachCell({ includeEmpty: true }, (cell) => {
const cellValue = cell.value ? String(cell.value) : ''; // 确保空值也处理
maxLength = Math.max(maxLength, cellValue.length);
});

// 设置列宽，确保列宽适应最大值
column.width = maxLength + 2; // 留出额外的空间
});

// 导出为 Excel 文件
workbook.xlsx.writeBuffer().then((buffer) => {
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, '订单信息.xlsx');
});
};
