<template>
  <div class="sql-editor-wrapper">
    <div class="sql-editor-container">
      <Codemirror
        v-model:value="internalValue"
        :options="cmOptions"
        :width="width"
        :height="height"
        :readonly="readonly"
        @ready="onReady"
        @blur="onBlur"
        @change="onChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onBeforeUnmount } from 'vue'
import Codemirror from 'codemirror-editor-vue3'

// 引入必要的样式和插件
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/idea.css'
import 'codemirror/mode/sql/sql.js'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/sql-hint'
import 'codemirror/addon/display/placeholder.js'

const props = defineProps({
  modelValue: String,
  readonly: Boolean,
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  },
  placeholder: {
    type: String,
    default: '请输入 SQL 语句...'
  },
  tables: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'blur'])

const internalValue = ref(props.modelValue || '')
const editorInstance = ref(null)
const isEditorReady = ref(false)

// 强制刷新编辑器内容
const refreshEditor = () => {
  if (editorInstance.value) {
    nextTick(() => {
      editorInstance.value.refresh()
      editorInstance.value.setValue(internalValue.value)
    })
  }
}

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  if (newVal !== internalValue.value) {
    internalValue.value = newVal || ''
    if (isEditorReady.value) {
      editorInstance.value.setValue(newVal || '')
      refreshEditor()
    }
  }
}, { immediate: true })

const cmOptions = computed(() => ({
  mode: 'text/x-sql',
  theme: 'idea',
  lineNumbers: true,
  lineWrapping: true,
  tabSize: 2,
  readOnly: props.readonly ? 'nocursor' : false,
  placeholder: props.placeholder,
  extraKeys: { 'Ctrl-Space': 'autocomplete' },
  hintOptions: {
    completeSingle: false,
    tables: props.tables
  }
}))

const onReady = (editor) => {
  editorInstance.value = editor
  isEditorReady.value = true
  
  // 初始设置值
  editor.setValue(internalValue.value)
  refreshEditor()
  
  // 设置代码提示
  editor.on('inputRead', (cm, event) => {
    if (event && event.text && /[a-zA-Z]/.test(event.text[0])) {
      setTimeout(() => cm.showHint(), 0)
    }
  })
}

const onBlur = () => {
  emit('blur', internalValue.value)
}

const onChange = (value) => {
  internalValue.value = value
  emit('update:modelValue', value)
  emit('change', value)
}

onBeforeUnmount(() => {
  if (editorInstance.value) {
    editorInstance.value.toTextArea()
    editorInstance.value = null
  }
  isEditorReady.value = false
})
</script>

<style>
.sql-editor-wrapper {
  width: 100%;
  display: flex;
}

.sql-editor-container {
  flex: 1;
  min-width: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s;
  overflow: hidden; /* 确保内容不会溢出 */
}

.sql-editor-container:hover {
  border-color: #c0c4cc;
}

/* 确保CodeMirror容器正确继承宽度 */
.CodeMirror {
  width: 100% !important;
  height: 100%;
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 14px;
}

/* 修复行号区域的宽度 */
.CodeMirror-gutters {
  height: 100% !important;
}

.CodeMirror-hints {
  z-index: 9999 !important;
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
}
</style>