<template>
    <u-modal
        :show="show"
        :title="dialogTitle"
        :showConfirmButton="false"
        :showCancelButton="false"
        @close="handleClose"
        :closeOnClickOverlay="false"
    >
        <view class="dialog-content">
            <u-form :model="formData" :rules="rules" ref="formRef" label-width="auto">
                <!-- 资源基本信息 -->
                <!-- <view class="section-title">资源基本信息</view> -->
                <u-form-item label="" prop="fileName">
                    <u-input v-model="formData.fileName" placeholder="请输入文件名称" border="bottom" />
                </u-form-item>

                <!-- <u-form-item label="文件类型" prop="fileType" required>
                    <u-input v-model="formData.fileType" placeholder="请选择文件类型" border="bottom"
                        @click="showFileTypePicker = true" />
                </u-form-item> -->

                <u-form-item label="上传文件" prop="file" required>
                    <view class="file-upload">
                        <u-button v-if="!formData.file" @click="chooseFile" type="primary" class="ui-button">
                            <text class="font_10">选择文件</text>
                        </u-button>
                        <view v-else class="file-info">
                            <view class="file-name-container">
                                <text class="file-name">{{ formData.file.name }}</text>
                                <text class="remove-icon" @click="removeFile">×</text>
                            </view>
                        </view>
                    </view>
                </u-form-item>

                <!-- 操作按钮 -->
                <view class="dialog-buttons">
                    <u-button
                        type="primary"
                        @click="handleSubmit"
                        :loading="loading"
                        size="normal"
                        class="submit-btn"
                        color="var(--fui-color-success)"
                    >
                        {{ submitButtonText }}
                    </u-button>
                    <u-button @click="handleClose" size="normal" class="cancel-btn">取消</u-button>
                </view>
            </u-form>
        </view>
    </u-modal>
</template>

<script setup lang="ts">
    import { ref, reactive, watch, computed } from 'vue'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as WodeAPI from '@/api/model/wode'
    // 定义Props
    interface Props {
        show: boolean
        editData?: any
    }

    const props = withDefaults(defineProps<Props>(), {
        show: false,
        editData: null,
    })

    // 定义Emits
    const emit = defineEmits<{
        'update:show': [value: boolean]
        submit: [data: any]
        close: []
        submitSuccess: []
    }>()

    // 表单引用
    const formRef = ref()
    const loading = ref(false)
    const uploading = ref(false)
    const showFileTypePicker = ref(false)

    // 文件类型选项
    const fileTypeOptions = [
        { value: 'doc', text: 'Word文档' },
        { value: 'xls', text: 'Excel表格' },
        { value: 'ppt', text: 'PPT演示' },
        { value: 'pdf', text: 'PDF文档' },
        { value: 'img', text: '图片文件' },
        { value: 'video', text: '视频文件' },
        { value: 'audio', text: '音频文件' },
        { value: 'zip', text: '压缩文件' },
        { value: 'other', text: '其他文件' },
    ]

    // 表单数据
    const formData = reactive({
        fileName: '',
        fileType: '',
        fileTypeText: '',
        file: null,
        fileSrc: '',
    })

    // 计算属性
    const dialogTitle = computed(() => {
        return props.editData ? '编辑资源' : '上传资源'
    })

    const submitButtonText = computed(() => {
        return props.editData ? '保存' : '上传'
    })

    // 表单验证规则
    const rules = {
        fileName: [
            { required: true, message: '请输入文件名称', trigger: 'blur' },
            { min: 2, max: 50, message: '文件名称长度在2-50个字符之间', trigger: 'blur' },
        ],
        fileType: [{ required: true, message: '请选择文件类型', trigger: 'change' }],
        file: [
            {
                required: true,
                message: '请选择文件',
                trigger: 'change',
                validator: (rule, value, callback) => {
                    if (!value) {
                        callback(new Error('请选择文件'))
                    } else {
                        callback()
                    }
                },
            },
        ],
    }

    // 监听显示状态
    watch(
        () => props.show,
        (newVal) => {
            if (newVal && props.editData) {
                // 编辑模式，填充数据
                resetFormData()
                loadEditData()
            } else if (newVal) {
                // 添加模式，重置表单
                resetFormData()
            }
        },
    )

    // 重置表单数据
    const resetFormData = () => {
        formData.fileName = ''
        formData.fileType = ''
        formData.fileTypeText = ''
        formData.file = null
        formData.fileSrc = ''
        // 清除验证状态
        if (formRef.value) {
            formRef.value.resetFields()
        }
    }

    // 加载编辑数据
    const loadEditData = () => {
        if (!props.editData) return

        formData.fileName = props.editData.fileName || ''
        formData.fileType = props.editData.fileType || ''
        formData.fileTypeText = props.editData.fileTypeText || ''

        // 编辑模式不修改文件本身
        // formData.file = null
    }
    const uplpoadFile = ref(null)
    // 选择文件
    const chooseFile = () => {
        uni.chooseFile({
            count: 1,
            extension: ['*'],
            success: (res) => {
                uplpoadFile.value = res
                const tempFilePaths = res.tempFilePaths
                const tempFiles = res.tempFiles
                console.log(tempFiles)
                if (tempFiles && tempFiles.length > 0) {
                    if (!formData.fileName) {
                        formData.fileName = tempFiles[0].name || ''
                    }

                    // 根据文件扩展名设置文件类型
                    const fileName = tempFiles[0].name || ''
                    const ext = fileName.split('.').pop()?.toLowerCase() || ''
                    const fileType = getFileTypeByExt(ext)
                    formData.file = tempFiles[0]
                    formData.fileType = fileType.value
                    formData.fileTypeText = fileType.text

                    // 文件选择后触发验证
                    if (formRef.value) {
                        formRef.value.validateField('file')
                    }
                }
            },
            fail: (err) => {
                console.error('选择文件失败:', err)
                uni.showToast({ title: '选择文件失败', icon: 'none' })
                uploading.value = false
            },
        })
    }

    // 移除文件
    const removeFile = () => {
        formData.file = null
        // 移除文件后触发验证
        if (formRef.value) {
            formRef.value.validateField('file')
        }
    }

    // 根据文件扩展名获取文件类型
    const getFileTypeByExt = (ext) => {
        const map = {
            doc: 'doc',
            docx: 'doc',
            xls: 'xls',
            xlsx: 'xls',
            ppt: 'ppt',
            pptx: 'ppt',
            pdf: 'pdf',
            jpg: 'img',
            jpeg: 'img',
            png: 'img',
            gif: 'img',
            mp4: 'video',
            avi: 'video',
            mp3: 'audio',
            wav: 'audio',
            zip: 'zip',
            rar: 'zip',
            '7z': 'zip',
        }

        const type = map[ext] || 'other'
        return fileTypeOptions.find((item) => item.value === type) || fileTypeOptions[8]
    }
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    const toastRef = ref()
    // 提交表单
    const handleSubmit = async () => {
        try {
            console.log(formData)
            // 先进行表单验证
            const valid = await formRef.value.validate()
            if (!valid) {
                // 验证失败，返回
                return
            }

            // 额外校验文件是否存在
            if (!formData.file) {
                uni.showToast({
                    title: '请选择文件',
                    icon: 'none',
                })
                return
            }

            loading.value = true

            // 准备提交数据
            const submitData = {
                fileName: formData.fileName,
                fileType: formData.fileType,
                fileSize: formData.file ? formData.file.size : 0,
                fileSrc: formData.fileSrc,
                // createTime: new Date().toLocaleString()
            }

            // API留空
            console.log('上传资源数据:', submitData)
            uni.uploadFile({
                url: globSetting.apiUrl + globSetting.urlPrefix + '/sys/common/upload', // 直接使用上传接口URL
                filePath: uplpoadFile.value.tempFilePaths[0],
                name: 'file',
                formData: {
                    biz: 'temp',
                },
                header: {
                    'X-Access-Token': userStore.getToken,
                },
                success: (res) => {
                    if (res.statusCode === 200) {
                        const data = JSON.parse(res.data)
                        if (data.code === 200 || data.code === 0) {
                            submitData.fileSrc = data.message
                            WodeAPI.addResource(submitData)
                                .then((res) => {
                                    toastRef.value.show({
                                        type: 'success',
                                        text: `上传成功`,
                                    })
                                    // emit('update:show', false)
                                    emit('submitSuccess')
                                })
                                .catch((error) => {
                                    uni.showToast({
                                        title: error.message || '提交失败，请重试',
                                        icon: 'none',
                                        duration: 2000,
                                    })
                                })
                                .finally(() => {
                                    loading.value = false
                                })
                        }
                    }
                },
                fail: () => {
                    toastRef.value.show({
                        type: 'error',
                        text: '上传失败',
                    })
                },
            })
            // 模拟上传过程
            // setTimeout(() => {
            //     uni.showToast({ title: '操作成功', icon: 'success' })
            //     emit('update:show', false)
            //     emit('submitSuccess')
            // }, 1500)
        } catch (error) {
            console.log('提交失败:', error)
            uni.showToast({
                title: '操作失败',
                icon: 'none',
                duration: 2000,
            })
        } finally {
            loading.value = false
        }
    }

    // 关闭弹窗
    const handleClose = () => {
        emit('update:show', false)
        emit('close')
    }
