<template>
    <!-- 小型弹窗，用于完成，删除，保存等操作 -->
    <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
        :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
        <div class="dialog-content-scrollable">
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="110px" label-position="top">
                <el-form-item label="工器具名称" prop="toolName">
                    <el-input class="form-item" v-model="form.toolName" clearable show-word-limit placeholder="请输入工器具名称"
                        maxlength="64" :disabled="isDisabled"></el-input>
                </el-form-item>
                <el-form-item label="规格型号" prop="model">
                    <el-input class="form-item" v-model="form.model" clearable show-word-limit placeholder="请输入规格型号"
                        maxlength="32" :disabled="isDisabled"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-input class="form-item" v-model="form.unit" clearable show-word-limit placeholder="请输入单位"
                        maxlength="32" :disabled="isDisabled"></el-input>
                </el-form-item>
                <el-form-item label="技术参数" prop="technicalParameters">
                    <el-input class="form-item" v-model="form.technicalParameters" clearable show-word-limit
                        placeholder="请输入技术参数" maxlength="100" :disabled="isDisabled"></el-input>
                </el-form-item>
                <el-form-item label="主要作用" prop="mainFunction">
                    <el-input class="form-item" v-model="form.mainFunction" clearable show-word-limit
                        placeholder="请输入主要作用" maxlength="100" :disabled="isDisabled"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" class="form-item"
                        v-model.trim="form.remark" clearable show-word-limit placeholder="请输入备注"
                        maxlength="200" :disabled="isDisabled"></el-input>
                </el-form-item>
                <!-- 工器具图片 -->
                <el-form-item label="工器具图片" prop="fileList" v-if="!isDisabled">
                    <UploadFile :fileList="form.fileList" :fileUploadRule="defaultParams.fileUploadRule"
                        @file-change="handleFileChange" @del-file="handleDelFile" type="tool" />
                </el-form-item>
                <el-form-item label="工器具图片" v-if="isDisabled">
                    <FileOrImageDisplay :file="form.fileList[0]" :image-url="form.url"/>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" class="confirm-btn" :disabled="disabled"
                @click="submitForm('ruleForm')" v-if="!isDisabled">确认</el-button>
            <el-button class="cancel-btn" @click="handleClose" :disabled="disabled">取消</el-button>
        </span>
    </el-dialog>
