<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef"> </base-search>
        <!-- 横向滚动操作栏 -->
        <div class="operation-scroll-bar">
            <div class="operation-scroll-container">
                <el-button type="primary" v-hasPermi="['delivery:add']" @click="showAddDialog(null)">新增运送清单</el-button>
            </div>
        </div>

        <div class="main-container">
            <el-table :data="rows" :key="data.tableKey" border v-loading="data.dataListLoading" element-loading-text="数据加载中..." style="width: 100%">
                <el-table-column label="运送清单编号" prop="deliveryNumber">
                    <template #default="scope">
                        {{ scope.row.deliveryNumber || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="清单标题" prop="deliveryTitle">
                    <template #default="scope">
                        {{ scope.row.deliveryTitle || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="起始地" prop="startLocation">
                    <template #default="scope">
                        {{ scope.row.startLocation || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="目的地" prop="endLocation">
                    <template #default="scope">
                        {{ scope.row.endLocation || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="车牌号" prop="licensePlate">
                    <template #default="scope">
                        {{ scope.row.licensePlate || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="司机姓名" prop="driverName">
                    <template #default="scope">
                        {{ scope.row.driverName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="司机手机号" prop="driverMobile">
                    <template #default="scope">
                        {{ scope.row.driverMobile || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime">
                    <template #default="scope">
                        {{ scope.row.createTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" v-hasPermi="['delivery:view']" @click="showDetailDialog(scope.row)">详情</el-button>
                        <el-button type="warning" size="small" v-hasPermi="['delivery:export']" @click="handleDownload(scope.row)">下载文件</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <el-pagination
                v-model:current-page="form.pageNum"
                v-model:page-size="form.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="data.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 对话框 -->
        <OrderDialog ref="OrderDialogRef" @success="getDataList" />
        <LookDialog ref="LookDialogRef" />
        <DetailDialog ref="DetailDialogRef" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import baseSearch from '@/components/common/searchCustom/index.vue';
import { shippingList, orderDel } from '@/api/shipping.js';
import OrderDialog from './orderDialog.vue';
import LookDialog from './lookDialog.vue';
import DetailDialog from './detailDialog.vue';

const baseSearchRef = ref();
const OrderDialogRef = ref();
const LookDialogRef = ref();
const DetailDialogRef = ref();

const formItemList = reactive([
    {
        label: '运单号',
        type: 'input',
        param: 'deliveryNumber',
        span: 6,
        placeholder: '请输入运单号',
    },
    {
        label: '清单标题',
        type: 'input',
        param: 'deliveryTitle',
        span: 6,
        placeholder: '请输入清单标题',
    },
    {
        label: '目的地',
        type: 'input',
        param: 'endLocation',
        span: 6,
        placeholder: '请输入目的地',
    },
    {
        label: '车牌号',
        type: 'input',
        param: 'licensePlate',
        span: 6,
        placeholder: '请输入车牌号',
    },
    {
        label: '状态',
        type: 'select',
        param: 'status',
        span: 6,
        placeholder: '请选择状态',
        selectOptions: [
            { text: '待装车', value: 1 },
            { text: '已装车/待资金方付款', value: 2 },
            { text: '待核验/资金方已付款', value: 3 },
            { text: '已核验/待买家付款', value: 4 },
            { text: '买家已付款', value: 5 }
        ],
        labelKey: 'text',
        valueKey: 'value',
    },
    {
        label: '创建时间',
        type: 'daterange',
        param: 'createTimeRange',
        span: 6,
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
    },
]);

const data = reactive({
    total: 0,
    dataListLoading: false,
    tableKey: 0,
});

const rows = ref([]);
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});

const searchFrom = () => {
    console.log('=== 运送清单搜索功能被触发 ===');
    form.pageNum = 1;
    getDataList();
};

// 获取运送清单列表
const getDataList = () => {
    data.dataListLoading = true;
    const searchParams = baseSearchRef.value.penetrateParams();
    
    const params = {
        ...form,
        ...searchParams,
    };
    
    // 处理日期范围参数
    if (searchParams.createTimeRange && Array.isArray(searchParams.createTimeRange) && searchParams.createTimeRange.length === 2) {
        params.startTime = searchParams.createTimeRange[0];
        params.endTime = searchParams.createTimeRange[1];
        delete params.createTimeRange;
    }
    
    console.log('运送清单列表查询参数:', params);
    shippingList(params)
        .then((res) => {
            console.log('运送清单列表返回结果:', res);
            data.dataListLoading = false;
            
            if (res.data.rows && res.data.rows.length > 0) {
                rows.value = res.data.rows;
                data.total = res.data.total;
            } else {
                rows.value = [];
                data.total = 0;
            }
        })
        .catch((error) => {
            console.error('运送清单列表查询失败:', error);
            data.dataListLoading = false;
            ElMessage.error('查询失败');
        });
};

// 分页处理
const handleSizeChange = (val) => {
    form.pageSize = val;
    getDataList();
};

const handleCurrentChange = (val) => {
    form.pageNum = val;
    getDataList();
};

// 状态相关方法
const getStatusText = (status) => {
    const statusMap = {
        1: '待装车',
        2: '已装车/待资金方付款',
        3: '待核验/资金方已付款',
        4: '已核验/待买家付款',
        5: '买家已付款'
    };
    return statusMap[status] || '未知状态';
};

const getStatusType = (status) => {
    const typeMap = {
        1: 'warning',
        2: 'info',
        3: 'primary',
        4: 'success',
        5: 'success'
    };
    return typeMap[status] || 'info';
};

// 对话框方法
const showAddDialog = (row) => {
    OrderDialogRef.value.onShowDialog(row);
};

const showLookDialog = (row) => {
    LookDialogRef.value.onShowLookDialog(row);
};

const showDetailDialog = (row) => {
    DetailDialogRef.value.onShowDetailDialog(row);
};

// 下载方法 - 生成牛只验收单
const handleDownload = async (row) => {
    try {
        // 计算字段
        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('生成牛只验收单数据:', data);
        
        // 生成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('生成牛只验收单失败，请重试');
    }
};

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

<style scoped>
.operation-scroll-bar {
    overflow-x: auto;
    margin-bottom: 10px;
}

.operation-scroll-container {
    display: flex;
    gap: 10px;
    min-width: max-content;
    padding: 10px;
    background: #fff;
}

.main-container {
    background: #fff;
    padding: 20px;
}
</style>
