<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" width="680" @closed="$emit('closed', fileIsDel)">
        <share-form ref="shareForm" :mode="mode" @isUploadChange="isUpload = $event" @fileIsDelChange="fileIsDel = true"></share-form>

        <template #footer>
            <template v-if="mode != 'detail'">
                <el-button :loading="isSaving" type="primary" :disabled="isUpload" @click="submit(mode == 'decode' && 'edit' || mode)">确 定</el-button>
            </template>
        </template>
    </el-dialog>
</template>

<script>
import API from "@/api/policy/share";
import shareForm from "./form.vue";

export default {
    emits: ["success", "closed"],
    
    components: {
        shareForm
    },

    data() {
        return {
            visible: false,
            isSaving: false,
            isUpload: false,
            fileIsDel: false,

            mode: "saveDone",
            titleMap: {
                saveDone: "新增",
                edit: "修改",
                detail: "详情",
                decode: "添加解读"
            }
        }
    },

    methods: {
        open(mode = "saveDone") {
            this.mode = mode;
            this.visible = true;
            return this;
        },

        setData(id) {
            nextTick(() => this.$refs.shareForm.setData(id));
        },

        // 表单提交方法
        submit(mode) {
            this.$refs.shareForm.$refs.formRef.validate(valid => {
                if (valid) {
                    this.isSaving = true;
                    API[mode](this.$refs.shareForm.form).then(res => {
                        this.isSaving = false;
                        if (res.code === 200) {
                            ElMessage.success("操作成功");
                            this.visible = false;
                            this.fileIsDel = false;
                            this.$emit("success", mode);
                        } else ElMessage.error(res.msg);
                    }).catch(() => this.isSaving = false);
                } else {
                    return false;
                }
            });
        }
    }
}
</script>