<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="licensePlate" width="120"></el-table-column>
                <el-table-column label="车头照片" prop="carFrontPhoto" min-width="120">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.carFrontPhoto"
                            :src="scope.row.carFrontPhoto"
                            style="width: 60px; height: 60px; border-radius: 4px; border: 1px solid #dcdfe6"
                            fit="cover"
                            :preview-src-list="[scope.row.carFrontPhoto]"
                            preview-teleported
                            :lazy="true"
                        >
                            <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>
                        <span v-else style="color: #999; font-size: 12px">暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="车尾照片" prop="carRearPhoto" min-width="120">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.carRearPhoto"
                            :src="scope.row.carRearPhoto"
                            style="width: 60px; height: 60px; border-radius: 4px; border: 1px solid #dcdfe6"
                            fit="cover"
                            :preview-src-list="[scope.row.carRearPhoto]"
                            preview-teleported
                            :lazy="true"
                        >
                            <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>
                        <span v-else style="color: #999; font-size: 12px">暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="行驶证" prop="drivingLicensePhoto" min-width="120">
                    <template #default="scope">
                        <template v-if="getFirstImageUrl(scope.row.drivingLicensePhoto)">
                            <el-image
                                :src="getFirstImageUrl(scope.row.drivingLicensePhoto)"
                                style="width: 60px; height: 60px; border-radius: 4px; border: 1px solid #dcdfe6"
                                fit="cover"
                                :preview-src-list="getImageList(scope.row.drivingLicensePhoto)"
                                preview-teleported
                                :lazy="true"
                            >
                                <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>
                            <div v-if="getImageCount(scope.row.drivingLicensePhoto) > 1" style="margin-top: 4px; font-size: 12px; color: #409eff">
                                共{{ getImageCount(scope.row.drivingLicensePhoto) }}张
                            </div>
                        </template>
                        <span v-else style="color: #999; font-size: 12px">暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="牧运通备案码" prop="recordCode" min-width="120">
                    <template #default="scope">
                        <template v-if="getFirstImageUrl(scope.row.recordCode)">
                            <el-image
                                :src="getFirstImageUrl(scope.row.recordCode)"
                                style="width: 60px; height: 60px; border-radius: 4px; border: 1px solid #dcdfe6"
                                fit="cover"
                                :preview-src-list="getImageList(scope.row.recordCode)"
                                preview-teleported
                                :lazy="true"
                            >
                                <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>
                            <div v-if="getImageCount(scope.row.recordCode) > 1" style="margin-top: 4px; font-size: 12px; color: #409eff">
                                共{{ getImageCount(scope.row.recordCode) }}张
                            </div>
                        </template>
                        <span v-else style="color: #999; font-size: 12px">暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
                <el-table-column label="创建人" prop="createByName" width="120"></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="danger" @click="delClick(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" />
            <VehicleDialog ref="VehicleDialogRef" @success="getDataList" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import baseSearch from '@/components/common/searchCustom/index.vue';
import { vehicleList, vehicleDel } from '@/api/userManage.js';
import { sysUserList } from '@/api/sys.js';
import VehicleDialog from './vehicleDialog.vue';

const baseSearchRef = ref();
const VehicleDialogRef = ref();
const formItemList = reactive([
    {
        label: '车牌号',
        param: 'licensePlate',
        type: 'input',
        placeholder: '请输入车牌号',
        span: 7,
        labelWidth: 100,
    },
]);

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

const data = reactive({
    rows: [],
    total: 0,
    dataListLoading: false,
    userMap: {}, // 存储用户ID到用户名的映射 {userId: userName}
});

const form = reactive({
    pageNum: 1,
    pageSize: 10,
});

const showAddDialog = (row) => {
    VehicleDialogRef.value.open(row);
};

const delClick = (row) => {
    ElMessageBox.confirm('请确认是否删除该车辆数据？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            vehicleDel(row.id)
                .then(() => {
                    ElMessage.success('删除成功');
                    getDataList();
                })
                .catch((error) => {
                    ElMessage.error('删除失败');
                    console.error('删除失败:', error);
                });
        })
        .catch(() => {});
};

const getDataList = async () => {
    data.dataListLoading = true;
    try {
        // ✅ 使用 baseSearchRef 获取搜索参数
        const params = {
            ...form,
            ...baseSearchRef.value.penetrateParams(),
        };

        const res = await vehicleList(params);

        if (res.code === 200) {
            // 数据嵌套在 res.data.data 中
            const dataInfo = res.data?.data || res.data;
            data.rows = dataInfo?.rows || [];
            data.total = dataInfo?.total || 0;
            
            // 映射创建人名称
            await mapCreatedByName();
        } else {
            ElMessage.error(res.msg || '查询失败');
        }
    } catch (error) {
        console.error('查询车辆列表失败:', error);
        ElMessage.error('查询失败，请稍后重试');
    } finally {
        data.dataListLoading = false;
                }
};

