<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"
                >
                    <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"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="行驶证照片" prop="drivingLicensePhoto">
                <el-upload
                    :limit="1"
                    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"
                    :on-exceed="handleExceed"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="牧运通备案码" prop="recordCode">
                <el-upload
                    :limit="1"
                    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"
                    :on-exceed="handleExceed"
                >
                    <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) {
            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 isLt2M = file.size / 1024 / 1024 < 2;

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

const handleExceed = () => {
    ElMessage.warning('最多只能上传一张图片！');
};

const onClickSave = async () => {
    await formDataRef.value.validate(async (valid) => {
        if (valid) {
            data.saveLoading = true;
            
            try {
                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: ruleForm.drivingLicensePhoto.length > 0 ? ruleForm.drivingLicensePhoto[0].url : null,
                    recordCode: ruleForm.recordCode.length > 0 ? ruleForm.recordCode[0].url : null,
                    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 }] : [];
        ruleForm.drivingLicensePhoto = row.drivingLicensePhoto ? [{ url: row.drivingLicensePhoto }] : [];
        ruleForm.recordCode = row.recordCode ? [{ url: row.recordCode }] : [];
        ruleForm.remark = row.remark || '';
    }
};

defineExpose({ open });
</script>

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

