<template>
  <div v-if="visible" class="mindmap-modal" style="user-select: none">
    <div class="mindmap-modal_tool">
      <el-form ref="formRef" :model="formData" class="flex items-center" inline>
        <el-form-item label="收缩至" prop="level" class="mr-12px">
          <el-select
            v-model="formData.level"
            placeholder="请选择"
            style="width: 120px"
            @change="changeLevel"
          >
            <el-option
              v-for="item in 10"
              :key="item"
              :label="`${item}级`"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="布局" prop="layout" class="mr-12px">
          <el-select
            v-model="formData.layout"
            placeholder="请选择"
            style="width: 120px"
            @change="changeLayout"
          >
            <el-option label="逻辑右" value="logicalStructure" />
            <el-option label="逻辑左" value="logicalStructureLeft" />
            <el-option label="垂直" value="organizationStructure" />
          </el-select>
        </el-form-item>
        <el-form-item label="搜索" props="search">
          <div class="flex">
            <el-input v-model="formData.search" style="width: 120px" />
            <el-button
              class="ml-12px"
              :icon="Search"
              @click="handleSearch"
            ></el-button>
          </div>
        </el-form-item>
      </el-form>
      <div class="flex gap-4px">
        <el-button type="primary" link @click="handleSave" class="mr-8px"
          ><img class="w-1em mr-4px" :src="saveImg" />保存</el-button
        >
        <!-- <el-tooltip content="添加">
          <el-button
            type="default"
            circle
            :icon="CirclePlusFilled"
            @click="addNode"
          />
        </el-tooltip> -->
        <el-tooltip content="详情">
          <el-button
            type="default"
            circle
            :icon="InfoFilled"
            @click="openNodeDetail"
          />
        </el-tooltip>
        <el-tooltip content="自适应">
          <el-button type="default" circle @click="autoFit">
            <img :src="AutoIcon" style="width: 1em" />
          </el-button>
        </el-tooltip>
        <el-tooltip content="定位到根节点">
          <el-button type="default" circle :icon="Aim" @click="zoomToRoot" />
        </el-tooltip>
        <el-tooltip content="放大">
          <el-button
            type="default"
            circle
            :icon="ZoomIn"
            @click="handleZoom(1)"
          />
        </el-tooltip>
        <el-tooltip content="缩小">
          <el-button
            type="default"
            circle
            :icon="ZoomOut"
            @click="handleZoom(0)"
          />
        </el-tooltip>
      </div>
    </div>
    <div class="mindmap-modal_body">
      <Mindmap
        v-model:data="data"
        ref="mindmapRef"
        @node-dbl-click="handleNodeDbClick"
      />
    </div>
    <!-- <div class="mindmap-modal_footer">
    </div> -->
  </div>

  <ConfigDrawer ref="configDrawerRef" @ok="handleConfigOk"/>
</template>

<script setup lang="ts">
import { ref, defineExpose, reactive, defineProps, watch } from "vue";
import {
  Aim,
  // CirclePlusFilled,
  // Close,
  InfoFilled,
  Search,
  ZoomIn,
  ZoomOut,
} from "@element-plus/icons-vue";
import type { MindMapInstance } from "@/components/mindmap/Mindmap.vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { bfsWalk } from "simple-mind-map/src/utils";
// import { useEditBomStore } from "@/store/editbom";

import Mindmap from "@/components/mindmap/Mindmap.vue";
import ConfigDrawer from "./ConfigDrawer.vue";
import AutoIcon from "@/assets/auto.svg";
import saveImg from "@/assets/save.svg";

const props = defineProps<{
  defaultOpen?: boolean;
  hideClose?: boolean;
  defaultData?: any;
}>();

const visible = ref(!!props.defaultOpen);
const mindmapRef = ref<MindMapInstance>();
const configDrawerRef = ref();
const formRef = ref<FormInstance>();
// const editBomStore = useEditBomStore();
const data = ref(
  props?.defaultData || {
    id: "root",
    data: {
      name: "根节点",
    },
    children: [],
  }
);

// 1、初次读取本地缓存配置
const defaultConfig = JSON.parse(localStorage.getItem("mindmap-config") || "{}");
const formData = reactive({
  level: defaultConfig?.level,
  layout: defaultConfig?.layout ?? "logicalStructure",
  search: defaultConfig?.search || "",
});

// 2、监听配置项变化，保存到本地缓存
watch(
  () => formData,
  (val) => {
    localStorage.setItem("mindmap-config", JSON.stringify(val));
  },
  {
    deep: true
  }
);

