<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <el-button @click="handleResetClick()"> 重置 </el-button>
            <el-button type="primary" @click="handleConfirmClick()"> 提交 </el-button>
        </div>
        <div class="card table-main">
            <div style="width: 900px">
                <rulesForm
                    :ruleForm="dataStore.editRuleForm"
                    :formData="dataStore.editFormData"
                    :rules="dataStore.rules"
                    ref="formRef"
                    @handleSelectChangeEmits="handleSelectChangeEmits"
                >
                    <el-button type="primary" size="small" style="margin-bottom: 10px" @click="handleEditAdd">添加行</el-button>
                    <FormTable :columns="dataStore.editColumns" :tableData="dataStore.editTableData" :height="200">
                        <template #up="scope">
                            <el-upload
                                action="#"
                                class="upload"
                                :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, scope.row)"
                                :on-error="excelUploadError"
                                :accept="filesType!.join(',')"
                                ref="uploadRef"
                            >
                                <el-button type="primary" size="small">文件上传</el-button>
                            </el-upload>
                            <!-- 显示文件名 -->
                            <div v-if="scope.row.file_path" style="display: flex; align-items: center; justify-content: center">
                                <span style="padding: 0 10px; margin-right: 20px; border: 1px solid #eeeeee">
                                    {{ scope.row.file_path }}</span
                                >
                                <el-icon style="cursor: pointer" @click="handleDelete(scope.row)"><Delete /></el-icon>
                            </div>
                        </template>

                        <template #operation="scope">
                            <el-button type="danger" size="small" @click="handleEditDelete(scope)">删除行</el-button>
                        </template>
                    </FormTable>
                </rulesForm>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import rulesForm from "@/components/rulesForm/index.vue";
import FormTable from "@/components/FormTable/index.vue";
import { EDIT_TABLE_DATA, RULES, EDIT_RULE_FORM, EDIT_FORM_DATA } from "./constant/index";
import { useMsg } from "@/hooks/useMsg";
import { Delete } from "@element-plus/icons-vue";
const $route = useRoute();
import { getCategorysApi } from "@/api/modules/downloadClass";
import { recursiveCompare } from "@/utils/recursiveCompare";
import { addLabelValue } from "@/utils/addLabelValue";
import { ElNotification } from "element-plus";
//深拷贝方法
import { cloneDeep } from "lodash-es";
import {
    getAttachmentUpFileApi,
    getAttachmentSaveApi,
    getAttachmentUpdateApi,
    getAttachmentReadApi
} from "@/api/modules/downloadList";
//上传文件格式
const filesType = ref([".inf", ".sys", ".dll", ".exe", ".cat", ".ko", ".rpm", ".kext", ".zip", ".bin‌", ".rar", ".tar", ".gz"]);
const dataStore = reactive<any>({
    rules: cloneDeep(RULES), //抽屉表单验证
    editRuleForm: cloneDeep(EDIT_RULE_FORM),
    editFormData: cloneDeep(EDIT_FORM_DATA), //抽屉表单配置项
    editTableData: cloneDeep(EDIT_TABLE_DATA), //添加|编辑里的表格数据
    editColumns: [
        {
            label: "文件",
            prop: "file_path",
            disabled: false,
            formType: "up",
            width: "350",
            align: "left"
        },
        {
            label: "文件格式",
            prop: "file_ext",
            disabled: false,
            formType: "input",
            maxLength: 50,
            width: "150"
        },
        //operation
        {
            label: "按钮名称",
            prop: "btn_name",
            disabled: false,
            formType: "input",
            maxLength: 50,
            width: "150"
        },
        {
            label: "操作",
            prop: "operation",

            width: "112"
        }
    ] //添加|编辑里的表格配置项
});
const formRef: any = ref(null);
const uploadRef = ref<any>(null);
// 文件上传
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 isExcel && fileSize;
};

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

// 上传成功提示
const excelUploadSuccess = (response: any, row: any) => {
    console.log(response, "=response=");
    // 假设后端返回的数据中有文件路径和文件格式
    if (response?.code === 0) {
        row.file_path = response.data.path; // 假设后端返回的文件路径在 data.path 中
    }
    ElNotification({
        title: "温馨提示",
        message: `文件上传成功！`,
        type: "success"
    });
};
// 文件数超出提示
const handleExceed = () => {
    ElNotification({
        title: "温馨提示",
        message: "最多只能上传一个文件！",
        type: "warning"
    });
};
//添加
const getAttachmentSave = async () => {
    const result = await getAttachmentSaveApi({ ...dataStore.editRuleForm, attach: JSON.stringify(dataStore.editTableData) });
    if (result?.code === 0) {
        useMsg("success", result?.msg);
    }
};
// //更新
const getAttachmentUpdate = async () => {
    const result = await getAttachmentUpdateApi({ ...dataStore.editRuleForm, attach: JSON.stringify(dataStore.editTableData) });
    if (result?.code === 0) {
        useMsg("success", result?.msg);
    }
};
//抽屉确认
const handleConfirmClick = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef!.validate((valid: any) => {
        if (valid) {
            console.log("submit!");
            $route.query.title === "添加下载" ? getAttachmentSave() : getAttachmentUpdate();
        } else {
            console.log("error submit!");
            return false;
        }
    });
};
//抽屉重置
const handleResetClick = () => {
    if ($route.query.title === "添加下载") {
        resetFields();
    } else {
        getAttachmentRead();
    }
};
//重置验证状态
const resetFields = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef.resetFields();
};

const handleEditDelete = (scope: any) => {
    dataStore.editTableData.splice(scope.$index, 1);
};
const handleEditAdd = () => {
    dataStore.editTableData.push({
        file_path: "", //文件路径
        btn_name: "", //按钮名字
        file_ext: "" //文件格式
    });
};

//详情
const getAttachmentRead = async () => {
    let id = $route.query.id;
    if (!id) {
        return;
    }
    const result = await getAttachmentReadApi(id);
    if (result?.code === 0) {
        dataStore.editRuleForm = result?.data;
        dataStore.editTableData = result?.data.attach;
        //recursiveCompare
        let is = dataStore.editFormData[1].options.some((item: any) =>
            recursiveCompare(item, dataStore.editRuleForm.category_id)
        );
        console.log(is, "========is==========");
        // let is = dataStore.editFormData[1].options.some((item: any) => {
        //     console.log(item.id);
        //     console.log(dataStore.editRuleForm.category_id);
        //     return item.value == dataStore.editRuleForm.category_id;
        // });
        dataStore.editRuleForm.category_id1 = is ? dataStore.editRuleForm.category_id : dataStore.editRuleForm.category_name;
    }
};
getAttachmentRead();
const handleSelectChangeEmits = (value: any) => {
    if (value.prop === "category_id1") {
        dataStore.editRuleForm.category_id = value.id;
    }
};

//分类
const getCategorys = async () => {
    const result = await getCategorysApi({ is_show: 1 });

    if (result?.code === 0) {
        dataStore.editFormData[1].options = addLabelValue(result?.data);
    }
};
getCategorys();
const handleDelete = async (row: any) => {
    row.file_path = "";
    // 清空上传组件的文件列表

    if (uploadRef.value) {
        uploadRef.value.clearFiles();
    }

    ElNotification({
        title: "温馨提示",
        message: `文件已删除！`,
        type: "success"
    });
};
</script>

<style scoped></style>
