<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef"> </base-search>
        <div style="display: flex; padding: 10px; background: #fff; margin-bottom: 10px">
            <el-button type="primary" @click="showAddDialog(null)">新增司机</el-button>
        </div>
        <div class="main-container">
            <el-table :data="data.rows" border v-loading="data.dataListLoading" element-loading-text="数据加载中..." style="width: 100%">
                <el-table-column label="司机姓名" prop="username"></el-table-column>
                <el-table-column label="司机手机号" prop="mobile"> </el-table-column>
                <el-table-column label="车牌号" prop="car_number"></el-table-column>
                <el-table-column label="车辆照片" prop="car_img" min-width="120">
                    <template #default="scope">
                        <div style="display: flex; flex-wrap: wrap; gap: 5px">
                            <template v-if="scope.row.car_img && getImageListSync(scope.row.car_img).length > 0">
                                <el-image
                                    v-for="(item, index) in getImageListSync(scope.row.car_img)"
                                    :key="index"
                                    :src="item"
                                    style="width: 60px; height: 60px; border-radius: 4px; border: 1px solid #dcdfe6"
                                    fit="cover"
                                    :preview-src-list="getImageListSync(scope.row.car_img)"
                                    preview-teleported
                                    :lazy="true"
                                    @error="handleImageErrorLocal(item, index)"
                                >
                                    <template #error>
                                        <div style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background: #f5f7fa; border-radius: 4px; color: #909399">
                                            <el-icon size="20"><Picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </template>
                            <span v-else style="color: #999; font-size: 12px">暂无图片</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark"> </el-table-column>
                <el-table-column label="创建时间" prop="create_time"></el-table-column>
                <el-table-column label="操作" width="160">
                    <template #default="scope">
                        <el-button link type="primary" @click="showAddDialog(scope.row)">编辑</el-button>
                        <!-- <el-button link type="primary" @click="delClick(scope.row)">删除</el-button> -->
                        <el-button link type="primary" @click="showDetailDialog(scope.row)">详情</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" />
            <DriverDialog ref="DriverDialogRef" @success="getDataList" />
            <DetailDialog ref="DetailDialogRef" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Picture } from '@element-plus/icons-vue';
import baseSearch from '@/components/common/searchCustom/index.vue';
import { driverList } from '@/api/userManage.js';
import DriverDialog from './driverDialog.vue';
import DetailDialog from './driverDetailDialog.vue';
import { getImageList, getImageListWithProxy, getImageListSmart, testImageUrl, handleImageError } from '@/utils/imageUtils.js';

const baseSearchRef = ref();
const DriverDialogRef = ref();
const DetailDialogRef = ref();
const formItemList = reactive([
    {
        label: '司机姓名',
        param: 'username',
        type: 'input',
        placeholder: '请输入司机姓名',
        span: 7,
        labelWidth: 100,
    },
    {
        label: '司机手机号',
        param: 'mobile',
        type: 'input',
        placeholder: '请输入完整手机号（精确查询）',
        span: 7,
        labelWidth: 100,
    },
]);
const searchFrom = () => {
    form.pageNum = 1;
    getDataList();
};
const data = reactive({
    rows: [],
    total: 0,
    dataListLoading: false,
});
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});
// 列表
const getDataList = () => {
    data.dataListLoading = true;
    const params = {
        ...form,
        ...baseSearchRef.value.penetrateParams(),
    };
    
    // 添加调试信息
    console.log('发送查询参数:', params);
    
    driverList(params)
        .then((res) => {
            data.dataListLoading = false;
            console.log('查询结果:', res);
            console.log('司机数据详情:', res.data.rows);
            // 特别检查car_img字段 - 分析能显示和不能显示的图片差异
            if (res.data.rows && res.data.rows.length > 0) {
                res.data.rows.forEach(async (driver, index) => {
                    console.log(`=== 司机${index + 1}: ${driver.username} (${driver.mobile}) ===`);
                    console.log(`car_img字段:`, driver.car_img);
                    console.log(`car_img类型:`, typeof driver.car_img);
                    
                    if (driver.car_img) {
                        const urls = getImageList(driver.car_img);
                        console.log(`解析后的图片URLs:`, urls);
                        
                        // 分析URL特征
                        urls.forEach((url, urlIndex) => {
                            console.log(`URL ${urlIndex + 1} 分析:`);
                            console.log(`  - 完整URL: ${url}`);
                            console.log(`  - 长度: ${url.length}`);
                            console.log(`  - 是否HTTPS: ${url.startsWith('https://')}`);
                            console.log(`  - 域名: ${url.includes('cos.ap-guangzhou.myqcloud.com') ? '腾讯云COS' : '其他'}`);
                            console.log(`  - 文件名: ${url.split('/').pop()}`);
                            
                            // 检查是否是车辆照片还是其他类型图片
                            const fileName = url.split('/').pop().toLowerCase();
                            if (fileName.includes('cow') || fileName.includes('4c4e')) {
                                console.log(`  - 图片类型: 车辆照片 (可能CORS受限)`);
                            } else {
                                console.log(`  - 图片类型: 其他图片 (可能不受CORS限制)`);
                            }
                        });
                    } else {
                        console.log(`car_img字段为空`);
                    }
                    console.log(`---`);
                });
            }
            data.rows = res.data.rows;
            data.total = res.data.total;
        })
        .catch((error) => {
            data.dataListLoading = false;
            console.error('查询失败:', error);
        });
};
// 删除
const delClick = (row) => {
    ElMessageBox.confirm('请确认是否删除该条数据？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
    })
        .then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功',
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            });
        });
};
// 新增司机
const showAddDialog = (row) => {
    if (DriverDialogRef.value) {
        DriverDialogRef.value.onShowDialog(row);
    }
};
// 详情
const showDetailDialog = (row) => {
    if (DetailDialogRef.value) {
        DetailDialogRef.value.onShowDetailDialog(row);
    }
};

// 使用智能处理方案 - 根据图片域名决定是否使用代理
const getImageListSync = (imageUrl) => {
    return getImageListSmart(imageUrl);
};

// 异步版本用于调试
const getImageListAsync = async (imageUrl) => {
    const urls = getImageList(imageUrl);
    console.log('getImageList 输入参数:', imageUrl);
    console.log('getImageList 参数类型:', typeof imageUrl);
    console.log('getImageList 解析结果:', urls);
    
    // 测试每个URL的可访问性
    for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        console.log(`URL ${i + 1}:`, url);
        console.log(`URL ${i + 1} 是否以http开头:`, url.startsWith('http'));
        console.log(`URL ${i + 1} 长度:`, url.length);
        
        // 测试URL可访问性
        const isAccessible = await testImageUrl(url);
        console.log(`URL ${i + 1} 可访问性:`, isAccessible);
    }
    
    return urls;
};

// 使用工具函数处理图片错误
const handleImageErrorLocal = (imageUrl, index) => {
    handleImageError(imageUrl, index);
};

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

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