<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="['loading:create']" @click="showAddDialog(null)">创建订单</el-button>
                <el-button
                    type="primary"
                    v-hasPermi="['loading:add']"
                    @click="showCreateDeliveryDialog"
                    style="margin-left: 10px"
                >
                    新增运送清单
                </el-button>
                <el-dropdown
                    v-hasPermi="['order:import']"
                    @command="handleImportCommand"
                    style="margin-left: 10px"
                >
                    <el-button type="success">
                        导入数据
                        <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="import">导入数据</el-dropdown-item>
                            <el-dropdown-item command="download">下载模板</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" />
            </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="订单ID" prop="id" width="100">
                    <template #default="scope">
                        {{ scope.row.id || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="买方" prop="buyerName" width="200">
                    <template #default="scope">
                        {{ scope.row.buyerName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="卖方" prop="sellerName" width="200">
                    <template #default="scope">
                        {{ scope.row.sellerName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="结算方式" prop="settlementTypeDesc" width="150">
                    <template #default="scope">
                        {{ scope.row.settlementTypeDesc || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="创建人" prop="createdByName" width="120">
                    <template #default="scope">
                        {{ scope.row.createdByName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180">
                    <template #default="scope">
                        {{ scope.row.createTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" v-hasPermi="['order:edit']" @click="showEditDialog(scope.row)">编辑</el-button>
                        <el-button link type="primary" v-hasPermi="['order:delete']" @click="del(scope.row.id)">删除</el-button>
                    </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" 
            />
            <OrderDialog ref="OrderDialogRef" @success="getDataList" />
            <CreateDeliveryDialog ref="CreateDeliveryDialogRef" @success="getDataList" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';
import baseSearch from '@/components/common/searchCustom/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import { orderPageQuery, orderDelete, orderBatchImport } from '@/api/shipping.js';
import { memberListByType, userAdd } from '@/api/userManage.js';
import OrderDialog from './orderDialog.vue';
import CreateDeliveryDialog from './createDeliveryDialog.vue';

const baseSearchRef = ref();
const OrderDialogRef = ref();
const CreateDeliveryDialogRef = ref();
const fileInputRef = ref();
const formItemList = reactive([
    {
        label: '买方',
        type: 'input',
        param: 'buyerName',
        span: 6,
        placeholder: '请输入买方',
    },
    {
        label: '卖方',
        type: 'input',
        param: 'sellerName',
        span: 6,
        placeholder: '请输入卖方',
    },
    {
        label: '结算方式',
        type: 'select',
        param: 'settlementType',
        span: 6,
        selectOptions: [
            { text: '上车重量', value: 1 },
            { text: '下车重量', value: 2 },
            { text: '按肉价结算', value: 3 }
        ],
        placeholder: '请选择结算方式',
    },
    {
        label: '创建时间',
        type: 'daterange',
        param: 'createTimeRange',
        span: 6,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        format: 'YYYY-MM-DD',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
    },
]);
const data = reactive({
    total: 0,
    dataListLoading: false,
    tableKey: 0, // 用于强制重新渲染表格
    forceUpdate: 0, // 用于强制更新
});

// 使用ref确保响应式更新
const rows = ref([]);
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});

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

// 处理分页事件
const handlePagination = (paginationData) => {
    if (paginationData) {
        form.pageNum = paginationData.page || form.pageNum;
        form.pageSize = paginationData.limit || form.pageSize;
    }
    getDataList();
};

// 列表
const getDataList = () => {
    data.dataListLoading = true;
    const searchParams = baseSearchRef.value.penetrateParams();
    
    // 处理日期范围参数
    const params = {
        ...form,
        ...searchParams,
    };
    
    // 如果存在日期范围，需要拆分为startTime和endTime
    if (searchParams.createTimeRange && Array.isArray(searchParams.createTimeRange) && searchParams.createTimeRange.length === 2) {
        params.startTime = searchParams.createTimeRange[0];
        params.endTime = searchParams.createTimeRange[1];
        delete params.createTimeRange; // 删除原始参数
    }
    
    // 清理字符串参数中的空白字符
    if (params.buyerName && typeof params.buyerName === 'string') {
        params.buyerName = params.buyerName.trim();
        if (params.buyerName === '') delete params.buyerName;
    }
    if (params.sellerName && typeof params.sellerName === 'string') {
        params.sellerName = params.sellerName.trim();
        if (params.sellerName === '') delete params.sellerName;
    }
    

    // 调用订单列表接口，而不是装车订单接口
    console.log('[ORDER-LIST] 请求参数:', params);
    orderPageQuery(params)
        .then((res) => {
            data.dataListLoading = false;
            
            console.log('[ORDER-LIST] 响应数据:', res);
            
            // 处理响应数据结构
            // PageResultResponse 返回的结构是 { code, msg, data: { total, rows } }
            let responseData = res.data || res;
            
            // 如果 data 是对象且包含 total 和 rows，直接使用
            if (responseData && typeof responseData === 'object' && 'total' in responseData && 'rows' in responseData) {
                rows.value = responseData.rows || [];
                data.total = responseData.total || 0;
            } else if (responseData && responseData.data) {
                // 如果 data 是嵌套的，使用 data.data
                rows.value = responseData.data.rows || [];
                data.total = responseData.data.total || 0;
            } else {
                // 兜底处理
                rows.value = [];
                data.total = 0;
            }
            
            console.log('[ORDER-LIST] 解析后的数据 - 总数:', data.total, '当前页数据:', rows.value.length);
        })
        .catch((error) => {
            console.error('[ORDER-LIST] 请求失败:', error);
            data.dataListLoading = false;
            rows.value = [];
            data.total = 0;
        });
};
// 新增装车订单
const showAddDialog = (row) => {
    if (OrderDialogRef.value) {
        OrderDialogRef.value.onShowDialog(row);
    }
};
// 编辑订单
const showEditDialog = (row) => {
    if (OrderDialogRef.value) {
        OrderDialogRef.value.onShowDialog(row);
    }
};

// 新增运送清单
const showCreateDeliveryDialog = () => {
    if (CreateDeliveryDialogRef.value) {
        CreateDeliveryDialogRef.value.open();
    }
};

// 删除订单（逻辑删除）
const del = (id) => {
    ElMessageBox.confirm('请确认是否删除订单？删除后将不可恢复', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
    }).then(() => {
        // 调用订单删除接口
        orderDelete(id).then((res) => {
            if (res.code === 200) {
                ElMessage.success('订单删除成功');
                getDataList();
            } else {
                ElMessage.error(res.msg || '删除订单失败');
            }
        }).catch((error) => {
            console.error('删除订单失败:', error);
            ElMessage.error('删除订单失败');
        });
    });
};

// 导入数据相关
const handleImportCommand = (command) => {
    if (command === 'import') {
        if (fileInputRef.value) {
            fileInputRef.value.click();
        }
    } else if (command === 'download') {
        downloadTemplate();
    }
};

// 下载导入模板
const downloadTemplate = () => {
    try {
        // 创建表头
        const headers = ['单价/斤', '卖方全称', '买方全称'];
        
        // 创建工作簿
        const wb = XLSX.utils.book_new();
        
        // 创建工作表数据（只有表头）
        const wsData = [headers];
        const ws = XLSX.utils.aoa_to_sheet(wsData);
        
        // 设置列宽
        ws['!cols'] = [
            { wch: 15 }, // 单价/斤
            { wch: 30 }, // 卖方全称
            { wch: 30 }  // 买方全称
        ];
        
        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '订单导入模板');
        
        // 生成Excel文件并下载
        XLSX.writeFile(wb, '订单导入模板.xlsx');
        
        ElMessage.success('模板下载成功');
    } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error('下载模板失败：' + (error.message || '未知错误'));
    }
};

// 处理文件选择
const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) {
        return;
    }

    // 验证文件类型
    const fileName = file.name;
    const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
    if (fileExtension !== 'xlsx' && fileExtension !== 'xls') {
        ElMessage.error('请选择Excel文件（.xlsx或.xls格式）');
        event.target.value = '';
        return;
    }

    try {
        // 读取Excel文件
        const excelData = await readExcelFile(file);
        
        // 解析和转换数据
        const orderDataList = await parseExcelData(excelData);
        
        if (orderDataList.length === 0) {
            ElMessage.warning('Excel文件中没有有效数据');
            event.target.value = '';
            return;
        }

        // 批量导入
        await batchImportOrders(orderDataList);
        
        // 清空文件选择
        event.target.value = '';
    } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败：' + (error.message || '未知错误'));
        event.target.value = '';
    }
};

// 读取Excel文件
const readExcelFile = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                resolve(jsonData);
            } catch (error) {
                reject(new Error('Excel文件解析失败：' + error.message));
            }
        };
        reader.onerror = () => {
            reject(new Error('文件读取失败'));
        };
        reader.readAsArrayBuffer(file);
    });
};

