import { defineComponent, useModel, ref, reactive, onMounted, watch, resolveComponent, resolveDirective, openBlock, createBlock, withCtx, withDirectives, createElementBlock, createVNode, createCommentVNode, createTextVNode, toDisplayString, createElementVNode, unref, mergeModels } from 'vue';
import { Search, MoreFilled } from '@element-plus/icons-vue';
import '../../api/index.mjs';
import { useBaseApi } from '../../api/base/index.mjs';

const _hoisted_1 = { style: { "padding": "5px" } };
const _hoisted_2 = { style: { "display": "flex", "align-items": "center", "gap": "8px", "flex-wrap": "nowrap", "overflow": "hidden" } };
const _hoisted_3 = { style: { "flex": "1 1 200px", "min-width": "0", "overflow": "hidden" } };
const _hoisted_4 = { style: { "display": "flex", "align-items": "center", "flex-shrink": "0", "white-space": "nowrap" } };
const _hoisted_5 = { style: { "margin-bottom": "45px" } };
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{
    name: "FmTree"
  },
  __name: "index",
  props: /* @__PURE__ */ mergeModels({
    checkStrictly: { type: Boolean, default: true },
    /**
    * api service name
    */
    apiService: {
      type: String,
      default: ""
    },
    /**
    * api service 下的方法
    */
    apiAction: {
      type: String,
      default: ""
    },
    /**
    * 是否POST请求
    */
    isPost: {
      type: Boolean,
      default: false
    },
    paras: {
      type: Object,
      default: null
    },
    nodeKey: {
      type: String,
      default: "id"
    },
    defaultProps: {
      type: Object,
      default: { children: "children", label: "name" }
    },
    placeholder: {
      type: String,
      default: "\u7C7B\u578B\u540D\u79F0"
    },
    treeData: {
      type: Array,
      default: () => []
    }
  }, {
    "modelValue": {},
    "modelModifiers": {}
  }),
  emits: /* @__PURE__ */ mergeModels(["node-click", "refresh"], ["update:modelValue"]),
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const modeValue = useModel(__props, "modelValue");
    const filterText = ref("");
    const treeRef = ref();
    const state = reactive({
      loading: false,
      folderData: [],
      isShowCheckbox: false,
      strictly: false
    });
    onMounted(async () => {
      if (props.apiService != "" && props.apiAction != "") {
        await fetchTreeData();
      }
    });
    watch(filterText, (val) => {
      treeRef.value.filter(val);
    });
    watch(() => props.treeData, (newVal) => {
      state.folderData = newVal;
      const rtreeData = newVal != null ? newVal : [];
      modeValue.value = rtreeData.length > 0 ? rtreeData[0] : { id: 0, name: "", code: "" };
    });
    const fetchTreeData = async (showLoading = true) => {
      var _a, _b;
      if (showLoading) state.loading = true;
      var res = props.isPost ? await useBaseApi(props.apiService).post(props.paras, props.apiAction) : await useBaseApi(props.apiService).get(props.paras, props.apiAction);
      state.folderData = (_a = res.data.result) != null ? _a : [];
      if (showLoading) state.loading = false;
      const rtreeData = (_b = res.data.result) != null ? _b : [];
      modeValue.value = rtreeData.length > 0 ? rtreeData[0] : { id: 0, name: "", code: "" };
      return rtreeData;
    };
    const getCheckedKeys = () => {
      return treeRef.value.getCheckedKeys();
    };
    const getCheckedKeysByCmp = () => {
      const rel = { orgIdList: [], cmpList: [], depList: [], groupList: [], tenantList: [] };
      rel.orgIdList = treeRef.value.getCheckedKeys();
      if (rel.orgIdList && rel.orgIdList.length > 0) {
        const nodes = treeRef.value.getCheckedNodes();
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].pid == 0) {
            rel.cmpList.push(nodes[i].id);
            if (!rel.tenantList.includes(nodes[i].tenantId)) {
              rel.tenantList.push(nodes[i].tenantId);
            }
          }
          if (nodes[i].pid > 0 && nodes[i].level == 2) {
            rel.depList.push(nodes[i].id);
            if (!rel.cmpList.includes(nodes[i].pid)) {
              rel.cmpList.push(nodes[i].pid);
            }
            if (!rel.tenantList.includes(nodes[i].tenantId)) {
              rel.tenantList.push(nodes[i].tenantId);
            }
          }
          if (nodes[i].pid > 0 && nodes[i].level == 3) {
            rel.groupList.push(nodes[i].id);
            if (!rel.depList.includes(nodes[i].pid)) {
              rel.depList.push(nodes[i].pid);
            }
            if (!rel.tenantList.includes(nodes[i].tenantId)) {
              rel.tenantList.push(nodes[i].tenantId);
            }
            const fitem = findNode(nodes[i].pid);
            if (fitem && fitem.pid > 0) {
              if (!rel.cmpList.includes(fitem.pid))
                rel.cmpList.push(fitem.pid);
            }
          }
        }
      }
      return rel;
    };
    const filterNode = (value, data) => {
      if (!value) return true;
      return data.name.includes(value);
    };
    const handleCommand = async (command) => {
      var _a;
      if ("expandAll" == command) {
        for (let i = 0; i < treeRef.value.store._getAllNodes().length; i++) {
          treeRef.value.store._getAllNodes()[i].expanded = true;
        }
      } else if ("collapseAll" == command) {
        for (let i = 0; i < treeRef.value.store._getAllNodes().length; i++) {
          treeRef.value.store._getAllNodes()[i].expanded = false;
        }
      } else if ("refresh" == command) {
        if (props.apiService != "" && props.apiAction != "")
          fetchTreeData();
        else
          emit("refresh");
      } else if ("rootNode" == command) {
        (_a = treeRef.value) == null ? void 0 : _a.setCurrentKey();
        modeValue.value = { id: 0, name: "", code: "" };
        emit("node-click", { id: 0, name: "", code: "" });
      }
    };
    const emit = __emit;
    const nodeClick = (node) => {
      const reldata = findNode(node.id);
      modeValue.value = { id: node.id, name: node.name, code: reldata ? reldata.code : "" };
      let cmpId = 0;
      let deptId = 0;
      let groupId = 0;
      if (reldata) {
        cmpId = reldata.id;
        if (reldata.level == 2) {
          deptId = reldata.id;
          cmpId = reldata.pid;
          groupId = 0;
        } else if (reldata.level == 3) {
          groupId = reldata.id;
          deptId = reldata.pid;
          const fitem = findNode(reldata.pid);
          if (fitem && fitem.pid > 0) {
            cmpId = fitem.pid;
          }
        }
      }
      emit("node-click", { id: node.id, name: node.name, code: reldata ? reldata.code : "", data: reldata, cmpId, deptId, groupId });
    };
    const findNode = (id) => {
      const search = (nodes) => {
        var _a;
        for (const node of nodes) {
          if (node.id === id) return node;
          if ((_a = node.children) == null ? void 0 : _a.length) {
            const found = search(node.children);
            if (found) return found;
          }
        }
        return null;
      };
      return search(state.folderData || []);
    };
    const setCheckedKeys = (orgData) => {
      state.isShowCheckbox = true;
      treeRef.value.setCheckedKeys(orgData);
    };
    const setCurrentKey = (key, shouldAutoExpandParent) => {
      var _a;
      (_a = treeRef.value) == null ? void 0 : _a.setCurrentKey(key, shouldAutoExpandParent);
    };
    __expose({ fetchTreeData, getCheckedKeys, getCheckedKeysByCmp, setCheckedKeys, setCurrentKey });
    return (_ctx, _cache) => {
      const _component_el_input = resolveComponent("el-input");
      const _component_el_checkbox = resolveComponent("el-checkbox");
      const _component_el_icon = resolveComponent("el-icon");
      const _component_el_button = resolveComponent("el-button");
      const _component_el_dropdown_item = resolveComponent("el-dropdown-item");
      const _component_el_dropdown_menu = resolveComponent("el-dropdown-menu");
      const _component_el_dropdown = resolveComponent("el-dropdown");
      const _component_el_tree = resolveComponent("el-tree");
      const _component_el_scrollbar = resolveComponent("el-scrollbar");
      const _component_el_card = resolveComponent("el-card");
      const _directive_loading = resolveDirective("loading");
      return openBlock(), createBlock(_component_el_card, {
        shadow: "hover",
        "body-style": "height:100%;overflow:auto;padding:5px;width:100%;",
        style: { "height": "100%" }
      }, {
        header: withCtx(() => [
          createElementVNode("div", _hoisted_1, [
            createElementVNode("div", _hoisted_2, [
              createElementVNode("div", _hoisted_3, [
                createVNode(_component_el_input, {
                  "prefix-icon": unref(Search),
                  modelValue: filterText.value,
                  "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => filterText.value = $event),
                  modelModifiers: { lazy: true },
                  clearable: "",
                  placeholder: __props.placeholder
                }, null, 8, ["prefix-icon", "modelValue", "placeholder"])
              ]),
              createElementVNode("div", _hoisted_4, [
                !props.checkStrictly && state.isShowCheckbox ? (openBlock(), createBlock(_component_el_checkbox, {
                  key: 0,
                  modelValue: state.strictly,
                  "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => state.strictly = $event),
                  label: "\u8054\u52A8",
                  style: { "margin-left": "8px" },
                  border: ""
                }, null, 8, ["modelValue"])) : createCommentVNode("v-if", true),
                createVNode(_component_el_dropdown, { onCommand: handleCommand }, {
                  dropdown: withCtx(() => [
                    createVNode(_component_el_dropdown_menu, null, {
                      default: withCtx(() => [
                        createVNode(_component_el_dropdown_item, { command: "expandAll" }, {
                          default: withCtx(() => [..._cache[2] || (_cache[2] = [
                            createTextVNode(
                              "\u5168\u90E8\u5C55\u5F00",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        }),
                        createVNode(_component_el_dropdown_item, { command: "collapseAll" }, {
                          default: withCtx(() => [..._cache[3] || (_cache[3] = [
                            createTextVNode(
                              "\u5168\u90E8\u6298\u53E0",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        }),
                        createVNode(_component_el_dropdown_item, { command: "rootNode" }, {
                          default: withCtx(() => [..._cache[4] || (_cache[4] = [
                            createTextVNode(
                              "\u6839\u8282\u70B9",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        }),
                        createVNode(_component_el_dropdown_item, { command: "refresh" }, {
                          default: withCtx(() => [..._cache[5] || (_cache[5] = [
                            createTextVNode(
                              "\u5237\u65B0",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        })
                      ]),
                      _: 1
                      /* STABLE */
                    })
                  ]),
                  default: withCtx(() => [
                    createVNode(_component_el_button, { style: { "margin-left": "8px", "width": "34px" } }, {
                      default: withCtx(() => [
                        createVNode(_component_el_icon, { class: "el-icon--center" }, {
                          default: withCtx(() => [
                            createVNode(unref(MoreFilled))
                          ]),
                          _: 1
                          /* STABLE */
                        })
                      ]),
                      _: 1
                      /* STABLE */
                    })
                  ]),
                  _: 1
                  /* STABLE */
                })
              ])
            ])
          ])
        ]),
        default: withCtx(() => [
          withDirectives((openBlock(), createElementBlock("div", _hoisted_5, [
            createVNode(_component_el_scrollbar, null, {
              default: withCtx(() => [
                createVNode(_component_el_tree, {
                  ref_key: "treeRef",
                  ref: treeRef,
                  class: "filter-tree",
                  data: state.folderData,
                  "node-key": __props.nodeKey,
                  props: __props.defaultProps,
                  "filter-node-method": filterNode,
                  onNodeClick: nodeClick,
                  "show-checkbox": state.isShowCheckbox,
                  "default-expand-all": "",
                  "highlight-current": "",
                  "check-strictly": !state.strictly
                }, {
                  default: withCtx(({ node }) => [
                    createCommentVNode(' <el-icon v-if="node.level < 4" size="16" style="margin-right: 3px; display: inline; vertical-align: middle"><ele-FolderOpened /></el-icon>\r\n						<el-icon v-else size="16" style="margin-right: 3px; display: inline; vertical-align: middle"><ele-Folder /></el-icon> '),
                    createTextVNode(
                      " " + toDisplayString(node.label),
                      1
                      /* TEXT */
                    )
                  ]),
                  _: 1
                  /* STABLE */
                }, 8, ["data", "node-key", "props", "show-checkbox", "check-strictly"])
              ]),
              _: 1
              /* STABLE */
            })
          ])), [
            [_directive_loading, state.loading]
          ])
        ]),
        _: 1
        /* STABLE */
      });
    };
  }
});

export { _sfc_main as default };
