<template>
  <div class="sql-editor-wrapper" :style="{ height: height + 'px' }">
    <div class="editor-container">
      <div class="editor-toolbar">
        <el-tooltip content="格式化SQL" placement="top">
          <el-button type="primary" link @click="formatSql">
            <el-icon><Operation /></el-icon>
          </el-button>
        </el-tooltip>

        <el-dropdown @command="handleSnippetSelect" trigger="click">
          <el-button type="primary" link>
            <el-icon><Document /></el-icon>
            <span>插入SQL片段</span>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="(snippet, index) in sqlSnippets"
                              :key="index"
                              :command="snippet.code">
                {{ snippet.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- Monaco编辑器容器 -->
      <div ref="editorContainer" class="monaco-editor-container"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, nextTick, markRaw } from 'vue';
import { ElMessage } from 'element-plus';
import { Operation, Document } from '@element-plus/icons-vue';
import * as monaco from 'monaco-editor';
import { format } from 'sql-formatter'; // Ensure this library is installed and imported correctly

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: 300
  }
});

const emit = defineEmits(['update:modelValue']);

// 编辑器相关引用
const sqlValue = ref(props.modelValue);
const editorContainer = ref(null);
const editorInstance = ref(null);
const isFormatting = ref(false); // 格式化状态标记
const isInserting = ref(false); // 插入片段状态标记

// SQL代码片段
const sqlSnippets = [
  {
    name: '基本查询',
    code: 'SELECT * FROM table_name WHERE condition;'
  },
  {
    name: '分组查询',
    code: 'SELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING COUNT(*) > 1;'
  },
  {
    name: '联表查询',
    code: 'SELECT a.*, b.* FROM table1 a JOIN table2 b ON a.id = b.table1_id;'
  },
  {
    name: '分页查询',
    code: 'SELECT * FROM table_name LIMIT 10 OFFSET 0;'
  },
  {
    name: '插入数据',
    code: 'INSERT INTO table_name (column1, column2) VALUES (value1, value2);'
  },
  {
    name: '更新数据',
    code: 'UPDATE table_name SET column1 = value1 WHERE condition;'
  },
  {
    name: '删除数据',
    code: 'DELETE FROM table_name WHERE condition;'
  }
];

// SQL关键字
const sqlKeywords = [
  "SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "HAVING",
  "JOIN", "LEFT JOIN", "RIGHT JOIN", "INNER JOIN", "LIMIT", "OFFSET",
  "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP", "TABLE",
  "INTO", "VALUES", "SET", "AND", "OR", "NOT", "NULL", "IS", "AS",
  "DISTINCT", "COUNT", "SUM", "AVG", "MAX", "MIN", "BETWEEN", "LIKE",
  "IN", "EXISTS", "ALL", "ANY", "UNION", "CASE", "WHEN", "THEN", "ELSE", "END"
];

// 监听值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== sqlValue.value) {
    sqlValue.value = newValue;
    if (editorInstance.value) {
      // 使用安全的方式更新编辑器内容
      const model = editorInstance.value.getModel();
      if (model) {
        model.setValue(newValue);
      }
    }
  }
});

// 初始化Monaco编辑器
const initMonacoEditor = () => {
  if (!editorContainer.value) return;

  try {
    // 清理现有实例
    if (editorInstance.value) {
      editorInstance.value.dispose();
      editorInstance.value = null;
    }

    // 确保容器是空的
    if (editorContainer.value.childNodes.length > 0) {
      editorContainer.value.innerHTML = '';
    }

    // 创建编辑器实例
    const editor = monaco.editor.create(editorContainer.value, {
      value: sqlValue.value || '',
      language: 'sql',
      theme: 'vs',
      automaticLayout: true,
      scrollBeyondLastLine: false,
      minimap: { enabled: false },
      fontSize: 14,
      tabSize: 2,
      lineNumbers: 'on',
      scrollbar: {
        useShadows: false,
        verticalScrollbarSize: 10,
        horizontalScrollbarSize: 10,
        alwaysConsumeMouseWheel: false
      },
      // 禁用所有可能导致性能问题的功能
      folding: false,
      contextmenu: false,
      quickSuggestions: false,
      parameterHints: false,
      autoClosingBrackets: false,
      suggestOnTriggerCharacters: false,
      wordBasedSuggestions: false,
      links: false,
      hover: false,
      find: false,
      colorDecorators: false,
      lightbulb: { enabled: false },
      formatOnType: false,
      formatOnPaste: false,
      selectionHighlight: false,
      occurrencesHighlight: false,
      codeLens: false,
      renderControlCharacters: false,
      renderIndentGuides: false,
      renderLineHighlight: 'none',
      renderWhitespace: 'none'
    });

    console.log('[DEBUG] initMonacoEditor: Creating Monaco editor instance.');
    editorInstance.value = markRaw(editor);
    console.log('[DEBUG] initMonacoEditor: Monaco editor instance assigned to ref after markRaw.');

    // 使用节流处理内容变化
    const handleContentChange = () => {
      const currentEditor = editorInstance.value;
      if (!currentEditor) return;
      const value = currentEditor.getValue();
      sqlValue.value = value;
      emit('update:modelValue', value);
    };
    const changeModelDisposable = editorInstance.value.onDidChangeModelContent(handleContentChange);

    // 在组件销毁时清理事件监听器
    onBeforeUnmount(() => {
      if (changeModelDisposable) {
        try {
          changeModelDisposable.dispose();
        } catch (e) {
          // Error handling if needed
        }
      }
      
      // 确保也清理 editorInstance
      if (editorInstance.value) {
        try {
          editorInstance.value.dispose();
          editorInstance.value = null;
        } catch (e) {
          // Error handling if needed
        }
      }
    });
  } catch (error) {
    // 静默处理错误或进行适当的错误上报
  }
};

