<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">
                    <el-upload
                        ref="upload"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :data="uploadData"
                        :file-list="fileList"
                        :before-upload="beforeUpload"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :on-remove="handleRemove"
                        :auto-upload="false"
                        :limit="1"
                        accept=".pdf,.jpg,.jpeg,.png,.gif,.bmp">
                        <el-button size="small" type="primary" icon="el-icon-upload">选择文件</el-button>
                        <div slot="tip" class="el-upload__tip">
                            只能上传PDF和图片文件，且不超过10MB
                        </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 {
    addArchiveRightApi,
    editArchiveRightApi,
} from '@/api/archivesManagement/index.js'
import { getClassifyMarkSelApi } from '@/api/select.js'
import { getToken } from '@/utils/auth'
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: [],
            uploadUrl: process.env.VUE_APP_BASE_API + '/smartArchives/file/upload',
            uploadHeaders: {
                'Authorization': 'Bearer ' + getToken()
            },
            uploadData: {},
            maxFileSize: 10 * 1024 * 1024, // 默认10MB
            rules: {
                contentName: [
                    { required: true, message: '文件题名不能为空', trigger: 'blur' }
                ],
                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' }
                ],
            },
        };
    },
    created() {
        this.initFormData();
    },
    mounted() {
        // 在mounted生命周期中再次尝试获取字典数据
        this.$nextTick(() => {
            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);
                    }
                }
            }
        });
    },
    methods: {
        /** 初始化表单数据 */
        async initFormData() {
            // 等待字典数据加载完成
            await this.$nextTick();
            const fileSizeLimit = this.dict.type.file_size_limit;
            const firstFileSizeLimit = fileSizeLimit && Array.isArray(fileSizeLimit) && fileSizeLimit.length > 0 ? fileSizeLimit[0].value : null;
            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) {
                // 编辑模式：填充表单数据
                this.form = {
                    id: this.rowData.id,
                    contentName: this.rowData.contentName || null,
                    term: this.rowData.term || null,
                    major: this.rowData.major || null,
                    unitName: this.rowData.unitName || null,
                    markCode: this.rowData.markCode || null,
                    classifyMark: this.rowData.classifyMark || null,
                    parentId: this.rowData.parentId || null,
                    level: 4
                };
            } else {
                // 新增模式：重置表单
                this.form = {
                    contentName: null,
                    term: null,
                    unitName: null,
                    major: null,
                    markCode: null,
                    classifyMark: null,
                    parentId: this.rowData.id || null,
                    level: 4
                };
            }
        },
        /*关闭弹窗 */
        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: 4
            };
            this.fileList = [];
            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) {
            const isValidType = this.checkFileType(file)
            const isValidSize = this.checkFileSize(file)
            
            if (!isValidType) {
                this.$message.error('只能上传PDF和图片文件！')
                return false
            }
            if (!isValidSize) {
                this.$message.error('文件大小不能超过10MB！')
                return false
            }
            
            // 检查是否已有文件
            if (this.fileList.length >= 1) {
                this.$message.warning('只能上传一个文件，请先删除现有文件！')
                return false
            }
            
            // 设置上传数据
            this.uploadData = {
                projectId: this.projectId,
                categoryId: this.form.parentId || 0,
                description: this.form.contentName || ''
            }
            
            return true
        },
        // 检查文件类型
        checkFileType(file) {
            const allowedTypes = [
                'application/pdf',
                'image/jpeg',
                'image/jpg', 
                'image/png',
                'image/gif',
                'image/bmp'
            ]
            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) {
            this.fileList = fileList
        },
        // 上传文件
        uploadFiles() {
            return new Promise((resolve, reject) => {
                if (this.fileList.length === 0) {
                    resolve();
                    return;
                }
                
                let uploadPromises = this.fileList.map(file => {
                    return new Promise((fileResolve, fileReject) => {
                        const formData = new FormData();
                        formData.append('file', file.raw);
                        formData.append('projectId', this.projectId);
                        formData.append('categoryId', this.form.parentId || 0);
                        formData.append('description', this.form.contentName || '');
                        
                        this.$http.post(this.uploadUrl, formData, {
                            headers: this.uploadHeaders
                        }).then(response => {
                            if (response.data.code === 200) {
                                fileResolve(response.data);
                            } else {
                                fileReject(new Error(response.data.msg || '上传失败'));
                            }
                        }).catch(error => {
                            fileReject(error);
                        });
                    });
                });
                
                Promise.all(uploadPromises).then(() => {
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        /**验证 */
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 如果有文件需要上传，先上传文件
                    if (this.fileList.length > 0) {
                        this.uploadFiles().then(() => {
                            this.submitFormData();
                        }).catch(error => {
                            this.$message.error('文件上传失败，请重试');
                        });
                    } 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 params = _.cloneDeep(this.form);

            if (this.isAdd === 'add') {
                addArchiveRightApi(params).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('提交失败，请重试');
                });
            } else {
                editArchiveRightApi(params).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('提交失败，请重试');
                });
            }
        }
    }
};
</script>
<style lang="scss">
.w700 .el-dialog {
    width: 700px;
}

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

.w500 .el-dialog__header,
.w700 .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>