</script>

<style lang="scss" scoped>
    .dialog-content {
        padding: 10rpx 30rpx;
        width: 90%;
        max-height: 80vh;
        overflow-y: auto;
    }

    .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 30rpx;
        border-left: 6rpx solid #5db66f;
        padding-left: 12rpx;
    }

    .dialog-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 50rpx;
        gap: 20rpx;
    }

    .submit-btn,
    .cancel-btn {
        flex: 1;
    }

    .file-upload {
        width: 100%;
    }

    .file-info {
        padding: 20rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;

        .file-name-container {
            position: relative;
            display: flex;
            align-items: center;
        }

        .file-name {
            flex: 1;
            width: 40rpx;
            font-size: 28rpx;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding-right: 40rpx;
        }

        .remove-icon {
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            font-size: 36rpx;
            color: #999;
            width: 40rpx;
            height: 40rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            &:active {
                color: #ff4d4f;
                background-color: rgba(255, 77, 79, 0.1);
                border-radius: 50%;
            }
        }
    }

    // 模态框样式调整
    ::v-deep .u-modal {
        background: linear-gradient(0deg, rgba(93, 182, 111, 0) 50%, rgba(93, 182, 111, 0.25) 100%);

        .u-modal__content {
            border-radius: 20rpx;
            padding: 20rpx 0rpx;
        }

        .u-modal__header {
            border-bottom: 2rpx solid #f0f0f0;
            padding: 30rpx;

            .u-modal__header__title {
                font-size: 32rpx;
                font-weight: 600;
                color: #333;
            }
        }
    }

    .ui-button {
        padding: 16rpx 0;
        background-color: #5db66f26;
        border-radius: 10rpx;
        mix-blend-mode: NOTTHROUGH;
        border-color: #5db66f26;

        .font_10 {
            font-size: 24rpx;
            line-height: 24rpx;
            color: #16a34a;
        }
    }
</style>
