<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>
            </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-model:limit="form.pageSize" v-model:page="form.pageNum" :total="data.total" @pagination="getDataList" />
            <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 baseSearch from '@/components/common/searchCustom/index.vue';
import { orderPageQuery, orderDelete } from '@/api/shipping.js';
import OrderDialog from './orderDialog.vue';
import CreateDeliveryDialog from './createDeliveryDialog.vue';

const baseSearchRef = ref();
const OrderDialogRef = ref();
const CreateDeliveryDialogRef = 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 = () => {
    console.log('=== 搜索功能被触发 ===');
    form.pageNum = 1;
    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('订单列表查询参数:', params);
    // 调用订单列表接口，而不是装车订单接口
    orderPageQuery(params)
        .then((res) => {
            console.log('订单列表返回结果:', res);
            data.dataListLoading = false;
            
            // 直接赋值订单数据
            console.log('=== 订单数据 ===');
            console.log('完整响应:', res);
            console.log('res.data:', res.data);
            console.log('数据行数:', res.data?.rows?.length || 0);
            
            rows.value = res.data?.rows || [];
            data.total = res.data?.total || 0;
            
            console.log('更新后rows长度:', rows.value.length);
            console.log('更新后total:', data.total);
            if (rows.value.length > 0) {
                console.log('第一行订单数据:', rows.value[0]);
            }
        })
        .catch(() => {
            data.dataListLoading = false;
        });
};
// 新增装车订单
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('删除订单失败');
        });
    });
};

onMounted(() => {
    console.log('=== 装车订单页面已加载 ===');
    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>
