<template>
    <el-dialog
        v-model="dialogVisible"
        title="新增资源"
        width="520px"
        :destroy-on-close="true"
        :close-on-click-modal="!submitting"
        draggable
    >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
            <el-form-item label="资源名称" prop="name">
                <el-input v-model="form.name" maxlength="250" placeholder="请输入资源名称" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" maxlength="250" placeholder="请输入备注" type="textarea" :rows="3" />
            </el-form-item>
            <el-form-item label="文件" prop="file">
                <el-upload
                    ref="uploadRef"
                    action="#"
                    :auto-upload="false"
                    :limit="1"
                    accept=".mp4,video/mp4"
                    :file-list="fileList"
                    :on-change="handleFileChange"
                    :on-remove="handleFileRemove"
                    :on-exceed="handleExceed"
                >
                    <el-button type="primary" :icon="Upload">选择文件</el-button>
                    <template #tip>
                        <div class="el-upload__tip">仅支持 MP4 文件，最大 250MB</div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button :disabled="submitting" @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="submitting" @click="submit">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
    ElMessage,
    genFileId,
    type FormInstance,
    type FormRules,
    type UploadFile,
    type UploadInstance,
    type UploadProps,
    type UploadRawFile
} from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { addResourceManage } from '@/api/resourceManage'

const MAX_FILE_SIZE = 250 * 1024 * 1024

const props = defineProps<{
    refreshTable?: () => void
}>()

const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadFile[]>([])

const form = reactive<{
    name: string
    remark: string
    file: File | null
}>({
    name: '',
    remark: '',
    file: null
})

const validateFile = (_rule: unknown, value: File | null, callback: (error?: Error) => void) => {
    if (!value) {
        callback(new Error('请选择 MP4 文件'))
        return
    }
    callback()
}

const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
    remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
    file: [{ validator: validateFile, trigger: 'change' }]
})

const open = () => {
    form.name = ''
    form.remark = ''
    form.file = null
    fileList.value = []
    dialogVisible.value = true
}

const isValidMp4 = (file: File) => {
    return file.name.toLowerCase().endsWith('.mp4') && (!file.type || file.type === 'video/mp4')
}

const handleFileChange: UploadProps['onChange'] = uploadFile => {
    const raw = uploadFile.raw
    if (!raw) return
    if (!isValidMp4(raw)) {
        ElMessage.error('仅支持上传 MP4 文件')
        fileList.value = []
        form.file = null
        return
    }
    if (raw.size > MAX_FILE_SIZE) {
        ElMessage.error('文件大小不能超过 250MB')
        fileList.value = []
        form.file = null
        return
    }
    fileList.value = [uploadFile]
    form.file = raw
    formRef.value?.validateField('file')
}

const handleFileRemove = () => {
    form.file = null
    fileList.value = []
    formRef.value?.validateField('file')
}

const handleExceed: UploadProps['onExceed'] = files => {
    uploadRef.value?.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value?.handleStart(file)
}

const submit = async () => {
    if (!formRef.value) return
    await formRef.value.validate()
    if (!form.file) return

    const formData = new FormData()
    formData.append('name', form.name.trim())
    formData.append('remark', form.remark.trim())
    formData.append('file', form.file)

    submitting.value = true
    try {
        await addResourceManage(formData)
        ElMessage.success('新增成功')
        dialogVisible.value = false
        props.refreshTable?.()
    } finally {
        submitting.value = false
    }
}

defineExpose({
    open
})
</script>
