<template>
    <el-dialog v-model="data.dialogVisible" :title="data.title" :before-close="handleClose" style="width: 650px; padding-bottom: 20px">
        <el-form ref="formDataRef" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="车牌号" prop="licensePlate">
                <el-input v-model="ruleForm.licensePlate" placeholder="请输入车牌号" clearable></el-input>
            </el-form-item>
            <el-form-item label="车头照片" prop="carFrontPhoto">
                <el-upload
                    :limit="1"
                    list-type="picture-card"
                    action="/api/common/upload"
                    :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, 'carFrontPhoto')"
                    :on-preview="handlePreview"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, 'carFrontPhoto')"
                    :before-upload="beforeAvatarUpload"
                    :file-list="ruleForm.carFrontPhoto"
                    :headers="importHeaders"
                    :on-exceed="handleExceed"
                    @drop.native="(e) => handleDrop(e, 'carFrontPhoto')"
                    @dragover.native.prevent
                    @dragenter.native="(e) => handleDragEnter(e)"
                    @dragleave.native="(e) => handleDragLeave(e)"
                    class="upload-drag-area"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="车尾照片" prop="carRearPhoto">
                <el-upload
                    :limit="1"
                    list-type="picture-card"
                    action="/api/common/upload"
                    :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, 'carRearPhoto')"
                    :on-preview="handlePreview"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, 'carRearPhoto')"
                    :before-upload="beforeAvatarUpload"
                    :file-list="ruleForm.carRearPhoto"
                    :headers="importHeaders"
                    :on-exceed="handleExceed"
                    @drop.native="(e) => handleDrop(e, 'carRearPhoto')"
                    @dragover.native.prevent
                    @dragenter.native="(e) => handleDragEnter(e)"
                    @dragleave.native="(e) => handleDragLeave(e)"
                    class="upload-drag-area"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="行驶证照片" prop="drivingLicensePhoto">
                <el-upload
                    list-type="picture-card"
                    action="/api/common/upload"
                    :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, 'drivingLicensePhoto')"
                    :on-preview="handlePreview"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, 'drivingLicensePhoto')"
                    :before-upload="beforeAvatarUpload"
                    :file-list="ruleForm.drivingLicensePhoto"
                    :headers="importHeaders"
                    @drop.native="(e) => handleDrop(e, 'drivingLicensePhoto')"
                    @dragover.native.prevent
                    @dragenter.native="(e) => handleDragEnter(e)"
                    @dragleave.native="(e) => handleDragLeave(e)"
                    class="upload-drag-area"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="牧运通备案码" prop="recordCode">
                <el-upload
                    list-type="picture-card"
                    action="/api/common/upload"
                    :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, 'recordCode')"
                    :on-preview="handlePreview"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, 'recordCode')"
                    :before-upload="beforeAvatarUpload"
                    :file-list="ruleForm.recordCode"
                    :headers="importHeaders"
                    @drop.native="(e) => handleDrop(e, 'recordCode')"
                    @dragover.native.prevent
                    @dragenter.native="(e) => handleDragEnter(e)"
                    @dragleave.native="(e) => handleDragLeave(e)"
                    class="upload-drag-area"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="ruleForm.remark" placeholder="请输入备注" clearable></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="data.saveLoading" type="primary" @click="onClickSave">保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
        <el-dialog v-model="data.dialogVisibleImg">
            <img w-full :src="data.dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { vehicleAdd, vehicleEdit } from '@/api/userManage.js';
import { useUserStore } from '../../store/user';

const userStore = useUserStore();
const importHeaders = reactive({ Authorization: userStore.$state.token });
const emits = defineEmits(['success']);
const formDataRef = ref();
const data = reactive({
    dialogVisible: false,
    title: '',
    saveLoading: false,
    dialogVisibleImg: false,
    dialogImageUrl: '',
    isEdit: false,
});
const ruleForm = reactive({
    id: null,
    licensePlate: '',
    carFrontPhoto: [],
    carRearPhoto: [],
    drivingLicensePhoto: [],
    recordCode: [],
    remark: '',
});

