<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef"> </base-search>

        <div class="main-container">
            <el-table v-loading="dataListLoading" :data="data.rows" border element-loading-text="数据加载中...">
                <el-table-column label="运单号" prop="deliveryNumber"></el-table-column>
                <el-table-column label="核验状态" prop="statusDesc" width="100">
                    <template #default="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)">
                            {{ scope.row.statusDesc || getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="车牌号" prop="licensePlate"> </el-table-column>
                <el-table-column label="车身照片" prop="" width="160">
                    <template #default="scope">
                        <!-- 车头照片 -->
                        <el-image
                            v-if="scope.row.carFrontPhoto"
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="scope.row.carFrontPhoto"
                            fit="cover"
                            :preview-src-list="[scope.row.carFrontPhoto]"
                            preview-teleported
                        >
                            <template #error>
                                <div
                                    style="width: 50px; height: 50px; display: flex; justify-content: center; align-items: center"
                                    class="image-slot"
                                >
                                    <el-icon style="font-size: 50px"><Picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                        <div
                            v-else
                            style="width: 50px; height: 50px; margin-right: 10px; display: inline-flex; justify-content: center; align-items: center; background: #f5f7fa; border-radius: 4px; color: #909399"
                        >
                            <el-icon style="font-size: 30px"><Picture /></el-icon>
                        </div>
                        <!-- 车尾照片 -->
                        <el-image
                            v-if="scope.row.carBehindPhoto"
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="scope.row.carBehindPhoto"
                            fit="cover"
                            :preview-src-list="[scope.row.carBehindPhoto]"
                            preview-teleported
                        >
                            <template #error>
                                <div
                                    style="width: 50px; height: 50px; display: flex; justify-content: center; align-items: center"
                                    class="image-slot"
                                >
                                    <el-icon style="font-size: 50px"><Picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                        <div
                            v-else
                            style="width: 50px; height: 50px; margin-right: 10px; display: inline-flex; justify-content: center; align-items: center; background: #f5f7fa; border-radius: 4px; color: #909399"
                        >
                            <el-icon style="font-size: 30px"><Picture /></el-icon>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="起始地" prop="startLocation"> </el-table-column>
                <el-table-column label="送达目的地" prop="endLocation"> </el-table-column>
                <el-table-column label="预计送达时间" prop="estimatedDeliveryTime"> </el-table-column>
                <el-table-column label="登记设备数量" prop="registeredJbqCount" width="120">
                    <template #default="scope">
                        {{ getTotalDeviceCount(scope.row.id) }}
                    </template>
                </el-table-column>
                <el-table-column label="车内盘点耳标数量" prop="earTagCount" width="140">
                    <template #default="scope">
                        <span v-if="getEarTagCount(scope.row.id) == getTotalDeviceCount(scope.row.id)">
                            {{ getEarTagCount(scope.row.id) }}
                        </span>
                        <span style="color: red" v-else>
                            {{ getEarTagCount(scope.row.id) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="预警类型">
                    <template #default="scope">
                        <div v-for="(item, index) in scope.row.warningTypeList" :key="index">
                            <el-tag type="warning" v-if="item == '运输距离预警'" style="margin-top: 10px">运输距离预警</el-tag>
                            <el-tag type="danger" v-if="item == '数量盘点预警'" style="margin-top: 10px">数量盘点预警</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="司机姓名" prop="driverName"> </el-table-column>
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="创建人" prop="createByName"></el-table-column>
                <el-table-column label="操作" width="350">
                    <template #default="scope">
                        <div class="table_column_operation">
                            <el-button type="primary" link @click="details(scope.row, scope.row.warningTypeList ? scope.row.warningTypeList.length : 0)" v-hasPermi="['entry:view']">详情</el-button>
                            <el-button type="primary" link @click="viewDevices(scope.row)" v-hasPermi="['entry:device']">查看设备</el-button>
                            <el-button type="warning" link @click="editDelivery(scope.row)" v-hasPermi="['entry:edit']">编辑</el-button>
                            <el-button type="success" link @click="updateStatus(scope.row)" v-hasPermi="['entry:status']">修改状态</el-button>
                            <el-button type="info" link @click="downloadPackage(scope.row)" :loading="downLoading[scope.row.id]" v-hasPermi="['entry:download']">打包文件</el-button>
                            <el-button type="primary" link @click="downloadAcceptanceFormHandler(scope.row)" :loading="downLoading[scope.row.id]" v-hasPermi="['entry:export']">下载验收单</el-button>
                            <el-button type="danger" link @click="deleteDelivery(scope.row)" v-hasPermi="['entry:delete']">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="dataListOnEmpty">暂无数据</div>
                </template>
            </el-table>
            <Pagination 
                v-if="data.total > 0" 
                v-model:limit="form.pageSize" 
                v-model:page="form.pageNum" 
                :total="data.total" 
                @pagination="handlePagination" 
            />
        </div>
        
        <!-- 编辑对话框 -->
        <createDeliveryDialog ref="editDialogRef" @success="getDataList" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import baseSearch from '@/components/common/searchCustom/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import createDeliveryDialog from '@/views/shipping/createDeliveryDialog.vue';
import { inspectionList, downloadZip, pageDeviceList } from '@/api/abroad.js';
import { updateDeliveryStatus, deleteDeliveryLogic, downloadDeliveryPackage, getDeliveryDetail, downloadAcceptanceForm } from '@/api/shipping.js';

const router = useRouter();
const route = useRoute();
const baseSearchRef = ref();
const editDialogRef = ref();
const dataListLoading = ref(false);
const downLoading = reactive({});
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});
const data = reactive({
    rows: [],
    total: 10,
    deviceCounts: {}, // 存储每个订单的设备数量 {orderId: {host: 0, ear: 0, collar: 0, total: 0}}
});
const formItemList = reactive([
    {
        label: '运单号',
        type: 'input',
        param: 'deliveryNumber',
        labelWidth: 65,
        span: 7,
    },
    {
        label: '车牌号',
        type: 'input',
        param: 'licensePlate',
        labelWidth: 65,
        span: 7,
        placeholder: '请输入完整车牌号',
    },
    {
        label: '创建时间',
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        param: 'createTime',
        labelWidth: 80,
        span: 7,
        placeholder: '请选择创建日期',
    },
    {
        label: '核验状态',
        type: 'select',
        selectOptions: [
            { value: 1, text: '准备中' },
            { value: 2, text: '运输中' },
            { value: 3, text: '已结束' },
        ],
        param: 'status',
        span: 7,
    },
]);

// 获取指定订单的设备数量
const getDeviceCounts = async (deliveryId) => {
    try {

        // 获取所有设备类型的数据
        const [hostRes, earRes, collarRes] = await Promise.all([
            pageDeviceList({ pageNum: 1, pageSize: 100, deliveryId: parseInt(deliveryId), deviceType: 1 }),
            pageDeviceList({ pageNum: 1, pageSize: 100, deliveryId: parseInt(deliveryId), deviceType: 2 }),
            pageDeviceList({ pageNum: 1, pageSize: 100, deliveryId: parseInt(deliveryId), deviceType: 4 })
        ]);
        
        const hostCount = hostRes.code === 200 ? hostRes.data.length : 0;
        const earCount = earRes.code === 200 ? earRes.data.length : 0;
        const collarCount = collarRes.code === 200 ? collarRes.data.length : 0;
        const totalCount = hostCount + earCount + collarCount;
        

        // 存储设备数量
        data.deviceCounts[deliveryId] = {
            host: hostCount,
            ear: earCount,
            collar: collarCount,
            total: totalCount
        };
        
        return {
            host: hostCount,
            ear: earCount,
            collar: collarCount,
            total: totalCount
        };
    } catch (error) {
        console.error('获取设备数量失败:', error);
        return { host: 0, ear: 0, collar: 0, total: 0 };
    }
};

// 获取订单的设备总数
const getTotalDeviceCount = (deliveryId) => {
    const counts = data.deviceCounts[deliveryId];
    return counts ? counts.total : 0;
};

// 获取订单的耳标数量
const getEarTagCount = (deliveryId) => {
    const counts = data.deviceCounts[deliveryId];
    return counts ? counts.ear : 0;
};

const searchFrom = () => {
    form.pageNum = 1;
    getDataList();
};

// 处理分页事件
const handlePagination = (paginationData) => {
    console.log('[PAGINATION] 分页变化:', paginationData);
    if (paginationData) {
        form.pageNum = paginationData.page || form.pageNum;
        form.pageSize = paginationData.limit || form.pageSize;
        console.log('[PAGINATION] 更新后的分页参数 - pageNum:', form.pageNum, 'pageSize:', form.pageSize);
    }
    getDataList();
};

const getDataList = () => {
    dataListLoading.value = true;
    
    // 安全获取搜索参数
    let searchParams = {};
    if (baseSearchRef.value && baseSearchRef.value.penetrateParams) {
        searchParams = baseSearchRef.value.penetrateParams();
    }
    
    const params = {
        ...form,
        ...searchParams,
    };
    params.interfaceType = 2;
    
    // 处理精确的创建时间查询
    if (searchParams.createTime) {
        params.createTime = searchParams.createTime;

    }
    
    // 处理精确的车牌号查询
    if (searchParams.licensePlate) {
        params.licensePlate = searchParams.licensePlate.trim();

    }
    

    console.log('[INSPECTION-LIST] 请求参数:', params);
    inspectionList(params)
        .then(async (ret) => {
            console.log('[INSPECTION-LIST] 响应数据:', ret);
            
            // 处理响应数据结构
            // PageResultResponse 返回的结构是 { code, msg, data: { total, rows } }
            let responseData = ret.data || ret;
            
            // 如果 data 是对象且包含 total 和 rows，直接使用
            if (responseData && typeof responseData === 'object' && 'total' in responseData && 'rows' in responseData) {
                data.rows = responseData.rows || [];
                data.total = responseData.total || 0;
            } else if (responseData && responseData.data) {
                // 如果 data 是嵌套的，使用 data.data
                data.rows = responseData.data.rows || [];
                data.total = responseData.data.total || 0;
            } else {
                // 兜底处理
                data.rows = [];
                data.total = 0;
            }
            
            console.log('[INSPECTION-LIST] 解析后的数据 - 总数:', data.total, '当前页数据:', data.rows.length);
            dataListLoading.value = false;
            
            // 为每个订单获取设备数量
            if (data.rows && data.rows.length > 0) {
                for (const row of data.rows) {
                    if (row.id) {
                        await getDeviceCounts(row.id);
                    }
                }
            }
        })
        .catch((error) => {
            console.error('[INSPECTION-LIST] 请求失败:', error);
            dataListLoading.value = false;
            data.rows = [];
            data.total = 0;
        });
};
// 详情
const details = (row, length) => {
    router.push({
        path: '/entry/details',
        query: {
            id: row.id,
            status: row.status,
            length,
        },
    });
};
// 下载文件 - 生成HTML文档（可打印为PDF或Word）
const download = async (row) => {
    try {
        downLoading[row.id] = true;
        
        // 计算字段
        const landingWeight = parseFloat(row.landingEntruckWeight || 0);
        const emptyWeight = parseFloat(row.emptyWeight || 0);
        const totalWeight = ((landingWeight - emptyWeight) / 2).toFixed(2);
        const unitPrice = (parseFloat(row.firmPrice || 0) / 2).toFixed(2);
        const totalAmount = (parseFloat(totalWeight) * parseFloat(unitPrice)).toFixed(2);
        
        // 准备数据 - 使用回退机制
        const data = {
            supplierName: row.supplierName || row.supplierMobile || '',
            buyerName: row.buyerName || row.buyerMobile || '',
            startLocation: row.startLocation || '',
            createTime: row.createTime || '',
            endLocation: row.endLocation || '',
            driverName: row.driverName || '',
            driverMobile: row.driverMobile || '',
            licensePlate: row.licensePlate || '',
            ratedQuantity: row.ratedQuantity || '',
            totalWeight: totalWeight,
            unitPrice: unitPrice,
            totalAmount: totalAmount
        };
        

        // 生成HTML内容
        const htmlContent = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>牛只发车验收单</title>
    <style>
        @media print {
            body { margin: 0; }
            .no-print { display: none; }
        }
        body { 
            font-family: "Microsoft YaHei", "SimSun", Arial, sans-serif; 
            margin: 20px; 
            line-height: 1.4;
        }
        .header { 
            text-align: center; 
            font-size: 20px; 
            font-weight: bold; 
            margin-bottom: 30px;
            border-bottom: 2px solid #000;
            padding-bottom: 10px;
        }
        .order-number { 
            text-align: right; 
            margin-bottom: 20px; 
            font-size: 14px;
        }
        .info-grid { 
            width: 100%; 
            border-collapse: collapse; 
            margin-bottom: 20px; 
            font-size: 14px;
        }
        .info-grid td { 
            border: 1px solid #000; 
            padding: 10px; 
            vertical-align: top;
        }
        .info-grid .label { 
            background-color: #f5f5f5; 
            font-weight: bold; 
            width: 20%; 
            text-align: center;
        }
        .cattle-table { 
            width: 100%; 
            border-collapse: collapse; 
            margin-bottom: 20px; 
            font-size: 14px;
        }
        .cattle-table th, .cattle-table td { 
            border: 1px solid #000; 
            padding: 10px; 
            text-align: center; 
        }
        .cattle-table th { 
            background-color: #f5f5f5; 
            font-weight: bold; 
        }
        .signature-section { 
            width: 100%; 
            border-collapse: collapse; 
            margin-top: 20px; 
            font-size: 14px;
        }
        .signature-section td { 
            border: 1px solid #000; 
            padding: 10px; 
            vertical-align: top;
        }
        .signature-section .label { 
            background-color: #f5f5f5; 
            font-weight: bold; 
            width: 25%; 
            text-align: center;
        }
        .print-button {
            background-color: #409EFF;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 20px 0;
        }
        .print-button:hover {
            background-color: #66b1ff;
        }
    </style>
</head>
<body>
    <div class="header">牛只发车验收单</div>
    <div class="order-number">订单编号: </div>
    
    <table class="info-grid">
        <tr>
            <td class="label">供货单位</td>
            <td>${data.supplierName}</td>
            <td class="label">收货单位</td>
            <td>${data.buyerName}</td>
        </tr>
        <tr>
            <td class="label">发车地点</td>
            <td>${data.startLocation}</td>
            <td class="label">发车时间</td>
            <td>${data.createTime}</td>
        </tr>
        <tr>
            <td class="label">到达地点</td>
            <td>${data.endLocation}</td>
            <td class="label">动物检疫合格证明编号</td>
            <td></td>
        </tr>
        <tr>
            <td class="label">司机姓名及联系方式</td>
            <td>${data.driverName} ${data.driverMobile}</td>
            <td class="label">装车车牌号</td>
            <td>${data.licensePlate}</td>
        </tr>
    </table>
    
    <table class="cattle-table">
        <thead>
            <tr>
                <th>序号</th>
                <th>活牛品种</th>
                <th>单只体重范围 (斤)</th>
                <th>下车总数量 (头)</th>
                <th>下车总重量 (斤)</th>
                <th>单价 (元/斤)</th>
                <th>总金额 (元)</th>
                <th>备注</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td>${data.ratedQuantity}</td>
                <td>${data.totalWeight}</td>
                <td>${data.unitPrice}</td>
                <td>${data.totalAmount}</td>
                <td></td>
            </tr>
        </tbody>
    </table>
    
    <table class="signature-section">
        <tr>
            <td class="label">已支付货款时间</td>
            <td></td>
            <td class="label">已支付货款金额</td>
            <td></td>
        </tr>
        <tr>
            <td class="label">应支付尾款时间</td>
            <td></td>
            <td class="label">应支付尾款金额</td>
            <td></td>
        </tr>
        <tr>
            <td class="label">验收结论</td>
            <td></td>
            <td class="label">验收时间</td>
            <td></td>
        </tr>
        <tr>
            <td class="label">供货单位指定验收人签字及联系方式</td>
            <td></td>
            <td class="label">收货单位指定验收人签字及联系方式</td>
            <td></td>
        </tr>
        <tr>
            <td class="label">供货单位盖章</td>
            <td></td>
            <td class="label">收货单位盖章</td>
            <td></td>
        </tr>
    </table>
    
    <div class="no-print">
        <button class="print-button" onclick="window.print()">打印/保存为PDF</button>
        <p style="color: #666; font-size: 12px;">
            提示：点击"打印/保存为PDF"按钮可以将此文档打印或保存为PDF格式。
            在打印对话框中，您也可以选择"另存为PDF"来保存文档。
        </p>
    </div>
</body>
</html>`;
        
        // 在新窗口中打开HTML文档
        const newWindow = window.open('', '_blank');
        newWindow.document.write(htmlContent);
        newWindow.document.close();
        
        ElMessage.success('文档已生成，可以在新窗口中查看和打印');
        
    } catch (error) {
        console.error('生成文档失败:', error);
        ElMessage.error('生成文档失败，请重试');
    } finally {
        downLoading[row.id] = false;
    }
};

// 状态文本转换
const getStatusText = (status) => {
    const statusMap = {
        1: '准备中',
        2: '运输中',
        3: '已结束'
    };
    return statusMap[status] || '未知状态';
};

// 状态标签类型
const getStatusTagType = (status) => {
    const typeMap = {
        1: 'info',      // 准备中 - 蓝色
        2: 'warning',   // 运输中 - 橙色
        3: 'success'    // 已结束 - 绿色
    };
    return typeMap[status] || 'info';
};

// ==================== 新增功能方法 ====================

// 查看设备
const viewDevices = (row) => {
    router.push({
        path: '/entry/devices',
        query: {
            deliveryId: row.id,
            deliveryNumber: row.deliveryNumber
        }
    });
};

// 编辑运送清单
const editDelivery = async (row) => {
    try {

        // 检查编辑对话框组件是否已加载
        if (!editDialogRef.value || !editDialogRef.value.open) {
            ElMessage.warning('编辑功能暂不可用，请刷新页面重试');
            return;
        }
        
        // 调用 detail 接口获取完整数据（包含 supplierId, buyerId, 设备信息等）
        const detailRes = await getDeliveryDetail(row.id);

        if (detailRes.code === 200 && detailRes.data) {
            // 传入完整的 detail 数据给 open() 方法
            editDialogRef.value.open(detailRes.data);
        } else {
            ElMessage.error('获取运单详情失败：' + (detailRes.msg || '未知错误'));
        }
    } catch (error) {
        console.error('[EDIT-DELIVERY] 打开编辑对话框失败:', error);
        ElMessage.error('打开编辑对话框失败，请重试');
    }
};

// 修改状态
const updateStatus = (row) => {
    const statusOptions = [
        { value: 1, label: '准备中' },
        { value: 2, label: '运输中' },
        { value: 3, label: '已结束' }
    ];
    
    const currentStatus = statusOptions.find(opt => opt.value === row.status)?.label || '未知';
    
    ElMessageBox.confirm(
        `当前状态：${currentStatus}。请选择要修改的状态：\n1 - 准备中\n2 - 运输中\n3 - 已结束`,
        '修改状态',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            inputPattern: /^[1-3]$/,
            inputErrorMessage: '请输入 1-3 之间的数字',
            showInput: true,
            inputPlaceholder: '请输入新状态对应的数字（1/2/3）',
            inputValue: String(row.status)
        }
    ).then(async ({ value }) => {
        const newStatus = parseInt(value);
        if (newStatus && newStatus >= 1 && newStatus <= 3) {
            try {
                const res = await updateDeliveryStatus({
                    id: row.id,
                    status: newStatus
                });
                if (res.code === 200) {
                    ElMessage.success(`状态已修改为：${statusOptions.find(opt => opt.value === newStatus)?.label}`);
                    getDataList();
                } else {
                    ElMessage.error(res.msg || '状态修改失败');
                }
            } catch (error) {
                console.error('修改状态失败:', error);
                ElMessage.error('状态修改失败，请重试');
            }
        } else {
            ElMessage.error('无效的状态值');
        }
    }).catch(() => {
        ElMessage.info('已取消');
    });
};

// 删除运送清单（逻辑删除）
const deleteDelivery = (row) => {
    ElMessageBox.confirm(`确定要删除运单号为 ${row.deliveryNumber} 的运送清单吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteDeliveryLogic(row.id);
            if (res.code === 200) {
                ElMessage.success('删除成功');
                getDataList();
            } else {
                ElMessage.error(res.msg || '删除失败');
            }
        } catch (error) {
            console.error('删除运送清单失败:', error);
            ElMessage.error('删除失败，请重试');
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

// 打包文件
const downloadPackage = async (row) => {
    try {
        downLoading[row.id] = true;
        ElMessage.info('正在打包文件，请稍候...');
        
        // 调用后端API打包文件（包含图片、视频和信息）
        // 注意：由于响应拦截器设置了 responseType: 'blob'，返回的是 Blob 对象
        const res = await downloadDeliveryPackage(row.id);
        
        // 确保 res 是 Blob 对象，如果不是则转换为 Blob
        let blob;
        if (res instanceof Blob) {
            blob = res;
        } else {
            // 如果不是 Blob，尝试转换为 Blob
            blob = new Blob([res], { type: 'application/zip' });
        }
        
        // 检查响应是否是有效的ZIP文件（通过检查ZIP文件魔数）
        // ZIP 文件的魔数是：50 4B 03 04 (PK\x03\x04)
        const arrayBuffer = await blob.arrayBuffer();
        const uint8Array = new Uint8Array(arrayBuffer);
        
        // 检查是否是ZIP文件（前4个字节是 50 4B 03 04）
        const isZipFile = uint8Array.length >= 4 && 
            uint8Array[0] === 0x50 && 
            uint8Array[1] === 0x4B && 
            uint8Array[2] === 0x03 && 
            uint8Array[3] === 0x04;
        
        if (!isZipFile) {
            // 响应是错误信息（JSON或文本），尝试读取并显示错误
            try {
                const decoder = new TextDecoder('utf-8');
                const errorText = decoder.decode(uint8Array);
                let errorMsg = '打包文件失败';
                try {
                    // 尝试解析为 JSON
                    const errorObj = JSON.parse(errorText);
                    errorMsg = errorObj.msg || errorObj.message || errorText;
                } catch (e) {
                    // 不是 JSON，直接使用文本
                    errorMsg = errorText || '打包文件失败，请重试';
                }
                ElMessage.error(errorMsg);
            } catch (e) {
                ElMessage.error('打包文件失败，请重试');
            }
            return;
        }
        
        // 创建下载链接（使用验证后的 Blob）
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `运送清单_${row.deliveryNumber}_${new Date().getTime()}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        ElMessage.success('文件打包成功');
    } catch (error) {
        console.error('打包文件失败:', error);
        ElMessage.error(error.message || '打包文件失败，请重试');
    } finally {
        downLoading[row.id] = false;
    }
};

// 下载验收单
const downloadAcceptanceFormHandler = async (row) => {
    try {
        downLoading[row.id] = true;
        ElMessage.info('正在生成验收单，请稍候...');
        
        // 调用后端API生成验收单
        const res = await downloadAcceptanceForm(row.id);
        
        // 确保 res 是 Blob 对象
        let blob;
        if (res instanceof Blob) {
            blob = res;
        } else {
            blob = new Blob([res], { type: 'text/html;charset=UTF-8' });
        }
        
        // 检查是否是HTML文件（通过检查内容）
        const arrayBuffer = await blob.arrayBuffer();
        const uint8Array = new Uint8Array(arrayBuffer);
        
        // 尝试解码为文本，检查是否是HTML
        const decoder = new TextDecoder('utf-8');
        const htmlText = decoder.decode(uint8Array);
        
        // 检查是否是错误响应（JSON格式）
        if (htmlText.trim().startsWith('{') || htmlText.trim().startsWith('[')) {
            try {
                const errorObj = JSON.parse(htmlText);
                ElMessage.error(errorObj.msg || errorObj.message || '生成验收单失败，请重试');
            } catch (e) {
                ElMessage.error('生成验收单失败，请重试');
            }
            return;
        }
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `牛只发车验收单_${row.deliveryNumber || row.id}_${new Date().getTime()}.html`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        // 同时在新窗口中打开，方便预览
        const newWindow = window.open('', '_blank');
        if (newWindow) {
            newWindow.document.write(htmlText);
            newWindow.document.close();
        }
        
        ElMessage.success('验收单生成成功');
    } catch (error) {
        console.error('生成验收单失败:', error);
        ElMessage.error(error.message || '生成验收单失败，请重试');
    } finally {
        downLoading[row.id] = false;
    }
};

onMounted(() => {
    getDataList();
});
</script>

<style lang="less" scoped></style>