// 定位到根节点
const zoomToRoot = () => {
  const mindmap = mindmapRef.value?.getInstance();
  mindmap?.renderer?.setRootNodeCenter();
};

// 切换布局
const changeLayout = (value: string) => {
  const mindmap = mindmapRef.value?.getInstance();
  mindmap?.setLayout(value);
  let fited = false;
  mindmap?.on("node_tree_render_end", () => {
    // @ts-ignore
    !fited && mindmap?.view?.fit();
    fited = true;
  });
};

// 切换层级
const changeLevel = (level: number) => {
  const mindmap = mindmapRef.value?.getInstance();
  mindmap?.execCommand("UNEXPAND_TO_LEVEL", level);
};

const autoFit = () => {
  const mindmap = mindmapRef.value?.getInstance();
  // @ts-ignore
  mindmap?.view?.fit();
};

// 节点详情
const openNodeDetail = () => {
  const activeList = mindmapRef.value?.getActiveNodeList();
  if (!activeList?.length) {
    ElMessage.warning("请选择查看节点");
    return;
  }
  configDrawerRef.value.open(activeList[0].nodeData);
};

// 缩放
const handleZoom = (num: number) => {
  const mindmap = mindmapRef.value?.getInstance();
  if (num) {
    // @ts-ignore
    mindmap?.view?.enlarge();
  } else {
    // @ts-ignore
    mindmap?.view?.narrow();
  }
};

// 添加节点
// const addNode = () => {
//   const mindmap = mindmapRef.value?.getInstance();
//   const activeList = mindmapRef.value?.getActiveNodeList();
//   if (!activeList?.length) {
//     ElMessage.warning("请选择父节点");
//     return;
//   }

//   mindmap?.execCommand("INSERT_CHILD_NODE");
// };

// 搜索
const handleSearch = () => {
  const result: any[] = [];
  const mindmap = mindmapRef.value?.getInstance();
  const data = mindmap?.getData(false);
  mindmap?.execCommand("CLEAR_ACTIVE_NODE");
  bfsWalk(data, (node: any) => {
    if (node.data?.name?.includes(formData.search)) {
      result.push(node);
    }
  });

  if (result.length) {
    result.forEach((node) => {
      const n = mindmap?.renderer.findNodeByUid(node.data?.uid);
      n?.active();
    });
  } else {
    ElMessage.warning("未找到节点");
  }
};

const handleNodeDbClick = (node: any) => {
  console.log("handleNodeDbClick", node);
  if (node.isRoot) return;
  configDrawerRef.value.open(node.nodeData);
};

// 节点配置结束
const handleConfigOk = (updateNodeData: any) => {
  const mindmap = mindmapRef.value?.getInstance();
  const allData = mindmap?.getData(false);
  bfsWalk(allData, (node: any) => {
    if (node.data.uid === updateNodeData.uid) {
      node.data = updateNodeData;
    }
  });
  mindmap?.updateData(allData);
}
// 保存
const handleSave = () => {
  const mindmap = mindmapRef.value?.getInstance();
  const data = mindmap?.getData(false);
  
  bfsWalk(data, (node: any) => {
    delete node.smmVersion;
    delete node.data.uid;
    delete node.data.expand;
    delete node.data.isActive;
  });

  console.log("保存数据：", data);
  try {
    window.parent?.BpmTools?.program(
      {
        interfaceCode: "Common.doSaveBOMAiImageData",
        model: data,
      },
      (res: any) => {
        console.log("保存结果：", res);
        ElMessage.success("保存成功！");
      }
    );
  } catch (error) {
    console.log(error);
    ElMessage.error("保存失败！");
  }
};

watch(
  () => props?.defaultData,
  (val) => {
    data.value = val;
  }
);

// 打开弹窗
const open = () => {
  visible.value = true;
};

// 关闭弹窗
const close = () => {
  formRef.value?.resetFields();
  visible.value = false;
};

defineExpose({
  open,
  close,
});
</script>

<style lang="less" scoped>
.mindmap-modal {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
  display: flex;
  flex-direction: column;
  align-items: center;
  &_footer {
    height: 40px;
    width: 100%;
    box-sizing: border-box;
    background: #fff;
    display: flex;
    // justify-content: end;
    align-items: center;
    padding: 0 20px;
    line-height: 40px;
  }
  &_tool {
    width: 100%;
    box-sizing: border-box;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
  }
  &_body {
    flex: 1;
    width: 100%;
    background: #fafafa;
    overflow: hidden;
  }
}

:deep(*) {
  .el-form-item {
    margin-top: 12px;
    margin-bottom: 12px;
  }
}
</style>
