/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-07-06 15:29:43
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2022-07-08 10:25:02
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/sqlediter/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */



import React, { useRef, useState } from 'react'
import Editor, { useMonaco } from "@monaco-editor/react";


function SQLEditer() {

  const editorRef = useRef(null);
  const monaco = useMonaco();
  const [suggestions, set_suggestions] = useState([]);
  const [currentText, set_currentText] = useState('');

  // const changeModelContent = (e:any) => {
  //   console.log('内容改变', editorRef.current.getValue());

  // };

  const handleEditorDidMount = (editor: any, monaco: any) => {
    console.log({ editor, monaco })
    editorRef.current = editor;

    // editor.onDidChangeModelContent(changeModelContent);

    // this.editor = editor;
    // this.monaco = monaco;
    // 注册自定义语言
    // monaco.languages.register({ id: 'mylan' });

    // 为该语言注册一个语言提示器--联想
    monaco.languages.registerCompletionItemProvider('sql', {
      provideCompletionItems: () => {
        // this.suggestions 根据输入内容的不同发生变化
        return { suggestions: suggestions };
      },
    });


  }

  const onChangeHandle = (value: string | undefined, ev: any) => {
    // console.log({ value, ev });
    monaco.caretOffset = ev.changes[0].rangeOffset; //获取光标位置
    fetchSuggestions();
  }

  const fetchSuggestions = () => {

    let str = currentText.substr(0, monaco.caretOffset + 1);

    let reg = /薪资.$/;
    if (reg.test(str)) {
      const suggestions = [{
        label: '一月工资',
        insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
        kind: monaco.languages.CompletionItemKind.Function,
        insertText: '一月工资',
        detail: '一月工资',
      }];

    } else {
      const suggestions = [
        {
          label: 'sum',
          kind: monaco.languages.CompletionItemKind.Function,
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          insertText: 'sum(${1:})',
          detail: '计算所有参数数值的和',
        }];
    }
    if(editorRef.current){
      console.log('editorRef.current',editorRef.current)
      // editorRef.current.trigger('提示', 'editor.action.triggerSuggest', {});
    }
    
  }

  return (
    <Editor
      height="60vh"
      defaultLanguage="sql"
      defaultValue="// some comment"
      onChange={onChangeHandle}
      onMount={handleEditorDidMount}
    />
  );
}

export default SQLEditer