<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
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="scope.row.carFrontPhoto ? scope.row.carFrontPhoto : ''"
                            fit="cover"
                            :preview-src-list="[scope.row.carFrontPhoto] ? [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>
                        <el-image
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="scope.row.carBehindPhoto ? scope.row.carBehindPhoto : ''"
                            fit="cover"
                            :preview-src-list="[scope.row.carBehindPhoto] ? [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>
                    </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="194">
                    <template #default="scope">
                        <div class="table_column_operation">
                            <a v-hasPermi="['entry:view']" @click="details(scope.row, scope.row.warningTypeList ? scope.row.warningTypeList.length : 0)">详情</a>
                            <el-button
                                type="primary"
                                link
                                v-if="scope.row.status == 4 || scope.row.status == 5"
                                v-hasPermi="['entry:download']"
                                @click="download(scope.row)"
                                :loading="downLoading[scope.row.id]"
                                style="padding: 0"
                                >下载文件</el-button
                            >
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="dataListOnEmpty">暂无数据</div>
                </template>
            </el-table>
            <pagination v-model:limit="form.pageSize" v-model:page="form.pageNum" :total="data.total" @pagination="getDataList" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import baseSearch from '@/components/common/searchCustom/index.vue';
import { inspectionList, downloadZip, pageDeviceList } from '@/api/abroad.js';

const router = useRouter();
const route = useRoute();
const baseSearchRef = ref();
const dataListLoading = ref(false);
const downLoading = reactive({});
const form = reactive({
    pageNum: 1,
    pageSize: 20,
});
const data = reactive({
    rows: [],
    total: 20,
    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: '已装车/尾款待支付' },
            { value: 4, text: '已核验/待买家付款' },
            { value: 5, text: '尾款已付款' },
            { value: 6, text: '发票待开/进项票' },
            { value: 7, text: '发票待开/销项' },
        ],
        param: 'status',
        span: 7,
    },
]);

// 获取指定订单的设备数量
const getDeviceCounts = async (deliveryId) => {
    try {
        console.log('=== 获取订单设备数量，deliveryId:', deliveryId);
        
        // 获取所有设备类型的数据
        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;
        
        console.log('=== 设备数量统计:', {
            deliveryId,
            hostCount,
            earCount,
            collarCount,
            totalCount
        });
        
        // 存储设备数量
        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 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;
        console.log('精确创建时间查询:', searchParams.createTime);
    }
    
    // 处理精确的车牌号查询
    if (searchParams.licensePlate) {
        params.licensePlate = searchParams.licensePlate.trim();
        console.log('精确车牌号查询:', params.licensePlate);
    }
    
    console.log('查询参数:', params);
    
    inspectionList(params)
        .then(async (ret) => {
            console.log('入境检疫列表返回结果:', ret);
            data.rows = ret.data.rows;
            data.total = ret.data.total;
            dataListLoading.value = false;
            
            // 为每个订单获取设备数量
            if (ret.data.rows && ret.data.rows.length > 0) {
                console.log('=== 开始为每个订单获取设备数量');
                for (const row of ret.data.rows) {
                    if (row.id) {
                        await getDeviceCounts(row.id);
                    }
                }
                console.log('=== 所有订单设备数量获取完成');
            }
            
            // 调试：检查第一行数据的字段
            if (ret.data.rows && ret.data.rows.length > 0) {
                const firstRow = ret.data.rows[0];
                console.log('入境检疫第一行数据完整字段:', firstRow);
                console.log('入境检疫关键字段检查:', {
                    status: firstRow.status,
                    statusDesc: firstRow.statusDesc,
                    registeredJbqCount: firstRow.registeredJbqCount,
                    earTagCount: firstRow.earTagCount,
                    driverName: firstRow.driverName,
                    licensePlate: firstRow.licensePlate
                });
                
                // 检查Word导出所需字段
                console.log('Word导出字段检查:', {
                    supplierName: firstRow.supplierName,
                    buyerName: firstRow.buyerName,
                    startLocation: firstRow.startLocation,
                    createTime: firstRow.createTime,
                    endLocation: firstRow.endLocation,
                    driverName: firstRow.driverName,
                    driverMobile: firstRow.driverMobile,
                    licensePlate: firstRow.licensePlate,
                    ratedQuantity: firstRow.ratedQuantity,
                    landingEntruckWeight: firstRow.landingEntruckWeight,
                    emptyWeight: firstRow.emptyWeight,
                    firmPrice: firstRow.firmPrice
                });
            }
        })
        .catch(() => {
            dataListLoading.value = false;
        });
};
// 详情
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
        };
        
        console.log('生成Word文档数据:', data);
        console.log('原始数据字段检查:', {
            supplierName: row.supplierName,
            buyerName: row.buyerName,
            supplierMobile: row.supplierMobile,
            buyerMobile: row.buyerMobile,
            fundName: row.fundName,
            fundMobile: row.fundMobile
        });
        
        // 生成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: '已装车/尾款待支付',
        4: '已核验/待买家付款',
        5: '尾款已付款',
        6: '发票待开/进项票',
        7: '发票待开/销项'
    };
    return statusMap[status] || '未知状态';
};

// 状态标签类型
const getStatusTagType = (status) => {
    const typeMap = {
        1: 'warning',  // 待装车 - 橙色
        2: 'info',      // 已装车/预付款已支付 - 蓝色
        3: 'warning',   // 已装车/尾款待支付 - 橙色
        4: 'success',   // 已核验/待买家付款 - 绿色
        5: 'success',   // 尾款已付款 - 绿色
        6: 'info',      // 发票待开/进项票 - 蓝色
        7: 'info'       // 发票待开/销项 - 蓝色
    };
    return typeMap[status] || 'info';
};

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

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