const rules = reactive({
    licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
});

const handleAvatarSuccess = (res, file, fileList, type) => {
    if (ruleForm.hasOwnProperty(type)) {
        let imageUrl = null;
        
        if (res && res.data && res.data.src) {
            imageUrl = res.data.src;
        } else if (res && res.data && typeof res.data === 'string') {
            imageUrl = res.data;
        } else if (res && res.url) {
            imageUrl = res.url;
        } else if (res && typeof res === 'string') {
            imageUrl = res;
        }
        
        if (imageUrl) {
            // 行驶证和备案码支持多图片，其他字段保持单图片
            if (type === 'drivingLicensePhoto' || type === 'recordCode') {
                // 多图片：更新整个文件列表
                ruleForm[type] = fileList.map(item => {
                    // 如果是新上传的文件，使用新的 URL
                    if (item.uid === file.uid) {
                        return { url: imageUrl, uid: file.uid, name: file.name };
                    }
                    // 保持原有文件信息
                    return item;
                });
            } else {
                // 单图片：只保留最新的一张
                ruleForm[type] = [{ url: imageUrl, uid: file.uid, name: file.name }];
            }
        } else {
            console.error('无法解析图片URL:', res);
            ElMessage.error('上传失败：无法获取图片URL');
        }
    }
};

const handleRemove = (file, fileList, type) => {
    ruleForm[type] = fileList;
};

const handlePreview = (file) => {
    data.dialogImageUrl = file.url;
    data.dialogVisibleImg = true;
};

const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt10M = file.size / 1024 / 1024 < 10;

    if (!isImage) {
        ElMessage.error('上传文件只能是图片格式！');
        return false;
    }
    if (!isLt10M) {
        ElMessage.error('上传图片大小不能超过 10MB！');
        return false;
    }
    return true;
};

const handleExceed = () => {
    // 已移除单图片限制，此方法不再需要
};

// 处理拖拽进入
const handleDragEnter = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const target = e.currentTarget;
    if (target) {
        target.classList.add('drag-over');
    }
};

// 处理拖拽离开
const handleDragLeave = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const target = e.currentTarget;
    if (target) {
        target.classList.remove('drag-over');
    }
};

// 处理拖拽上传
const handleDrop = (e, type) => {
    e.preventDefault();
    e.stopPropagation();
    // 移除拖拽样式
    const target = e.currentTarget;
    if (target) {
        target.classList.remove('drag-over');
    }
    const files = Array.from(e.dataTransfer.files);
    
    // 过滤出图片文件
    const imageFiles = files.filter(file => file.type.startsWith('image/'));
    
    if (imageFiles.length === 0) {
        ElMessage.error('请拖拽图片文件！');
        return;
    }
    
    // 检查限制
    const limit = type === 'carFrontPhoto' || type === 'carRearPhoto' ? 1 : undefined;
    if (limit) {
        // 单图片：如果已有图片，先清空
        if (ruleForm[type].length > 0) {
            ruleForm[type] = [];
        }
        // 只处理第一个文件
        const file = imageFiles[0];
        if (!beforeAvatarUpload(file)) {
            return;
        }
        
        // 创建 FormData 并上传
        const formData = new FormData();
        formData.append('file', file);
        
        // 使用 fetch 上传文件
        fetch('/api/common/upload', {
            method: 'POST',
            headers: {
                'Authorization': importHeaders.Authorization
            },
            body: formData
        })
        .then(response => response.json())
        .then(res => {
            // 创建文件对象
            const fileObj = {
                uid: Date.now() + Math.random(),
                name: file.name,
                status: 'success',
                url: ''
            };
            
            // 调用成功处理函数
            handleAvatarSuccess(res, fileObj, [fileObj], type);
        })
        .catch(error => {
            console.error('上传失败:', error);
            ElMessage.error('上传失败，请稍后重试');
        });
    } else {
        // 多图片：处理所有文件
        imageFiles.forEach((file, index) => {
            // 验证文件
            if (!beforeAvatarUpload(file)) {
                return;
            }
            
            // 创建 FormData 并上传
            const formData = new FormData();
            formData.append('file', file);
            
            // 使用 fetch 上传文件
            fetch('/api/common/upload', {
                method: 'POST',
                headers: {
                    'Authorization': importHeaders.Authorization
                },
                body: formData
            })
            .then(response => response.json())
            .then(res => {
                // 创建文件对象
                const fileObj = {
                    uid: Date.now() + Math.random() + index,
                    name: file.name,
                    status: 'success',
                    url: ''
                };
                
                // 获取当前文件列表并添加新文件
                const currentFileList = [...ruleForm[type]];
                currentFileList.push(fileObj);
                
                // 调用成功处理函数
                handleAvatarSuccess(res, fileObj, currentFileList, type);
            })
            .catch(error => {
                console.error('上传失败:', error);
                ElMessage.error('上传失败，请稍后重试');
            });
        });
    }
};

