<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 30"
              :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 items-center gap-4px">
        <span class="text-12px text-green mr-12px"
          >最新版本号：{{ latestVersion || "-" }}</span
        >
        <span class="text-12px mr-12px font-bold text-#f56c6c"
          >{{ type == "1" ? "工程BOM" : "制造BOM" }}编辑</span
        >
        <span class="text-12px text-yellow mr-12px"
          >当前版本号：{{ version || "-" }}</span
        >
        <el-button type="primary" link @click="handleSave" class="mr-8px"
          ><img class="w-1em mr-4px" :src="saveImg" alt="" />保存</el-button
        >
        <el-tooltip content="添加" v-if="type == '1' && !readonly">
          <el-button
            type="default"
            circle
            :icon="CirclePlusFilled"
            @click="addNode"
          />
        </el-tooltip>
        <el-tooltip content="删除" v-if="type == '1' && !readonly">
          <el-button
            type="default"
            circle
            :icon="DeleteFilled"
            @click="removeNode"
          />
        </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" alt="" />
          </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"
        :type="type"
        :readonly="type == '2' || readonly"
        @node-dbl-click="handleNodeDbClick"
        @data-change="handleDataChange"
      />
    </div>
    <!-- <div class="mindmap-modal_footer">
    </div> -->
  </div>

  <!-- 工程bom -->
  <ConfigDrawerProject
    v-if="type == '1'"
    ref="configDrawerRef"
    @ok="handleConfigOk"
    :readonly="readonly"
  />
  <!-- 制造bom -->
  <ConfigDrawerProduction
    v-else
    ref="configDrawerRef"
    @ok="handleConfigOk"
    :readonly="readonly"
  />
</template>

<script setup lang="ts">
import {
  ref,
  defineExpose,
  reactive,
  defineProps,
  watch,
  onMounted,
  onBeforeUnmount,
  defineEmits,
  inject,
  computed,
  type Ref,
} from "vue";
import {
  Aim,
  CirclePlusFilled,
  DeleteFilled,
  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, ElMessageBox } from "element-plus";
import { bfsWalk, walk } from "simple-mind-map/src/utils";

import Mindmap from "@/components/mindmap/Mindmap.vue";
import ConfigDrawerProject from "./ConfigDrawerProject.vue";
import ConfigDrawerProduction from "./ConfigDrawerProduction.vue";
import AutoIcon from "@/assets/auto.svg";
import saveImg from "@/assets/save.svg";
import { BOMItem } from "./data";
import { cloneDeep } from "lodash-es";

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

const latestVersion = inject<Ref<string>>("latestVersion");
const visible = ref(!!props.defaultOpen);
const mindmapRef = ref<MindMapInstance>();
const configDrawerRef = ref();
const formRef = ref<FormInstance>();
const emit = defineEmits(["refresh"]);
// const editBomStore = useEditBomStore();

const data = ref(
  props?.defaultData || {
    id: "root",
    data: {
      name: "根节点",
    },
    children: [],
  }
);

// 当前版本号与最新版本号不一致时，禁止修改
const readonly = computed(() => {
  return props.version != latestVersion?.value;
});

// 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?.clearActiveNode();
  mindmap?.renderer?.setRootNodeCenter();
  const data = mindmap?.getData(false);
  const root = mindmap?.renderer.findNodeByUid(data?.data?.uid);
  root?.active();
};

// 切换布局
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 removeNode = () => {
  const mindmap = mindmapRef.value?.getInstance();
  const activeList = mindmapRef.value
    ?.getActiveNodeList()
    ?.filter((node) => !node?.isRoot);
  if (!activeList?.length) {
    ElMessage.warning("请选择删除节点");
    return;
  }

  // 原有数据将is_delete设置为true 新增数据直接删除
  const updateNodes: any[] = [];
  const deleteNodes: any[] = [];
  activeList.forEach((node) => {
    bfsWalk(node, (child: any) => {
      if (child.nodeData?.id) {
        updateNodes.push(child);
      } else {
        deleteNodes.push(child);
      }
    });
  });

  ElMessageBox.alert("确认删除节点?", "提示", {
    confirmButtonText: "确认",
    callback: (action: string) => {
      // 执行删除
      if (action === "confirm") {
        deleteNodes.length && mindmap?.execCommand("REMOVE_NODE", deleteNodes);
        updateNodes.forEach((node) => {
          handleConfigOk({
            ...node?.nodeData.data,
            is_deleted: true,
            bom_det: node?.nodeData.data?.bom_det || {},
          });
        });
      }
    },
  });
};

