import { ref, createApp } from "vue";
import { ElButton, ElDialog, ElInput, ElTree } from "element-plus";
import {
  GetAllTablesAndViews,
  GetAllBasicData,
} from "@shalu/service";

import type Node from "element-plus/es/components/tree/src/model/node";

type ViewItem = {
  name: string;
  schemaName: string;
  type: number;
  id: string;
};

type BisicData = {
  disabled?: boolean;
  displayOrder?: number;
  id?: string;
  isDisabled?: boolean;
  langName?: string;
  name: string;
  path?: string;
  updateTime?: string;
  value?: string;
};

/**
 * 获取系统内部的数据源
 * @param type 数据源类型
 * @returns 数据源
 */
export const getDataOrigin = (
  type: "table" | "view",
): Promise<{ value: string; result?: any }> => {
  const data = ref();
  const loading = ref(false);
  const val = ref("");
  const filterText = ref("");
  const treeRef = ref();
  const valId = ref("");

  // 获取视图
  if (type === "view") {
    data.value = [
      { label: "系统视图", children: [] },
      { label: "数据源视图", children: [] },
    ];
    loading.value = true;
    GetAllTablesAndViews({ types: type })
      .then((res: any) => {
        const { bpmViewTables = [] } = res || {};
        bpmViewTables.forEach((item: ViewItem) => {
          const { name, schemaName, type, id } = item;
          if (data.value[type - 1]) {
            // type 1: 系统视图 2: 数据源视图
            data.value[type - 1].children.push({
              label: `${schemaName}(${name})`,
              value: schemaName,
              id,
            });
          }
        });
      })
      .finally(() => {
        loading.value = false;
      });
  }

  // 动态加载数据
  const onload = (node: Node, resove: (data: BisicData[]) => void) => {
    if (node.level === 0) {
      return resove([{ name: "基础数据" }]);
    }
    const data = node.data;
    GetAllBasicData({
      currentPage: 1,
      pageSize: 999,
      orderByProperty: "id",
      Ascending: true,
      totalPage: 1,
      totalCount: 1,
      filters: data?.id ? [{ name: "parentId", value: data.id }] : null,
    }).then((res: any) => {
      resove(res || []);
    });
  };

  const getTreeVNode = () => {
    return type === "table" ? (
      <ElTree
        ref={treeRef}
        lazy={true}
        load={onload}
        props={{
          label: (data: any) =>
            data.path ? `${data.path}(${data.name})` : data.name,
          children: "children",
        }}
        onNode-click={(node: BisicData) => {
          if (node?.path) {
            val.value = node.path;
          }
        }}
        filterNodeMethod={(value: string, data: any) => {
          // treeRef.value?.onload();
          return (
            data.path?.toUpperCase().includes(value.toUpperCase()) ||
            data.name.toUpperCase().includes(value.toUpperCase())
          );
        }}
        empty-text={"暂无数据"}
      />
    ) : (
      <ElTree
        ref={treeRef}
        data={data.value}
        defaultExpandAll={true}
        onNode-click={(node) => {
          if (node?.value && node.id) {
            val.value = node.value;
            valId.value = node.id;
          }
        }}
        filterNodeMethod={(value: string, data) => {
          return data.label?.includes(value);
        }}
        empty-text={"暂无数据"}
      />
    );
  };

  return new Promise((resolve, reject) => {
    const mountNode = document.createElement("div");
    const app = createApp({
      render() {
        return (
          <ElDialog
            modelValue={true}
            title={type === "table" ? "选择数据集" : "选择视图表"}
            width="800px"
            style={{ height: "600px" }}
            v-slots={{
              footer: () => (
                  <ElButton
                    type="primary"
                    disabled={!val.value}
                    onClick={() => {
                      resolve({ value: val.value });
                      document.body.removeChild(mountNode);
                    }}
                  >
                    确定
                  </ElButton>
              ),
            }}
            onClose={() => {
              reject("close");
              document.body.removeChild(mountNode);
            }}
          >
            <ElInput
              size="small"
              placeholder="请输入关键字进行搜索"
              v-model={filterText.value}
              onInput={() => {
                treeRef.value?.filter(filterText.value);
              }}
              style={{
                marginBottom: "10px",
                height: "35px",
                fontSize: "14px",
              }}
            />
            <div style={{ height: "379px", overflow: "auto" }}>
              {getTreeVNode()}
            </div>
          </ElDialog>
        );
      },
    });
    document.body.appendChild(mountNode);
    app.mount(mountNode);
  });
};
