<template>
    <!-- 小型弹窗，用于完成，删除，保存等操作 -->
    <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
        :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
        <div>
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="110px">
                <el-form-item label="所属案卷">
                    <el-input type="textarea" class="form-item" :value="belongName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="档案名称" prop="contentName">
                    <el-input type="textarea" class="form-item" v-model="form.contentName" clearable show-word-limit
                        placeholder="请输入档案名称" maxlength="64" :disabled="detailStatus"></el-input>
                </el-form-item>
                <el-form-item label="案卷期限" prop="term">
                    <el-input class="form-item" v-model="form.term" clearable show-word-limit placeholder="请输入案卷期限"
                        maxlength="32" :disabled="detailStatus"></el-input>
                </el-form-item>
                <el-form-item label="归档责任单位" prop="unitName">
                    <el-input class="form-item" v-model="form.unitName" clearable show-word-limit
                        placeholder="请输入归档责任单位" maxlength="32" :disabled="detailStatus"></el-input>
                </el-form-item>
                <el-form-item label="所属专业" prop="major">
                    <el-input class="form-item" v-model="form.major" clearable show-word-limit placeholder="请输入所属专业"
                        maxlength="32" :disabled="detailStatus"></el-input>
                </el-form-item>
                <el-form-item label="档案标识代码" prop="markCode">
                    <el-select class="form-item" v-model="form.markCode" :disabled="detailStatus" filterable clearable
                        placeholder="请选择档案标识代码">
                        <el-option v-for="item in dict.type.mark_code" :key="item.value" :label="item.label"
                            :value="item.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文件分类标记" prop="classifyMark">
                    <el-select class="form-item" v-model="form.classifyMark" :disabled="detailStatus" filterable
                        clearable>
                        <el-option v-for="item in classifyMarkList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="附件上传" v-if="!detailStatus" prop="fileList">
                    <el-upload
                        ref="upload"
                        action="#"
                        :file-list="fileList"
                        :on-remove="handleRemove"
                        :on-change="handleFileChange"
                        :before-upload="beforeUpload"
                        :auto-upload="false"
                        :limit="1"
                        accept=".pdf,.jpg,.jpeg,.png">
                        <el-button size="small" type="primary" icon="el-icon-upload" :disabled="fileList.length > 0">选择文件</el-button>
                        <div slot="tip" class="el-upload__tip">
                            <span style="color: #f00;">
                                只能上传PDF和图片文件，且不超过{{maxFileTips}}
                            </span>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button class="clear-btn" @click="handleClose" :disabled="disabled">取消</el-button>
            <el-button type="primary" class="search-btn" :disabled="disabled" v-if="!detailStatus"
                @click="submitForm('ruleForm')">确认</el-button>
        </span>
    </el-dialog>
