<template>
  <LjDialog
    ref="ljDialogRef"
    class="is-selector lj-selector"
    :draggable="drawerProps.draggable"
    :overflow="drawerProps.overflow"
    :width="drawerProps.width"
    :modal-class="drawerProps.modalClass"
    :modal="false"
    :style="{ height: '60%' }"
    @close="onDialogClose"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">{{ props.title }}</span>
      </div>
    </template>

    <div class="flx-col h-full">
      <LjHeaderMenu :update="isDialogVisible" :data="initParams" :action="btnGroup" />
      <LjFoldLayoutDouble v-bind="layoutConfig" class="flx-1 overflow-hidden">
        <template #secondMain>
          <div class="flx h-full">
            <div class="flx-col w-full">
              <FormulaEditor ref="formulaEditorRef" v-model="localFormula" :tree-data="treeData" />
            </div>
          </div>
        </template>
      </LjFoldLayoutDouble>
    </div>
  </LjDialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import LjDialog from "@/components/LjDialog/index.vue";
import LjFoldLayoutDouble from "@/components/LjFoldLayoutDouble/index.vue";
import FormulaEditor from "./editor.vue";
import { GetFormulaVarList } from "@/api/modules/basicinfo";
import { useAuthButtons } from "@/hooks/useAuthButtons";

const { t } = useI18n();
const { buttonDefault } = useAuthButtons(t);

const props = defineProps({
  title: { type: String, default: "公式编辑器" }
});

const emit = defineEmits<{
  (e: "confirm", payload: { formula: string; valid: boolean; parameters: any[] }): void;
}>();

interface TreeNode {
  text: string;
  value?: number | string | null;
  children?: TreeNode[];
}

// ---------- 状态 ----------
const ljDialogRef = ref();
const formulaEditorRef = ref();
const localFormula = ref<string>("");
const requestType = ref<number>(0);
const treeData = ref<TreeNode[]>([]);
const isDialogVisible = ref(false);
const initParams = ref<any>();

// 抽屉配置（用 reactive 明确类型）
const drawerProps = reactive({
  draggable: true,
  overflow: true,
  width: "60%",
  modalClass: "lj-file-dialog"
});

// 布局配置（命名语义化）
const layoutConfig = ref<Record<string, any>>({
  // 这里放置需要传给 LjFoldLayoutDouble 的配置项（若无可保持空对象）
});

// 按钮组
const btnGroup = ref([
  buttonDefault({
    label: "取消",
    clickFunc: () => {
      hide();
    }
  }),
  buttonDefault({
    label: "清空",
    clickFunc: () => {
      formulaEditorRef.value?.reset?.();
      localFormula.value = "";
    }
  }),
  buttonDefault({
    label: "检查公式",
    clickFunc: async () => {
      // 子组件的 check 方法返回 boolean
      const ok = await formulaEditorRef.value?.check?.();
      // 提示逻辑由子组件处理（这里仅作为动作触发）
      return ok;
    }
  }),
  buttonDefault({
    label: "确认",
    clickFunc: async () => {
      await handleConfirm();
    }
  })
]);

// ---------- 方法 ----------
const getFormulaVarList = async () => {
  try {
    const res: any = await GetFormulaVarList({ list: [], type: 1 });
    treeData.value = res?.recursionList ?? [];
  } catch (err) {
    treeData.value = [];
  }
};

const show = (type = 0, refresh = false, formula = "") => {
  localFormula.value = formula ?? "";
  requestType.value = type ?? 0;
  ljDialogRef.value?.show?.(refresh);
  nextTick(() => {
    isDialogVisible.value = true;
  });
};

const hide = () => {
  ljDialogRef.value?.hide?.();
  isDialogVisible.value = false;
};

const onDialogClose = () => {
  // 当对话框关闭时需要同步状态
  isDialogVisible.value = false;
};

const handleConfirm = async () => {
  // 调用子组件的校验方法
  let valid = true;
  if (formulaEditorRef.value?.check) {
    try {
      valid = await formulaEditorRef.value.check();
    } catch (err) {
      console.warn("公式校验出错：", err);
      valid = false;
    }
  }

  if (!valid) return;

  // 返回更丰富的上下文
  emit("confirm", {
    formula: localFormula.value,
    valid,
    parameters: treeData.value
  });

  hide();
};

// ---------- 生命周期 ----------
onMounted(() => {
  getFormulaVarList();
});

// 暴露给父组件使用
defineExpose({
  show,
  hide
});
</script>

<style lang="scss">
.lj-selector {
  padding: 0;
  .el-tree {
    background: unset;
  }
}
.ljselector-aside-collapse {
  height: 100%;
  display: flex;
  flex-direction: column;

  .el-collapse-item {
    display: flex;
    flex-direction: column;
    overflow: auto;
    height: auto;

    &.is-active {
      flex: 1;
    }
    &:not(.is-active) {
      flex-shrink: 0;
    }
    .el-collapse-item__header {
      flex-shrink: 0;
    }
    .el-collapse-item__wrap {
      flex: 1;
      overflow: auto;
      background-color: $color-gray-2;
      padding: 8px 4px;

      .lj-infor-item {
        background-color: $color-gray-1;
      }
    }
  }
}
</style>
