<template>
  <div class="formula-editor-with-model">
    <!-- 显示当前公式值的输入框 -->
    <el-input v-model="displayValue" :type="type" :rows="3" placeholder="点击编辑公式" readonly @click="openFormulaEditor">
    </el-input>

    <!-- 公式编辑器弹窗 -->
    <FormulaEditorDialog ref="formulaEditorRef" :title="title" @confirm="handleFormulaConfirm" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from "vue";
import { Edit } from "@element-plus/icons-vue";
import FormulaEditorDialog from "./index.vue";

interface Props {
  modelValue?: string;
  title?: string;
  type?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  title: "公式编辑器",
  type: "textarea"
});

const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();

// 组件引用
const formulaEditorRef = ref<InstanceType<typeof FormulaEditorDialog>>();

// 显示值（用于输入框显示）
const displayValue = computed({
  get: () => props.modelValue,
  set: value => emit("update:modelValue", value)
});

// 打开公式编辑器
const openFormulaEditor = () => {
  formulaEditorRef.value?.show(1, false, props.modelValue);
};

// 处理公式确认
const handleFormulaConfirm = ({ formula, valid, parameters }: { formula: string; valid: boolean; parameters: any[] }) => {
  if (valid) {
    displayValue.value = formula;
  }
};

// 暴露方法给父组件
const show = (type = 0, refresh = false, formula = "") => {
  formulaEditorRef.value?.show(type, refresh, formula);
};

const hide = () => {
  formulaEditorRef.value?.hide();
};

defineExpose({
  show,
  hide
});
</script>

<style lang="scss" scoped>
.formula-editor-with-model {
  width: 100%;

  :deep(.el-textarea) {
    .el-textarea__inner {
      cursor: pointer;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
}
</style>