// 解析Excel数据
const parseExcelData = async (data) => {
    if (!data || data.length < 2) {
        return [];
    }

    // 第一行是表头
    const headers = data[0].map(h => String(h || '').trim());
    
    // 查找列索引
    const priceIndex = headers.findIndex(h => h.includes('单价') || h.includes('价格'));
    const sellerIndex = headers.findIndex(h => h.includes('卖方'));
    const buyerIndex = headers.findIndex(h => h.includes('买方'));

    if (priceIndex === -1) {
        throw new Error('未找到"单价/斤"列');
    }
    if (sellerIndex === -1) {
        throw new Error('未找到"卖方全称"列');
    }
    if (buyerIndex === -1) {
        throw new Error('未找到"买方全称"列');
    }

    const orderDataList = [];
    
    // 从第二行开始读取数据
    for (let i = 1; i < data.length; i++) {
        const row = data[i];
        if (!row || row.length === 0) {
            continue;
        }

        const price = row[priceIndex];
        const sellerName = String(row[sellerIndex] || '').trim();
        const buyerName = String(row[buyerIndex] || '').trim();

        // 跳过空行
        if (!sellerName && !buyerName) {
            continue;
        }

        // 验证必填字段
        if (!sellerName) {
            throw new Error(`第${i + 1}行：卖方全称不能为空`);
        }
        if (!buyerName) {
            throw new Error(`第${i + 1}行：买方全称不能为空`);
        }
        if (price === null || price === undefined || price === '') {
            throw new Error(`第${i + 1}行：单价/斤不能为空`);
        }

        // 转换价格为数字
        const firmPrice = parseFloat(price);
        if (isNaN(firmPrice) || firmPrice < 0) {
            throw new Error(`第${i + 1}行：单价/斤格式不正确，必须为大于等于0的数字`);
        }

        // 查找或创建用户
        const sellerId = await findOrCreateUser(sellerName);
        const buyerId = await findOrCreateUser(buyerName);

        if (!sellerId) {
            throw new Error(`第${i + 1}行：无法创建或找到卖方"${sellerName}"`);
        }
        if (!buyerId) {
            throw new Error(`第${i + 1}行：无法创建或找到买方"${buyerName}"`);
        }

        orderDataList.push({
            sellerId: String(sellerId),
            buyerId: String(buyerId),
            settlementType: 1, // 默认结算方式为上车重量
            firmPrice: firmPrice
        });
    }

    return orderDataList;
};