// 格式化SQL
const formatSql = () => {
  console.log('[DEBUG] formatSql START');
  if (!editorInstance.value) {
    console.error('[DEBUG] formatSql: Editor instance is NOT available.');
    // ElMessage.error('编辑器实例未准备好，请稍后再试。');
    return;
  }
  console.log('[DEBUG] formatSql: Editor instance is available.');

  const currentContent = editorInstance.value.getValue();
  console.log('[DEBUG] formatSql: Current content length:', currentContent.length);

  if (!currentContent.trim()) {
    console.log('[DEBUG] formatSql: Content is empty or whitespace, skipping format.');
    // ElMessage.info('SQL内容为空，无需格式化。');
    return;
  }

  // loading.value = true; // 假设有加载状态
  // isFormatting.value = true;
  console.log('[DEBUG] formatSql: Attempting to format SQL...');
  try {
    const formattedSql = format(currentContent, {
      language: 'mysql', // 根据需要选择 'mysql', 'sql', 'n1ql', 'plsql', 'spark', 'tsql' 等
      indent: '  ', // 两个空格缩进
      uppercase: true, // 关键字大写
      linesBetweenQueries: 1
    });
    console.log('[DEBUG] formatSql: SQL formatted successfully.');

    editorInstance.value.setValue(formattedSql);
    console.log('[DEBUG] formatSql: Formatted SQL set to editor.');
    // ElMessage.success('SQL格式化成功！');
  } catch (error) {
    console.error('[DEBUG] formatSql: Error during formatting:', error);
    // ElMessage.error('SQL格式化失败，请检查SQL语法或格式化库配置。详情请查看控制台。');
  } finally {
    // loading.value = false;
    // isFormatting.value = false;
    console.log('[DEBUG] formatSql END');
  }
};

// 处理SQL片段选择 - 使用防抖动处理
const handleSnippetSelect = (snippet: string) => {
  console.log('[DEBUG] handleSnippetSelect START. Snippet:', snippet);
  if (!editorInstance.value) {
    console.error('[DEBUG] Editor instance is NOT available.');
    return;
  }
  console.log('[DEBUG] Editor instance is available.');

  try {
    const model = editorInstance.value.getModel();
    if (!model) {
      console.error('[DEBUG] Editor model is NOT available.');
      return;
    }
    console.log('[DEBUG] Editor model obtained.');

    const currentPosition = editorInstance.value.getPosition();
    console.log('[DEBUG] Current position:', currentPosition);

    if (currentPosition) {
      const range = new monaco.Range(
        currentPosition.lineNumber,
        currentPosition.column,
        currentPosition.lineNumber,
        currentPosition.column
      );
      const op = { range: range, text: snippet, forceMoveMarkers: true };
      console.log('[DEBUG] Preparing to executeEdits. Op:', op);
      editorInstance.value.executeEdits('snippet-inserter', [op]); // Monaco API call
      console.log('[DEBUG] executeEdits completed.');
    } else {
      console.warn('[DEBUG] Cannot get current position. Appending to end.');
      const currentValue = model.getValue();
      const newContent = currentValue + (currentValue ? '\n' : '') + snippet;
      model.setValue(newContent); // Monaco API call
      console.log('[DEBUG] Appended to end using setValue.');
    }
  } catch (error) {
    console.error('[DEBUG] CRITICAL ERROR in handleSnippetSelect:', error);
  }
  console.log('[DEBUG] handleSnippetSelect END.');
};

// 组件挂载后的生命周期钩子
onMounted(() => {
  // 延迟初始化编辑器，确保 DOM 已完全渲染
  setTimeout(() => {
    initMonacoEditor();
  }, 300);
});

// 组件销毁前
onBeforeUnmount(() => {
  // 清理编辑器实例
  if (editorInstance.value) {
    try {
      editorInstance.value.dispose();
      editorInstance.value = null;
    } catch (e) {
      // Error handling if needed
    }
  }
});
</script>

<style scoped>
.sql-editor-wrapper {
  display: flex;
  height: 300px;
  min-height: 200px;
  width: 100%;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-container {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  width: 100%;
}

.editor-toolbar {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-bottom: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  z-index: 10;
}

.monaco-editor-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 200px;
  width: 100%;
}

/* 深色模式样式 */
.dark .sql-editor-wrapper {
  border-color: #4c4d4f;
}

.dark .editor-toolbar {
  background-color: #252526;
  border-color: #4c4d4f;
}
</style>
