<template>
  <div class="data-solve-editor">
    <a-select
      v-model:value="localValue"
      mode="multiple"
      style="width: 100%"
      :allowClear="true"
      :filterOption="false"
      :options="dataSolveOptions"
      placeholder="可选"
      @change="updateValue"
    />
    <a-button type="primary" title="添加自定义表达式" :icon="h(PlusOutlined)" @click="openAddModal" />
    <a-modal
      v-model:open="addModalVisible"
      title="添加自定义表达式"
      ok-text="添加"
      destroy-on-close
      @ok="confirmAddCustom"
      @cancel="closeAddModal"
    >
      <a-textarea
        v-model:value="customExprInput"
        placeholder="请输入表达式, 请参考源码设置"
        allow-clear
        :auto-size="{ minRows: 2, maxRows: 5 }"
        @press-enter="confirmAddCustom"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { h, ref, watch } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps<{
  modelValue?: string[];
}>();
const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void;
}>();

const dataSolveOptions = ref([
  { value: 'none', label: '无' },
  { value: 'ich', label: '传承相关' },
  { value: 'common', label: '通用' },
  { value: 'date', label: '日期' },
  { value: 'form', label: '来源' },
  { value: 'inheritor-deadbox', label: '传承人死亡盒子' },
  { value: 'inheritor', label: '年代' },
]);

const localValue = ref<string[]>(props.modelValue || []);
const addModalVisible = ref(false);
const customExprInput = ref('');

watch(
  () => props.modelValue,
  (newValue) => {
    localValue.value = newValue || [];
  },
  { deep: true, immediate: true }
);

const updateValue = () => {
  emit('update:modelValue', localValue.value);
};

function openAddModal() {
  customExprInput.value = '';
  addModalVisible.value = true;
}

function closeAddModal() {
  addModalVisible.value = false;
  customExprInput.value = '';
}

function confirmAddCustom() {
  const value = customExprInput.value?.trim();
  if (!value) {
    return Promise.reject(new Error('请输入表达式'));
  }
  const exists = dataSolveOptions.value.some((opt) => opt.value === value);
  if (!exists) {
    dataSolveOptions.value.push({ value, label: value });
  }
  if (!localValue.value.includes(value)) {
    localValue.value = [...localValue.value, value];
    updateValue();
  }
  closeAddModal();
}
</script>

<style scoped>
.data-solve-editor {
  display: flex;
  gap: 8px;
  align-items: center;
}
.data-solve-editor .ant-select {
  flex: 1;
}
</style>