const onClickSave = async () => {
    await formDataRef.value.validate(async (valid) => {
        if (valid) {
            data.saveLoading = true;
            
            try {
                // 将行驶证和备案码的图片数组转换为 JSON 字符串
                const drivingLicensePhotoJson = ruleForm.drivingLicensePhoto.length > 0 
                    ? JSON.stringify(ruleForm.drivingLicensePhoto.map(item => item.url))
                    : null;
                const recordCodeJson = ruleForm.recordCode.length > 0 
                    ? JSON.stringify(ruleForm.recordCode.map(item => item.url))
                    : null;
                
                const formData = {
                    id: data.isEdit ? ruleForm.id : null,
                    licensePlate: ruleForm.licensePlate,
                    carFrontPhoto: ruleForm.carFrontPhoto.length > 0 ? ruleForm.carFrontPhoto[0].url : null,
                    carRearPhoto: ruleForm.carRearPhoto.length > 0 ? ruleForm.carRearPhoto[0].url : null,
                    drivingLicensePhoto: drivingLicensePhotoJson,
                    recordCode: recordCodeJson,
                    remark: ruleForm.remark,
                };
                

                const res = data.isEdit ? await vehicleEdit(formData) : await vehicleAdd(formData);
                
                if (res.code === 200) {
                    ElMessage.success(data.isEdit ? '编辑成功' : '新增成功');
                    handleClose();
                    emits('success');
                } else {
                    ElMessage.error(res.msg || '操作失败');
                }
            } catch (error) {
                console.error('保存失败:', error);
                ElMessage.error('保存失败，请稍后重试');
            } finally {
                data.saveLoading = false;
            }
        }
    });
};

const handleClose = () => {
    formDataRef.value?.resetFields();
    ruleForm.id = null;
    ruleForm.licensePlate = '';
    ruleForm.carFrontPhoto = [];
    ruleForm.carRearPhoto = [];
    ruleForm.drivingLicensePhoto = [];
    ruleForm.recordCode = [];
    ruleForm.remark = '';
    data.dialogVisible = false;
    data.isEdit = false;
};

