<template>
    <form-option title="编辑抽查细则">
        <vue-editor 
            id="editor"
            v-model="content"
            useCustomImageHandler
            @image-added="handleImageAdded">
        </vue-editor>
        <el-row class="mt">
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" :loading="uploading" @click="commitContent">确定</el-button>
        </el-row>
    </form-option>
</template>

<script>
import FormOption from "@/component/FormOption";
import { VueEditor } from "vue2-editor";

import { getOneDetail, addDetail, updateDetail } from '@/api/system';
import { upload } from '@/api/file';
import { notEmpty, handleProblemImgs } from '@/utils/tool';

export default {
    components: {
        FormOption,
        VueEditor
    },
    data () {
        return {
            content: '',
            uploading: false,
        }
    },
    computed: {
        id() {
            return this.$route.params.id
        }
    },
    mounted () {
        this.initData()
    },
    methods: {
        initData() {
            if (notEmpty(this.id)) {
                getOneDetail(this.id).then(res => {
                    if (res) {
                        this.content = res.content || '';
                    }
                })
            }
        },
        handleImageAdded(file, Editor, cursorLocation, resetUploader) {
            const name = file.name || (new Date().getTime() + '.jpg')
            upload(name, file).then(res => {
                if (res) {
                    const url = handleProblemImgs(res.id);
                    Editor.insertEmbed(cursorLocation, "image", url);
                    resetUploader();
                }
            });
        },
        cancelEdit() {
            this.$router.back();
        },
        commitContent() {
            this.uploading = true;
            const vm = this;
            if (notEmpty(this.id)) {
                updateDetail(this.id, {
                    content: this.content
                }).then(res => {
                    vm.$message.success('修改成功');
                    vm.cancelEdit();
                }).catch(() => {
                    vm.uploading = false;
                });
            }
            else {
                addDetail({
                    content: this.content
                }).then(res => {
                    vm.$message.success('新增成功');
                    vm.cancelEdit();
                }).catch(() => {
                    vm.uploading = false;
                });
            }
        }
    },
}
</script>