</template>
<script>
import _ from 'lodash'
import UploadFile from '@/views/common/UploadFile.vue'
import FileOrImageDisplay from '@/views/common/FileOrImageDisplay.vue';
import { addDataAPI, editDataAPI, getDetailDataAPI } from '@/api/enterpriseLibrary/tool/tool'
// 默认参数
const defaultParams = {
    fileUploadRule: {
        fileUploadType: 'tools',
        fields_json: '',
        suffix: 'tools_database'
    },
};
export default {
    name: "ToolForm",
    components: {
        UploadFile,
        FileOrImageDisplay
    },
    props: ["width", "rowData", "title", "disabled", "isAdd"],
    data() {
        return {
            lDialog: this.width > 500 ? "w700" : "w500",
            dialogVisible: true,
            defaultParams,
            form: {
                toolId: null,
                enterpriseId: this.rowData.enterpriseId,
                toolName: '',
                model: '',
                unit: '',
                technicalParameters: '',
                mainFunction: '',
                remark: '',
                fileList: [],
                delFileList: []
            },
            rules: {
                toolName: [
                    { required: true, message: '工器具名称不能为空', trigger: 'blur' }
                ],
                model: [
                    { required: true, message: '规格型号不能为空', trigger: 'blur' }
                ],
                unit: [
                    { required: true, message: '单位不能为空', trigger: 'blur' }
                ],
                fileList: [
                    { required: true, message: '工器具图片不能为空', trigger: ['blur', 'change'] }
                ],
            },
        };
    },
    watch: {
        isAdd: {
            handler(newVal) {
                if (newVal === 'edit' || newVal === 'detail') {
                    this.initFormData();
                }
            },
            immediate: true,
        },
    },
    computed: {
        isDisabled() {
            return this.isAdd === 'detail';
        }
    },
    methods: {
        /** 初始化表单数据 */
        async initFormData() {
            if (!this.rowData) return;
            const files = await this.getDetail();
            // 编辑模式：填充表单数据
            this.form = {
                toolId: this.rowData.toolId,
                enterpriseId: this.rowData.enterpriseId,
                toolName: this.rowData.toolName || '',
                model: this.rowData.model || '',
                unit: this.rowData.unit || '',
                technicalParameters: this.rowData.technicalParameters || '',
                mainFunction: this.rowData.mainFunction || '',
                remark: this.rowData.remark || '',
                fileList: Array.isArray(files) ? files : [],
                delFileList: [],
            };
            if(this.isDisabled){
                this.rules = {};
                this.$set(this.form, 'url', files[0]?.lsFilePath || null);
            }
        },
        async getDetail() {
            try {
                const res = await getDetailDataAPI({ toolId: this.rowData.toolId, enterpriseId: this.rowData.enterpriseId });
                if (res && res.code === 200) {
                    return this.getFileList(res.data);
                }
                return [];
            } catch (error) {
                console.error(error);
                return [];
            }
        },
        getFileList(detailData){
            const list = detailData && Array.isArray(detailData.resourceFileVoList)
                ? detailData.resourceFileVoList
                : [];
            return list.map(item => {
                return {
                    name: item.fileName,
                    filePath: item.filePath,
                    lsFilePath: item.lsFilePath,
                    fileType: item.fileType
                };
            });
        },
        // 文件变化
        handleFileChange(file) {
            console.log(file);
            this.form.fileList = file;
        },
        // 文件删除时触发
        handleDelFile(file) {
            console.log(file);
            const delPath = file?.response?.fileRes?.filePath || file?.filePath || null;
            if (delPath) {
                this.form.delFileList.push(delPath);
            }
        },
        /*关闭弹窗 */
        handleClose() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
        },
        /**确认弹窗 */
        sureBtnClick() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
        },
        /**重置表单*/
        reset() {
            this.form = {
                toolName: '',
                model: '',
                unit: '',
                technicalParameters: '',
                mainFunction: '',
                remark: '',
                fileList: [],
                delFileList: []
            };
            this.resetForm("ruleForm");
        },
        handleReuslt(res) {
            this.$modal.msgSuccess(res.msg);
            this.reset();
            this.$emit('handleQuery');
            this.handleClose();
        },
        validate(formName) {
            return new Promise((resolve, reject) => {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        resolve(this.form) // 校验成功返回表单数据
                    } else {
                        reject(new Error('数据未填写完整'))
                    }
                })
            })
        },
        /**验证 */
        async submitForm(formName) {
            try {
                const data = await this.validate(formName);
                // 所有校验通过，组装完整数据
                let formData = {
                    ...data,
                    allFiles: [
                        ...data.fileList.map(file => JSON.parse(JSON.stringify(file))),
                    ],
                    delFiles: [
                        ...data.delFileList
                    ]
                }

                let allFiles = formData.allFiles.map(file => {
                    return file?.response?.fileRes ? {
                        ...file.response.fileRes,
                    } : null;
                }).filter(item => item !== null);
                formData.files = allFiles;
                delete formData.fileList;
                delete formData.delFileList;
                delete formData.allFiles;
                // 显示遮罩层
                this.loading = this.$loading({
                    lock: true,
                    text: "数据提交中，请稍候...",
                    background: 'rgba(0,0,0,0.5)',
                    target: this.$el.querySelector('.el-dialog') || document.body
                })
                console.log('所有表单校验通过，完整数据:', formData)
                const res = await this.saveData(formData)
                if (res.code === 200) {
                    this.handleReuslt(res);
                } else {
                    this.$modal.msgError(res.msg);
                }
            } catch (error) {

            } finally {
                if(this.loading){
                    this.loading.close()
                }
            }
        },

        // 保存接口
        async saveData(formData) {
            return new Promise((resolve, reject) => {
                if (this.isAdd === 'add') { // 新增
                    addDataAPI(formData).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                } else { // 修改
                    editDataAPI(formData).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                }

            })
        },
    }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
    width: 700px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
}

.w500 ::v-deep .el-dialog {
    width: 500px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
}

// 弹窗主体区域
.w500 ::v-deep .el-dialog__body,
.w700 ::v-deep .el-dialog__body {
    flex: 1;
    overflow: hidden;
    padding: 20px;
    display: flex;
    flex-direction: column;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
    flex-shrink: 0;
    border-bottom: 1px solid #EBEEF5;
    
    .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;
}

.confirm-btn {
    width: 98px;
    height: 36px;
    background: #1F72EA;
    box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
    border-radius: 4px 4px 4px 4px;
    color: #fff;
    border: none;
    font-size: 14px;
    transition: all 0.3s;

    &:hover {
        background: #4A8BFF;
        box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
    }
}

.cancel-btn {
    width: 98px;
    height: 36px;
    background: #E5E5E5;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px 4px 4px 4px;
    color: #333;
    border: none;
    font-size: 14px;
    transition: all 0.3s;

    &:hover {
        background: #d0d0d0;
        box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
}

::v-deep .el-dialog__footer {
    text-align: center;
    flex-shrink: 0;
}

// 内容区域可滚动
.dialog-content-scrollable {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 6px;
    max-height: calc(90vh - 120px); // 减去头部和底部的高度

    // 自定义滚动条样式
    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-track {
        background: transparent;
    }

    &::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;

        &:hover {
            background: rgba(0, 0, 0, 0.3);
        }
    }
}
</style>