const open = (row = null) => {
    data.dialogVisible = true;
    data.isEdit = !!row;
    data.title = row ? '编辑车辆' : '新增车辆';
    
    if (row) {
        ruleForm.id = row.id;
        ruleForm.licensePlate = row.licensePlate || '';
        ruleForm.carFrontPhoto = row.carFrontPhoto ? [{ url: row.carFrontPhoto }] : [];
        ruleForm.carRearPhoto = row.carRearPhoto ? [{ url: row.carRearPhoto }] : [];
        
        // 行驶证照片：尝试解析 JSON 数组，如果失败则按单图片处理
        if (row.drivingLicensePhoto) {
            const drivingLicenseValue = row.drivingLicensePhoto;
            console.log('[VEHICLE] 行驶证照片原始数据:', drivingLicenseValue, typeof drivingLicenseValue);
            // 检查是否是 JSON 字符串格式（以 [ 开头）
            if (typeof drivingLicenseValue === 'string' && drivingLicenseValue.trim().startsWith('[')) {
                try {
                    const parsed = JSON.parse(drivingLicenseValue);
                    console.log('[VEHICLE] 行驶证照片解析结果:', parsed);
                    if (Array.isArray(parsed) && parsed.length > 0) {
                        ruleForm.drivingLicensePhoto = parsed.map((url, index) => {
                            // 确保 url 是字符串类型
                            const urlStr = typeof url === 'string' ? url : String(url);
                            console.log(`[VEHICLE] 行驶证照片 ${index}:`, urlStr);
                            return { 
                                url: urlStr, 
                                uid: Date.now() + index, 
                                name: `行驶证${index + 1}.jpg` 
                            };
                        });
                        console.log('[VEHICLE] 行驶证照片最终数据:', ruleForm.drivingLicensePhoto);
                    } else {
                        ruleForm.drivingLicensePhoto = [];
                    }
                } catch (e) {
                    console.error('解析行驶证照片 JSON 失败:', e, drivingLicenseValue);
                    // 解析失败，按单图片处理（兼容旧数据）
                    ruleForm.drivingLicensePhoto = [{ url: drivingLicenseValue }];
                }
            } else {
                // 不是 JSON 格式，按单图片处理（兼容旧数据）
                console.log('[VEHICLE] 行驶证照片不是 JSON 格式，按单图片处理');
                ruleForm.drivingLicensePhoto = [{ url: drivingLicenseValue }];
            }
        } else {
            ruleForm.drivingLicensePhoto = [];
        }
        
        // 牧运通备案码：尝试解析 JSON 数组，如果失败则按单图片处理
        if (row.recordCode) {
            const recordCodeValue = row.recordCode;
            console.log('[VEHICLE] 备案码原始数据:', recordCodeValue, typeof recordCodeValue);
            // 检查是否是 JSON 字符串格式（以 [ 开头）
            if (typeof recordCodeValue === 'string' && recordCodeValue.trim().startsWith('[')) {
                try {
                    const parsed = JSON.parse(recordCodeValue);
                    console.log('[VEHICLE] 备案码解析结果:', parsed);
                    if (Array.isArray(parsed) && parsed.length > 0) {
                        ruleForm.recordCode = parsed.map((url, index) => {
                            // 确保 url 是字符串类型
                            const urlStr = typeof url === 'string' ? url : String(url);
                            console.log(`[VEHICLE] 备案码 ${index}:`, urlStr);
                            return { 
                                url: urlStr, 
                                uid: Date.now() + index + 1000, 
                                name: `备案码${index + 1}.jpg` 
                            };
                        });
                        console.log('[VEHICLE] 备案码最终数据:', ruleForm.recordCode);
                    } else {
                        ruleForm.recordCode = [];
                    }
                } catch (e) {
                    console.error('解析备案码 JSON 失败:', e, recordCodeValue);
                    // 解析失败，按单图片处理（兼容旧数据）
                    ruleForm.recordCode = [{ url: recordCodeValue }];
                }
            } else {
                // 不是 JSON 格式，按单图片处理（兼容旧数据）
                console.log('[VEHICLE] 备案码不是 JSON 格式，按单图片处理');
                ruleForm.recordCode = [{ url: recordCodeValue }];
            }
        } else {
            ruleForm.recordCode = [];
        }
        
        ruleForm.remark = row.remark || '';
    }
};

defineExpose({ open });
</script>

<style scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

/* 拖拽上传样式 */
:deep(.upload-drag-area) {
    position: relative;
}

:deep(.upload-drag-area .el-upload--picture-card) {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
}

:deep(.upload-drag-area .el-upload--picture-card:hover) {
    border-color: #409eff;
    background-color: #f5f7fa;
}

:deep(.upload-drag-area .el-upload-list--picture-card) {
    display: inline-block;
    vertical-align: top;
}

/* 拖拽时的视觉反馈 */
:deep(.upload-drag-area.drag-over .el-upload--picture-card) {
    border-color: #409eff;
    background-color: #ecf5ff;
    border-style: solid;
}

:deep(.upload-drag-area.drag-over .el-upload--picture-card .el-icon) {
    color: #409eff;
}
</style>