// 查找或创建用户
const findOrCreateUser = async (username) => {
    if (!username || !username.trim()) {
        return null;
    }

    try {
        // 先尝试查找用户（同时查询 type=2 和 type=4）
        const [supplierRes, purchaserRes] = await Promise.all([
            memberListByType({
                pageNum: 1,
                pageSize: 100,
                type: 2,
                username: username.trim()
            }),
            memberListByType({
                pageNum: 1,
                pageSize: 100,
                type: 4,
                username: username.trim()
            })
        ]);

        // 合并结果并查找匹配的用户（精确匹配用户名）
        const supplierList = supplierRes.data?.rows || [];
        const purchaserList = purchaserRes.data?.rows || [];
        const allUsers = [...supplierList, ...purchaserList];
        
        // 精确匹配用户名
        const matchedUser = allUsers.find(user => {
            const userUsername = String(user.username || '').trim();
            return userUsername === username.trim();
        });

        if (matchedUser && matchedUser.id) {
            return matchedUser.id;
        }

        // 如果找不到，创建新用户（默认类型为2-供应商）
        try {
            const createRes = await userAdd({
                username: username.trim(),
                type: 2, // 默认类型为供应商
                status: 0, // 启用
                mobile: null,
                cbkAccount: '',
                remark: '通过订单导入自动创建'
            });

            if (createRes.code === 200) {
                // 创建成功后，再次查询获取新用户的ID
                const newUserRes = await memberListByType({
                    pageNum: 1,
                    pageSize: 1,
                    type: 2,
                    username: username.trim()
                });

                const newUserList = newUserRes.data?.rows || [];
                if (newUserList.length > 0) {
                    const newUser = newUserList.find(user => {
                        const userUsername = String(user.username || '').trim();
                        return userUsername === username.trim();
                    });
                    if (newUser && newUser.id) {
                        return newUser.id;
                    }
                }
            } else {
                throw new Error(createRes.msg || '创建用户失败');
            }
        } catch (createError) {
            console.error(`创建用户失败 "${username}":`, createError);
            throw new Error(`创建用户"${username}"失败：${createError.message || '未知错误'}`);
        }

        return null;
    } catch (error) {
        console.error(`查找或创建用户失败 "${username}":`, error);
        throw error;
    }
};