</template>
<script>
import _ from 'lodash'
import {
    addFileManageRightApi,
    updateFileManageRightApi,
    getFileManageByIdApi
} from '@/api/archivesManagement/fileManager/fileManager.js'
import { getClassifyMarkSelApi } from '@/api/select.js'
export default {
    name: "FileAddTableData",
    props: ["width", "dataForm", "title", "disabled", "isAdd", "rowData", "projectId"],
    dicts: ['mark_code','file_size_limit'],
    data() {
        return {
            lDialog: this.width > 500 ? "w700" : "w500",
            dialogVisible: true,
            isDisabled: true,
            getClassifyMarkSelApi,
            classifyMarkList: [],
            form: {
                contentName: null,
                term: null,
                unitName: null,
                major: null,
                markCode: null,
                classifyMark: null,
            },
            belongName: '',
            loading: null,
            detailStatus: false,
            // 文件上传相关
            fileList: [],
            maxFileSize: 10 * 1024 * 1024, // 默认10MB
            maxFileTips: '10MB',
            rules: {
                contentName: [
                    { required: true, message: '档案名称不能为空', trigger: 'blur' }
                ],
                fileList: [
                    {required: true, validator: (rule, value, callback) => {
                        if (!Array.isArray(this.fileList) || this.fileList.length === 0) {
                            callback(new Error('请上传附件文件'))
                        } else {
                            callback()
                        }
                    }, trigger: 'change' }
                ],
                term: [
                    { required: true, message: '案卷期限不能为空', trigger: 'blur' }
                ],
                unitName: [
                    { required: true, message: '归档责任单位不能为空', trigger: 'blur' }
                ],
                major: [
                    { required: true, message: '所属专业不能为空', trigger: 'blur' }
                ],
                markCode: [
                    { required: true, message: '请选择档案标识代码', trigger: 'change' }
                ],
                classifyMark: [
                    { required: true, message: '请选择文件分类标记', trigger: 'change' }
                ],
            },
            errorObj: {
                contentName: '档案名称',
                term: '案卷期限',
                unitName: '归档责任单位',
                major: '所属专业',
            },
        };
    },
    created() {
        this.initUploadLimit();
        this.initFormData();
    },
    mounted() {
        // 在mounted生命周期中再次尝试获取字典数据
        this.$nextTick(() => {
            this.updateFileSizeLimit();
        });
    },
    watch: {
        // 监听字典数据变化
        'dict.type.file_size_limit': {
            handler(newVal) {
                if (newVal && Array.isArray(newVal) && newVal.length > 0) {
                    this.updateFileSizeLimit();
                }
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        async initUploadLimit(){
            // 加载文件上传限制
            await this.$nextTick();
            this.updateFileSizeLimit();
        },
        // 更新文件大小限制
        updateFileSizeLimit() {
            if (this.dict && this.dict.type && this.dict.type.file_size_limit) {
                const fileSizeLimit = this.dict.type.file_size_limit;
                if (Array.isArray(fileSizeLimit) && fileSizeLimit.length > 0) {
                    const firstValue = fileSizeLimit[0].value;
                    if (firstValue && !isNaN(firstValue)) {
                        this.maxFileSize = parseInt(firstValue) * 1024 * 1024;
                        this.maxFileTips = firstValue + 'MB';
                    }
                }
            }
        },
        /** 初始化表单数据 */
        async initFormData() {
            const res = await getClassifyMarkSelApi();
            this.classifyMarkList = res.data;
            this.belongName = this.rowData.belongName;
            this.detailStatus = this.rowData.detailStatus;
            if ((this.isAdd === 'edit' || this.isAdd === 'detail') && this.rowData) {

                const res2 = await getFileManageByIdApi({id:this.rowData.id,proId:this.projectId});
                const obj =res2.data;

                // 编辑模式：填充表单数据
                this.form = {
                    id: obj.id,
                    contentName: obj.contentName || null,
                    term: obj.term || null,
                    major: obj.major || null,
                    unitName: obj.unitName || null,
                    markCode: obj.markCode || null,
                    classifyMark: obj.classifyMark || null,
                    parentId: this.rowData.parentId || null,
                    level: 5,
                    proId:this.projectId
                };
                const fileList = [{name:obj.fileName,businessId:obj.businessId}];
                this.fileList = fileList;
            } else {
                const id = this.rowData.id;
                const proId = this.projectId;
                const res = await getFileManageByIdApi({id,proId});
                const obj =res.data;
                // 新增模式：重置表单
                this.form = {
                    contentName: null,
                    term: obj.term || null,
                    unitName: obj.unitName || null,
                    major: obj.major || null,
                    markCode: obj.markCode || null,
                    classifyMark: obj.classifyMark || null,
                    parentId: this.rowData.id || null,
                    level: 5,
                    proId:this.projectId
                };
            }
        },
        /*关闭弹窗 */
        handleClose() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
            /* setTimeout(() => {
                this.dialogVisible = true;
            }); */
        },
        /**确认弹窗 */
        sureBtnClick() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
            /* setTimeout(() => {
                this.dialogVisible = true;
            }); */
        },
        /**重置表单*/
        reset() {
            this.form = {
                contentName: null,
                term: null,
                unitName: null,
                major: null,
                markCode: null,
                classifyMark: null,
                parentId: null,
                level: 5
            };
            this.fileList = [];
            this.$nextTick(() => {
                this.$refs.upload && this.$refs.upload.clearFiles();
            });
            this.resetForm("ruleForm");
        },
        handleReuslt(res) {
            this.$modal.msgSuccess(res.msg);
            this.reset();
            this.$emit('handleQuery');
            this.handleClose();
        },
        // 上传前对文件进行验证
        beforeUpload(file) {
            if(!(file.raw instanceof File)){
                return true;
            }
            const isValidType = this.checkFileType(file)
            const isValidSize = this.checkFileSize(file)

            if (!isValidType) {
                this.$message.error('只能上传PDF和图片文件！')
                return false
            }
            if (!isValidSize) {
                this.$message.error('文件大小不能超过`${this.maxFileTips}`！')
                return false
            }

            // 检查是否已有文件
            if (this.fileList.length >= 1) {
                this.$message.warning('只能上传一个文件，请先删除现有文件！')
                return false
            }

            return true
        },
        // 检查文件类型
        checkFileType(file) {
            const allowedTypes = [
                'application/pdf',
                'image/jpeg',
                'image/jpg',
                'image/png',
            ]
            return allowedTypes.includes(file.type)
        },
        // 检查文件大小
        checkFileSize(file) {
            const maxSize = this.maxFileSize || (10 * 1024 * 1024) // 使用动态配置或默认10MB
            return file.size <= maxSize
        },
        // 上传成功
        handleUploadSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.$message.success('文件上传成功！')
            } else {
                this.$message.error(response.msg || '上传失败')
            }
        },
        // 上传失败
        handleUploadError(error, file, fileList) {
            this.$message.error('文件上传失败，请重试')
            console.error('Upload error:', error)
        },
        // 移除文件
        handleRemove(file, fileList) {
            if(!(file instanceof File)){
                this.form.businessId = file.businessId;
            }
            this.fileList = fileList
        },
        // 文件状态改变
        handleFileChange(file, fileList) {
            this.fileList = fileList
            // 主动触发校验
            if (this.$refs.ruleForm) {
                this.$refs.ruleForm.validateField('fileList')
            }
            // console.log('文件列表更新:', fileList.length, '个文件')
        },

        /**验证 */
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 如果有文件需要上传，先上传文件
                    if (this.fileList.length > 0) {
                        this.submitFormData();
                    } else {
                        this.submitFormData();
                    }
                }
            });
        },
        // 提交表单数据
        submitFormData() {
            // 显示遮罩层
            this.loading = this.$loading({
                lock: true,
                text: "数据提交中，请稍候...",
                background: 'rgba(0,0,0,0.5)',
                target: this.$el.querySelector('.el-dialog') || document.body
            })
            let formData = new FormData();
            let params = _.cloneDeep(this.form);
            if(this.fileList.length > 0){
                this.fileList.map(file => {
                    if(file.raw instanceof File){
                        formData.append('file', file.raw);
                    }
                })
            }
            if (this.isAdd === 'add') {
                formData.append('params', JSON.stringify(params));
                // console.log(params);
                addFileManageRightApi(formData).then(res => {
                    this.loading.close();
                    if (res.code === 200) {
                        this.handleReuslt(res);
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                }).catch(error => {
                    this.loading.close();
                    this.$modal.msgError(this.errorMsg(error));
                });
            } else {
                formData.append('params', JSON.stringify(params));
                // console.log(params);
                updateFileManageRightApi(formData).then(res => {
                    this.loading.close();
                    if (res.code === 200) {
                        this.handleReuslt(res);
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                }).catch(error => {
                    this.loading.close();
                    this.$modal.msgError(this.errorMsg(error));
                });
            }
        },
        errorMsg(error) {
            const errorMessage = error.message;
            const errorArr = errorMessage.split('：');
            const errorObjData = errorArr.length > 1 ? JSON.parse(errorArr[1]) : '';
            if(errorObjData){
                return this.errorObj[errorObjData.paramName] + errorArr[0] + ':' + errorObjData.originalValue;
            }else{
                return errorMessage;
            }

        }
    }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
    width: 700px;
}

.w500 ::v-deep .el-dialog {
    width: 500px;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
    // background: #eeeeee;

    .el-dialog__title {
        font-size: 16px;
    }
}

.yxq .el-range-separator {
    margin-right: 7px !important;
}

.el-date-editor--daterange.el-input__inner {
    width: 260px;
}

.form-item {
    width: 100%;
}

.select-style {
    display: flex;
    justify-content: space-between;
}
</style>
