<template>
    <div class="code-container" ref="container" :class="cssClass"></div>
</template>
<script>
    import * as monaco from "monaco-editor";
    let sqlStr =
        "add except percent all exec plan alter execute precision and exists primary any exit print as fetch " +
        "proc asc file procedure authorization fillfactor public backup for raiserror begin foreign read between " +
        "freetext readtext break freetexttable reconfigure browse from references bulk full replication by " +
        "function restore cascade goto restrict case grant return check group revoke checkpoint having right " +
        "close holdlock rollback clustered identity rowcount coalesce identity_insert rowguidcol collate identitycol " +
        "rule column if save commit in schema compute index select constraint inner session_user contains insert set " +
        "containstable intersect setuser continue into shutdown convert is some create join statistics cross key " +
        "system_user current kill table current_date left textsize current_time like then current_timestamp lineno " +
        "to current_user load top cursor national tran database nocheck transaction dbcc nonclustered trigger " +
        "deallocate not truncate declare null tsequal default nullif union delete of unique deny off update desc " +
        "offsets updatetext disk on use distinct open user distributed opendatasource values double openquery varying " +
        "drop openrowset view dummy openxml waitfor dump option when else or where end order while errlvl outer " +
        "with escape over writetext recursive";
    export default {
        name: "CodeEditor",
        props: {
            disabled: false,
            title: "",
            cssClass:"",
            placeholder: "",
            language:{
                type: String,
                default: "java"
            },
            options: {
                type: Object,
                default() {
                    return {
                        // language: "java", // shell、sql、python
                        theme: "vs-dark", //官方自带三种主题vs, hc-black, or vs-dark
                        selectOnLineNumbers: true,//显示行号
                        cursorStyle: 'line',        //光标样式
                        automaticLayout: false, //自动布局
                        glyphMargin: true,  //字形边缘
                        roundedSelection: false,
                        scrollBeyondLastColumn:false,//滚动到最后一列外
                        scrollBeyondLastLine:false,//滚动到最后一行外
                        useTabStops: false,
                        wordWrap: "on",//自动换行
                        wrappingIndent: "indent",
                        fontSize: 12,       //字体大小
                        autoIndent:true,//自动缩进
                        quickSuggestionsDelay: 500,   //代码提示延时
                    };
                }
            },
            value: {
                type: String,
                default: ""
            }
        },

        data() {
            return {
                monacoInstance: null,
                provider: null,
                hints: [
                    "select",
                    "insert",
                    "delete",
                    "update",
                    "create table",
                    "drop table",
                    "alter table",
                    "create view",
                    "drop view",
                    "create index",
                    "drop index",
                    "create procedure",
                    "drop procedure",
                    "create trigger",
                    "drop trigger",
                    "create schema",
                    "drop schema",
                    "create domain",
                    "alter domain",
                    "drop domain",
                    "grant",
                    "deny",
                    "revoke",
                    "commit",
                    "rollback",
                    "set transaction",
                    "declare",
                    "explan",
                    "open",
                    "fetch",
                    "close",
                    "prepare",
                    "execute",
                    "describe",
                    "form",
                    "order by"
                ]
            };
        },
        created() {
            this.initHints();
        },
        mounted() {
            this.init();
        },
        beforeDestroy() {
            this.dispose();
        },
        methods: {
            dispose() {
                if (this.monacoInstance) {
                    if (this.monacoInstance.getModel()) {
                        this.monacoInstance.getModel().dispose();
                    }
                    this.monacoInstance.dispose();
                    this.monacoInstance = null;
                    if (this.provider) {
                        this.provider.dispose();
                        this.provider = null
                    }
                }
            },
            initHints() {
                let sqlArr = sqlStr.split(" ");
                this.hints = Array.from(new Set([...this.hints, ...sqlArr])).sort();
            },
            init() {
                let that = this;
                this.dispose();
                let createCompleters = textUntilPosition => {
                    //过滤特殊字符
                    let _textUntilPosition = textUntilPosition
                        .replace(/[\*\[\]@\$\(\)]/g, "")
                        .replace(/(\s+|\.)/g, " ");
                    //切割成数组
                    let arr = _textUntilPosition.split(" ");
                    //取当前输入值
                    let activeStr = arr[arr.length - 1];
                    //获得输入值的长度
                    let len = activeStr.length;

                    //获得编辑区域内已经存在的内容
                    let rexp = new RegExp('([^\\w]|^)' + activeStr + '\\w*', "gim");
                    let match = that.value.match(rexp);
                    let _hints = !match ? [] : match.map(ele => {
                        let rexp = new RegExp(activeStr, "gim");
                        let search = ele.search(rexp);
                        return ele.substr(search)
                    })

                    //查找匹配当前输入值的元素
                    let hints = Array.from(new Set([...that.hints, ..._hints])).sort().filter(ele => {
                        let rexp = new RegExp(ele.substr(0, len), "gim");
                        return match && match.length === 1 && ele === activeStr || ele.length === 1
                            ? false
                            : activeStr.match(rexp);
                    });
                    //添加内容提示
                    let res = hints.map(ele => {
                        return {
                            label: ele,
                            kind: that.hints.indexOf(ele) > -1 ?
                                monaco.languages.CompletionItemKind.Keyword :
                                monaco.languages.CompletionItemKind.Text,
                            documentation: ele,
                            insertText: ele
                        };
                    });
                    return res;
                };
                this.provider = monaco.languages.registerCompletionItemProvider("sql", {
                    provideCompletionItems(model, position) {
                        // this.$d.debug().log("======》智能感知",model,position);
                        let textUntilPosition = model.getValueInRange({
                            startLineNumber: position.lineNumber,
                            startColumn: 1,
                            endLineNumber: position.lineNumber,
                            endColumn: position.column
                        });
                        let suggestions = createCompleters(textUntilPosition);
                        return {
                            suggestions: suggestions
                        };

                        return createCompleters(textUntilPosition);
                    }
                });
                // 初始化编辑器实例
                this.monacoInstance = monaco.editor.create(this.$refs["container"], {
                    value: this.value,
                    autoIndex: true,
                    language: this.language,
                    readOnly: this.disabled,
                    ...this.options
                });

                // 监听编辑器content变化事件
                this.monacoInstance.onDidChangeModelContent(() => {
                    this.$emit("change", this.monacoInstance.getValue());
                });
            }
        }
    };
</script>
<style lang="scss" scope>
    .code-container {
        width: 100%;
        height: 100%;
        overflow: hidden;
        border: 1px solid #eaeaea;
        .monaco-editor .scroll-decoration {
            box-shadow: none;
        }
    }
</style>