// 批量导入订单
const batchImportOrders = async (orderDataList) => {
    const total = orderDataList.length;
    
    ElMessage.info(`开始导入，共${total}条数据`);

    try {
        const res = await orderBatchImport({
            orders: orderDataList
        });

        if (res.code === 200) {
            const successCount = res.data?.successCount || total;
            const failCount = res.data?.failCount || 0;
            const failMessages = res.data?.failMessages || [];

            if (failCount === 0) {
                ElMessage.success(`导入成功！共导入${successCount}条数据`);
            } else {
                ElMessage.warning(`导入完成：成功${successCount}条，失败${failCount}条`);
                if (failMessages.length > 0) {
                    ElMessageBox.alert(
                        failMessages.slice(0, 10).join('\n') + (failMessages.length > 10 ? `\n...还有${failMessages.length - 10}条错误` : ''),
                        '导入失败详情',
                        { type: 'error' }
                    );
                }
            }

            // 刷新列表
            getDataList();
        } else {
            ElMessage.error(res.msg || '导入失败');
        }
    } catch (error) {
        console.error('批量导入失败:', error);
        const errorMsg = error.response?.data?.msg || error.message || '未知错误';
        ElMessage.error('导入失败：' + errorMsg);
    }
};

onMounted(() => {

    getDataList();
});
</script>

<style lang="less" scoped>
/* 横向滚动操作栏样式 */
.operation-scroll-bar {
    background: #fff;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    margin-bottom: 16px;
    padding: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.operation-scroll-container {
    display: flex;
    overflow-x: auto;
    gap: 10px;
    padding-bottom: 5px;
    
    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
        height: 6px;
    }
    
    &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
        
        &:hover {
            background: #a8a8a8;
        }
    }
    
    /* 确保按钮不会被压缩 */
    .el-button {
        flex-shrink: 0;
        white-space: nowrap;
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .operation-scroll-bar {
        padding: 8px;
        margin-bottom: 12px;
    }
    
    .operation-scroll-container {
        gap: 8px;
        
        .el-button {
            font-size: 12px;
            padding: 6px 12px;
        }
    }
}
</style>

