import { defineComponent, ref, watch, onMounted, onUnmounted, computed } from 'vue';

// 模拟 DataGridTextColumn
interface DataGridTextColumn {
  Header: string;
  Binding: string;
}

// 模拟 DataGridCell 和 DataGridColumnHeader
class DataGridCell {}
class DataGridColumnHeader {}

// 模拟 ComboBoxHelper
class ComboBoxHelper {
  static PartEditableTextBox = 'PART_EditableTextBox';
}

export default defineComponent({
  name: 'ComboBoxDataGrid',
  props: {
    itemsSource: {
      type: Array,
      default: () => []
    },
    displayMemberPath: {
      type: String,
      default: ''
    },
    isEditable: {
      type: Boolean,
      default: false
    },
    isAutoComplete: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array as () => DataGridTextColumn[],
      default: () => []
    }
  },
  emits: ['selection-changed'],
  setup(props, { emit }) {
    const isDropDownOpen = ref(false);
    const selectedItem = ref(null);
    const selectedIndex = ref(-1);
    const editTextBox = ref<HTMLInputElement | null>(null);
    const isKeyEvent = ref(false);
    const oldSelStart = ref(0);
    const oldSelLength = ref(0);
    const oldText = ref('');
    let interval: NodeJS.Timeout | null = null;

    const toggleDropDown = () => {
      isDropDownOpen.value = !isDropDownOpen.value;
    };

    const handleDataGridSelectionChanged = (item: any, index: number) => {
      selectedItem.value = item;
      selectedIndex.value = index;
      isDropDownOpen.value = false;
      emit('selection-changed', { item, index });
    };

    const handleDataGridMouseDown = (event: MouseEvent) => {
      let dep = event.target as HTMLElement;
      while (dep && !(dep.classList.contains('data-grid-cell') || dep.classList.contains('data-grid-column-header'))) {
        dep = dep.parentElement as HTMLElement;
      }

      if (!dep) return;

      if (dep.classList.contains('data-grid-column-header')) {
        // do something
      }

      if (dep.classList.contains('data-grid-cell')) {
        isDropDownOpen.value = false;
      }
    };

    const handleEditTextBoxPreviewKeyDown = () => {
      isKeyEvent.value = true;
    };

    const handleEditTextBoxTextChanged = () => {
      if (!editTextBox.value) return;

      if (editTextBox.value.value === '') {
        isDropDownOpen.value = false;
      } else if (isKeyEvent.value) {
        selectedItem.value = null;
        if (interval) clearTimeout(interval);
        interval = setTimeout(() => {
          isKeyEvent.value = false;
          isDropDownOpen.value = true;
          // 模拟筛选逻辑
          // if (!dv.Filter(text)) editTextBox.value.value = '';
          if (selectedItem.value) {
            editTextBox.value.value = selectedItem.value[props.displayMemberPath];
          }
        }, 400);
      }
    };

    const handleLostFocus = () => {
      isKeyEvent.value = false;
      isDropDownOpen.value = false;
      if (selectedIndex.value === -1 && editTextBox.value) {
        editTextBox.value.value = '';
      }
      if (interval) clearTimeout(interval);
      if (editTextBox.value) {
        try {
          editTextBox.value.setSelectionRange(0, 0);
        } catch (e) {}
      }
    };

    const handleGotFocus = () => {
      if (editTextBox.value) {
        editTextBox.value.focus();
      }
    };

    const handleDropDownOpened = () => {
      if (editTextBox.value) {
        editTextBox.value.value = oldText.value;
        editTextBox.value.setSelectionRange(oldSelStart.value, oldSelStart.value + oldSelLength.value);
      }
    };

    const handleGotMouseCapture = () => {
      if (editTextBox.value) {
        oldSelStart.value = editTextBox.value.selectionStart || 0;
        oldSelLength.value = editTextBox.value.selectionEnd || 0 - oldSelStart.value;
        oldText.value = editTextBox.value.value;
      }
    };

    onMounted(() => {
      if (props.isAutoComplete) {
        if (editTextBox.value) {
          editTextBox.value.addEventListener('keydown', handleEditTextBoxPreviewKeyDown);
          editTextBox.value.addEventListener('input', handleEditTextBoxTextChanged);
        }
      }
    });

    onUnmounted(() => {
      if (interval) clearTimeout(interval);
      if (editTextBox.value) {
        editTextBox.value.removeEventListener('keydown', handleEditTextBoxPreviewKeyDown);
        editTextBox.value.removeEventListener('input', handleEditTextBoxTextChanged);
      }
    });

    const displayText = computed(() => {
      if (selectedItem.value && props.displayMemberPath) {
        return selectedItem.value[props.displayMemberPath];
      }
      return '';
    });

    return {
      isDropDownOpen,
      selectedItem,
      selectedIndex,
      editTextBox,
      toggleDropDown,
      handleDataGridSelectionChanged,
      handleDataGridMouseDown,
      handleEditTextBoxPreviewKeyDown,
      handleEditTextBoxTextChanged,
      handleLostFocus,
      handleGotFocus,
      handleDropDownOpened,
      handleGotMouseCapture,
      displayText
    };
  }
});