<template>
    <div v-for="(config, configIndex) in configs" :key="configIndex">
        <el-form-item :label="config.title" v-if="config.type === 'radio'">
            <el-radio-group v-model="config.value">
                <el-radio
                    v-for="extraItem in config.extra"
                    :key="extraItem.value"
                    :label="extraItem.value"
                    @change="handleRadioChange(extraItem, config)"
                >
                    {{ extraItem.name }}
                </el-radio>
            </el-radio-group>
            <span style="margin-left: 20px; color: #999999" v-if="config.remark">({{ config.remark }})</span>
        </el-form-item>
        <el-form-item :label="config.title" v-if="config.type === 'text'">
            <el-input v-model="config.value" style="width: 400px" :placeholder="config.remark"> </el-input>
        </el-form-item>
        <el-form-item v-if="config.type === 'select'" :label="config.title">
            <el-select v-model="config.value" :placeholder="config.remark">
                <el-option
                    v-for="extraItem in config.extra"
                    :key="extraItem.value"
                    :label="extraItem.name"
                    :value="extraItem.value"
                >
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item v-if="config.type === 'checkbox'" :label="config.title">
            <el-checkbox-group v-model="config.value">
                <el-checkbox v-for="extraItem in config.extra" :key="extraItem.value" :label="extraItem.value">
                    {{ extraItem.name }}
                </el-checkbox>
            </el-checkbox-group>
            <span style="margin-left: 20px; color: #999999" v-if="config.remark">({{ config.remark }})</span>
        </el-form-item>
        <el-form-item v-if="config.type === 'image'" :label="config.title">
            <UploadImg v-model:image-url="config.value" />
        </el-form-item>
        <el-form-item v-if="config.type === 'textarea'" :label="config.title">
            <el-input v-model="config.value" type="textarea" :rows="8" style="width: 400px" :placeholder="config.remark">
            </el-input>
        </el-form-item>

        <el-form-item v-if="config.type === 'file'" :label="config.title">
            <el-upload
                action="#"
                :limit="1"
                :multiple="true"
                :show-file-list="false"
                :http-request="param => uploadExcel(param)"
                :before-upload="file => beforeExcelUpload(file)"
                :on-exceed="handleExceed"
                :on-success="(response, file, fileList) => excelUploadSuccess(response, config)"
                :on-error="excelUploadError"
                :accept="filesType!.join(',')"
                ref="uploadRef"
            >
                <el-button type="primary" size="small" style="display: block"> 文件上传 </el-button>
                <template #tip>
                    <!-- 显示上传成功后的文件路径 -->
                    <div v-if="config.value" @click.stop style="display: flex; align-items: center; justify-content: center">
                        <span style="padding: 0 10px; margin-right: 20px; border: 1px solid #eeeeee"> {{ config.value }}</span>
                        <el-icon style="cursor: pointer" @click="handleDelete(config, configIndex)"><Delete /></el-icon>
                    </div>
                </template>
            </el-upload>
        </el-form-item>
        <template v-for="extraItem in filteredExtra(config)" :key="extraItem.value">
            <recursive-form
                :configs="extraItem.children"
                v-if="extraItem.children && extraItem.children.length > 0 && config.value.includes(extraItem.value)"
            >
            </recursive-form>
        </template>
    </div>
</template>

<script setup lang="ts" name="RecursiveForm">
import { ref, computed } from "vue";
import RecursiveForm from "./RecursiveForm.vue";
import UploadImg from "@/components/Upload/UploadImg.vue";
import { getAttachmentUpFileApi } from "@/api/modules/downloadList";
import { ElNotification } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
// 上传文件格式
const filesType = ref([".inf", ".sys", ".dll", ".exe", ".cat", ".ko", ".rpm", ".kext", ".zip", ".bin", ".rar", ".tar", ".gz"]);

defineProps<{
    configs: any;
}>();
const uploadRef = ref<any>(null);

const handleRadioChange = (extraItem: any, config: any) => {
    // 当单选框选项改变时，可在这里添加额外逻辑
    console.log(extraItem, "=extraItem=");
    console.log(config, "=config=");
};

// 文件上传
const uploadExcel = async (param: any) => {
    let excelFormData = new FormData();
    excelFormData.append("attachment", param.file);
    const result = await getAttachmentUpFileApi(excelFormData);
    return result;
};

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * @param row 当前行数据
 * */
const beforeExcelUpload = (file: any) => {
    const maxSize = 50 * 1024 * 1024;
    if (file.size > maxSize) {
        setTimeout(() => {
            ElNotification({
                title: "温馨提示",
                message: `上传文件大小不能超过 ${50}MB！`,
                type: "warning"
            });
        }, 0);
        return false;
    }
    return true;
};

// 上传错误提示
const excelUploadError = () => {
    ElNotification({
        title: "温馨提示",
        message: `文件上传失败，请您重新上传！`,
        type: "error"
    });
};

// 上传成功提示
const excelUploadSuccess = (response: any, config: any) => {
    // 假设后端返回的数据中有文件路径和文件格式
    if (response?.code === 0) {
        // 这里简单打印信息，你可根据实际情况修改
        console.log("文件上传成功，文件路径:", response.data.path);
        // 将文件路径赋值给 config.value
        config.value = response.data.path;
    }
    ElNotification({
        title: "温馨提示",
        message: `文件上传成功！`,
        type: "success"
    });
};

// 文件数超出提示
const handleExceed = (files: any) => {
    console.log(files);
    ElNotification({
        title: "温馨提示",
        message: "最多只能上传一个文件！",
        type: "warning"
    });
};

// 计算属性，用于过滤 extra 数组
const filteredExtra: any = computed(() => {
    return (config: any) => {
        if (config.type === "radio" || config.type === "select") {
            return config.extra.filter((extraItem: any) => config.value.includes(extraItem.value));
        }
        return config.extra;
    };
});
const handleDelete = (config: any, index: any) => {
    config.value = "";
    console.log(index, "======index========");
    // 清空上传组件的文件列表
    if (uploadRef.value) {
        uploadRef.value[index].clearFiles();
    }
    ElNotification({
        title: "温馨提示",
        message: `文件已删除！`,
        type: "success"
    });
};
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>