// 解析图片 URL（支持 JSON 数组和单图片）
const getFirstImageUrl = (value) => {
    if (!value) return null;
    
    // 检查是否是 JSON 字符串格式（以 [ 开头）
    if (typeof value === 'string' && value.trim().startsWith('[')) {
        try {
            const parsed = JSON.parse(value);
            if (Array.isArray(parsed) && parsed.length > 0) {
                return parsed[0];
            }
            return null;
        } catch (e) {
            // 解析失败，按单图片处理（兼容旧数据）
            return value;
        }
    }
    // 不是 JSON 格式，按单图片处理（兼容旧数据）
    return value;
};

// 获取图片列表（用于预览）
const getImageList = (value) => {
    if (!value) return [];
    
    // 检查是否是 JSON 字符串格式（以 [ 开头）
    if (typeof value === 'string' && value.trim().startsWith('[')) {
        try {
            const parsed = JSON.parse(value);
            if (Array.isArray(parsed) && parsed.length > 0) {
                return parsed;
            }
            return [];
        } catch (e) {
            // 解析失败，按单图片处理（兼容旧数据）
            return [value];
        }
    }
    // 不是 JSON 格式，按单图片处理（兼容旧数据）
    return [value];
};

// 获取图片数量
const getImageCount = (value) => {
    if (!value) return 0;
    
    // 检查是否是 JSON 字符串格式（以 [ 开头）
    if (typeof value === 'string' && value.trim().startsWith('[')) {
        try {
            const parsed = JSON.parse(value);
            if (Array.isArray(parsed)) {
                return parsed.length;
            }
            return 0;
        } catch (e) {
            // 解析失败，按单图片处理（兼容旧数据）
            return 1;
        }
    }
    // 不是 JSON 格式，按单图片处理（兼容旧数据）
    return 1;
};

// 映射创建人名称
const mapCreatedByName = async () => {
    if (!data.rows || data.rows.length === 0) {
        return;
    }
    
    // 检查是否所有记录都已经有 createByName 字段（后端可能已经返回）
    const needMapping = data.rows.some(row => !row.createByName && row.createdBy);
    
    if (!needMapping) {
        // 如果所有记录都有 createByName，不需要映射
        return;
    }
    
    // 收集所有的 createdBy 字段值（去重）
    const createdByIds = [...new Set(data.rows
        .map(row => row.createdBy)
        .filter(id => id != null && id !== '' && id !== undefined))];
    
    if (createdByIds.length === 0) {
        // 如果没有创建人ID，设置默认值
        data.rows.forEach(row => {
            if (!row.createByName) {
                row.createByName = '--';
            }
        });
        return;
    }
    
    try {
        // 查询用户信息
        const userRes = await sysUserList({
            pageNum: 1,
            pageSize: 1000 // 设置一个较大的值以获取所有用户
        });
        
        if (userRes.code === 200) {
            const userList = userRes.data?.rows || userRes.data || [];
            
            // 创建用户ID到用户名的映射（只映射需要的用户）
            const idSet = new Set(createdByIds.map(id => String(id)));
            userList.forEach(user => {
                const userId = String(user.id);
                if (idSet.has(userId) && user.name) {
                    data.userMap[userId] = user.name;
                    // 同时支持数字ID和字符串ID的映射
                    data.userMap[user.id] = user.name;
                }
            });
            
            // 为每条记录设置 createByName（只设置没有值的记录）
            data.rows.forEach(row => {
                if (!row.createByName) {
                    if (row.createdBy) {
                        const userId = String(row.createdBy);
                        // 尝试多种方式查找用户名
                        row.createByName = data.userMap[row.createdBy] 
                            || data.userMap[userId] 
                            || data.userMap[Number(row.createdBy)]
                            || '--';
                    } else {
                        row.createByName = '--';
                    }
                }
            });
        } else {
            // API返回错误，使用默认值
            data.rows.forEach(row => {
                if (!row.createByName) {
                    row.createByName = row.createdBy ? String(row.createdBy) : '--';
                }
            });
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        // 如果获取用户信息失败，显示ID或默认值
        data.rows.forEach(row => {
            if (!row.createByName) {
                if (row.createdBy) {
                    row.createByName = String(row.createdBy);
                } else {
                    row.createByName = '--';
                }
            }
        });
    }
};

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

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

.dataListOnEmpty {
    text-align: center;
    padding: 20px;
    color: #999;
}
</style>