// 搜索
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) => {
      mindmap?.renderer?.expandToNodeUid(node.data?.uid);
    });

    setTimeout(() => {
      const list = result.map((node) =>
        mindmap?.renderer.findNodeByUid(node.data?.uid)
      );
      mindmap?.renderer?.activeMultiNode(list);
    }, 300);
  } 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);
  let valid = true;
  // let hasAddData = false;

  bfsWalk(data, (node: any) => {
    delete node?.smmVersion;
    delete node.data?.uid;
    delete node.data?.expand;
    delete node.data?.isActive;
    delete node.data?.richText;
    delete node.data?.text;
    delete node.data?.id;
    // TODO: 业务校验
    // if (!node.data.name?.trim()) {
    //   valid = false;
    // }
    // if(node.data.is_add) {
    //   hasAddData = true;
    // }
  });
  console.log("node:", data);

  if (!valid) {
    ElMessage.error("请检查数据是否填写完整！");
    return;
  }
  // 添加版本号
  data.version = props.version;

  try {
    window.parent?.BpmTools?.program(
      {
        interfaceCode: "Common.doSaveBOMAiImageData",
        model: data,
      },
      () => {
        ElMessage.success(`保存成功！`);
        emit("refresh");
      }
    );
  } catch (error) {
    console.log(error);
    ElMessage.error("保存失败！");
  }
};

// 数据变化 处理新增数据
const handleDataChange = (newData: any) => {
  // 新增数据
  const addItem = newData?.find((item: any) => item.action === "create");
  if (addItem && !addItem.data.data?.name) {
    const newItemData = new BOMItem();
    delete addItem.data.data.text;
    const newNodeData = {
      ...(addItem?.data || {}),
      data: {
        ...addItem?.data?.data,
        is_deleted: false,
        is_disable: false,
        is_change: false,
        is_add: true,
        qty: undefined,
        name: "",
        type: "",
        bom_code: "",
        change_content: "",
        bom_det: newItemData,
      },
    };
    handleConfigOk(newNodeData.data);
    const mindmap = mindmapRef.value?.getInstance();
    const nodeData = mindmap?.renderer.findNodeByUid(newNodeData?.data?.uid);

    configDrawerRef.value.open(newNodeData, "add", nodeData.layerIndex);
  }
};

watch(
  () => props?.defaultData,
  (val) => {
    // 设置初始化加载层级
    walk(val, null, (node: any, _p: any, _isRoot: any, layerIndex: number) => {
      node.data.id = node?.id;
      if (formData.level && layerIndex >= formData.level) {
        node.data.expand = false;
      }
    });
    data.value = val;
  }
);

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

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

defineExpose({
  open,
  close,
});

const handlePressDel = (e: KeyboardEvent) => {
  // 删除节点
  if (
    e.key === "Delete" &&
    visible.value &&
    props.type == "1" &&
    !readonly.value
  ) {
    e.preventDefault();
    removeNode();
  }
};

watch(
  () => data.value,
  () => {
    const result = cloneDeep(data.value);
    if (result?.id && result.id !== "root") {
      bfsWalk(result, (node: any) => {
        delete node.smmVersion;
        delete node.data?.uid;
        delete node.data?.expand;
        delete node.data?.isActive;
        delete node.data?.richText;
        delete node.data?.text;
        delete node.data?.id;
      });
      // 缓存编辑结果
      sessionStorage.setItem(result.id, JSON.stringify(result));
    }
  }
);

onMounted(() => {
  addEventListener("keydown", handlePressDel);
});

onBeforeUnmount(() => {
  removeEventListener("keydown", handlePressDel);
});
</script>

<style lang="less" scoped>
.mindmap-modal {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  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>
