<template>
  <div class="LayerTree lightOrDark2">
    <!-- 三个蓝色方块标题 -->
    <div class="title">
      <div class="title-button lightOrDark1">
        <a-popover placement="bottom" trigger="click">
          <template #content>
            <span
              class="content lightOrDark3"
              :class="{ 'active-style': bottomSpan == 1 }"
              @click="bottomSpan = 1"
            >
              底层
            </span>
            <span
              class="content lightOrDark3"
              :class="{ 'active-style': bottomSpan == 2 }"
              @click="bottomSpan = 2"
            >
              地形
            </span>
            <span
              class="content lightOrDark3"
              :class="{ 'active-style': bottomSpan == 3 }"
              @click="bottomSpan = 3"
            >
              图层树
            </span>
          </template>
          <div class="title-button-image"><MenuOutlined /></div>
          <span class="title-button-span lightOrDark1">图层</span>
          <div class="title-button-imagedown"><DownOutlined /></div>
        </a-popover>
      </div>
      <div class="title-button lightOrDark1">
        <div class="title-button-image"><SettingOutlined /></div>
        <span class="title-button-span lightOrDark1">控件</span>
      </div>
      <div class="title-button lightOrDark1">
        <div class="title-button-image"><StarOutlined /></div>
        <span class="title-button-span">特效</span>
      </div>
    </div>

    <div class="tree lightOrDark1">
      <!-- 树之上的按钮 -->
      <div style="height: 15px" />
      <div class="tree-title">
        <div class="tree-title-left"> 图层结构 </div>
        <div class="tree-title-right">
          <FolderOutlined v-if="expandedKeys.length == 0" @click="expandAll(true)" />
          <FolderOpenOutlined v-if="expandedKeys.length > 0" @click="expandAll(false)" />
          <a-divider type="vertical" />
          <a-popover placement="bottom">
            <template #content>
              <span
                class="content lightOrDark3"
                :class="{ 'active-style': treeTitleSpan == 1 }"
                @click="treeTitleSpan = 1"
              >
                新建目录
              </span>
              <span
                class="content lightOrDark3"
                :class="{ 'active-style': treeTitleSpan == 2 }"
                @click="openImportModal"
              >
                导入图层
              </span>
              <span
                class="content lightOrDark3"
                :class="{ 'active-style': treeTitleSpan == 3 }"
                @click="treeTitleSpan = 3"
              >
                修改目录名称
              </span>
              <span
                class="content lightOrDark3"
                :class="{ 'active-style': treeTitleSpan == 4 }"
                @click="treeTitleSpan = 4"
              >
                删除
              </span>
            </template>
            <PlusCircleOutlined />
          </a-popover>
        </div>
      </div>
      <!-- 树 -->
      <div style="height: 15px" />
      <div class="tree-content">
        <a-tree
          checkable
          v-model:checkedKeys="checkedKeys"
          v-model:selectedKeys="selectedKeys"
          :tree-data="treeData"
          :selectable="true"
          :defaultExpandAll="true"
          :blockNode="true"
          @select="onSelect"
        >
          <!-- v-model:expandedKeys="expandedKeys" -->
          <template #title="{ title, key }">
            <span v-if="treeStatus == 'add'" style="width: 100%">
              {{ title }}
              <PlusOutlined
                style="position: absolute; top: 3px; right: 20px"
                @click="openAddModal(key)"
              />
            </span>
            <span v-if="treeStatus == 'edit'">
              {{ title }}
              <EditOutlined
                style="position: absolute; top: 3px; right: 20px"
                @click="openEditModal(key, title)"
              />
            </span>
            <span v-if="treeStatus == 'delete'">
              {{ title }}
              <DeleteOutlined
                style="position: absolute; top: 3px; right: 20px"
                @click="deleteTreeKey(key)"
              />
            </span>
            <span v-if="treeStatus == ''">{{ title }}</span>
          </template>
        </a-tree>
      </div>
    </div>
    <!-- 新建目录 -->
    <a-modal
      title="新建目录"
      :open="addModalOpen"
      :width="400"
      :maskClosable="false"
      :centered="true"
      @cancel="addModalClose"
      @ok="addModalSubmit"
    >
      <div style="margin: 10px">
        <a-tree-select
          v-model:value="addModalData.parentkey"
          style="width: 100%; margin-bottom: 10px"
          tree-default-expand-all
          :tree-data="treeData"
          :field-names="{
            children: 'children',
            label: 'title',
            value: 'key',
          }"
          placeholder="请选择上级"
        >
        </a-tree-select>
        <a-input
          style="width: 100%; margin-bottom: 10px"
          v-model:value="addModalData.key"
          placeholder="请输入key"
        />
        <a-input v-model:value="addModalData.title" placeholder="请输入标题名称" />
      </div>
    </a-modal>
    <!-- 修改目录名称 -->
    <a-modal
      title="修改目录名称"
      :open="editModalOpen"
      :width="400"
      :maskClosable="false"
      :centered="true"
      @cancel="editModalClose"
      @ok="editModalSubmit"
    >
      <div style="margin: 10px">
        <a-input v-model:value="editModalData.title" placeholder="请输入标题名称" />
      </div>
    </a-modal>
    <!-- 导入 -->
    <LayerImport :importOpen="importOpen" @importModalClose="importModalClose" />
  </div>
</template>

<script setup lang="ts">
  import { ref, defineEmits, defineProps, watch, onMounted } from 'vue';
  import {
    MenuOutlined,
    SettingOutlined,
    StarOutlined,
    DownOutlined,
    FolderOutlined,
    FolderOpenOutlined,
    PlusCircleOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    CloseOutlined,
  } from '@ant-design/icons-vue';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import type { TreeProps } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { createVNode } from 'vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import LayerImport from './import/index.vue';
  import { prepareTreeData } from './util.ts';

  const { createMessage } = useMessage();

  const bottomSpan = ref(0);

  const selectedKeys = ref<string[]>([]);
  const expandedKeys = ref<string[]>([]);
  const checkedKeys = ref<string[]>([]);
  const treeData: any = ref(prepareTreeData);

  const treeTitleSpan = ref(0);
  const treeStatus = ref('');
  watch(
    () => treeTitleSpan.value,
    () => {
      switch (treeTitleSpan.value) {
        case 1:
          treeStatus.value = 'add';
          break;
        case 2:
          treeStatus.value = '';
          break;
        case 3:
          treeStatus.value = 'edit';
          break;
        case 4:
          treeStatus.value = 'delete';
          break;
        default:
          break;
      }
    },
  );

  // 展开--------------------------------------------------------------------
  const expandAll = (value) => {
    if (value) {
      // 展开全部
      treeData.value.forEach((rootNode) => extractKeys(rootNode));
    } else {
      expandedKeys.value = [];
    }
  };
  // 全部树的key
  let allKeys: any = [];
  function extractKeys(node) {
    if (node.key) {
      allKeys.push(node.key);
    }
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => extractKeys(child));
    }
  }

  // 添加--------------------------------------------------------------------
  const addModalOpen = ref(false);
  const addModalData = ref({
    parentkey: null,
    key: null,
    title: null,
  });
  // 开启
  function openAddModal(key) {
    addModalData.value.parentkey = key;
    addModalData.value.key = null;
    addModalData.value.title = null;
    addModalOpen.value = true;
  }
  // 点击遮罩层或右上角叉或取消按钮的回调
  function addModalClose() {
    addModalOpen.value = false;
  }
  // 点击确定回调
  function addModalSubmit() {
    treeData.value.forEach((rootNode) => extractKeys(rootNode));
    if (allKeys.includes(addModalData.value.key)) {
      createMessage.error('key值不能与树中的重复！');
      return;
    }
    const newSubNode = { title: addModalData.value.title, key: addModalData.value.key };
    const result = addSubNode(treeData.value, addModalData.value.parentkey, newSubNode);
    if (result) {
      createMessage.success('添加成功！');
      addModalOpen.value = false;
    }
  }
  // 添加子节点
  function addSubNode(tree, targetKey, newNode) {
    for (let node of tree) {
      if (node.key === targetKey) {
        if (!node.children) {
          node.children = [];
        }
        node.children.push(newNode);
        return true;
      }
      if (node.children && addSubNode(node.children, targetKey, newNode)) {
        return true;
      }
    }
    return false;
  }
  // 编辑--------------------------------------------------------------------
  const editModalOpen = ref(false);
  const editModalData = ref({
    parentkey: null,
    key: null,
    title: null,
  });
  // 开启
  function openEditModal(key, title) {
    editModalData.value.key = key;
    editModalData.value.title = title;
    editModalOpen.value = true;
  }
  // 点击遮罩层或右上角叉或取消按钮的回调
  function editModalClose() {
    editModalOpen.value = false;
  }
  // 点击确定回调
  function editModalSubmit() {
    const newSubNode = { title: editModalData.value.title, key: editModalData.value.key };
    const result = editSubNode(treeData.value, editModalData.value.key, newSubNode);
    if (result) {
      createMessage.success('修改成功！');
      editModalOpen.value = false;
    }
  }
  // 编辑子节点
  function editSubNode(tree, targetKey, newNode) {
    for (let i = 0; i < tree.length; i++) {
      let node = tree[i];
      if (node.key === targetKey) {
        Object.assign(node, newNode);
        return true;
      }
      if (node.children && node.children.length > 0) {
        if (editSubNode(node.children, targetKey, newNode)) {
          return true;
        }
      }
    }
    return false;
  }
  // 删除--------------------------------------------------------------------
  // 删除
  function deleteTreeKey(key) {
    if (key == treeData.value[0].key) {
      createMessage.warn('根分支不能删除！');
      return;
    }
    Modal.confirm({
      title: '是否确认删除?',
      icon: createVNode(ExclamationCircleOutlined),
      onCancel() {},
      onOk() {
        // 删除
        let res = deleteNode(treeData.value, key);
        if (res) {
          createMessage.success('所选分支删除成功！');
        } else {
          createMessage.error('所选分支删除失败！');
        }
      },
    });
  }
  // 找到目标节点，从数组中删除
  function deleteNode(tree, targetKey) {
    for (let i = 0; i < tree.length; i++) {
      if (tree[i].key === targetKey) {
        tree.splice(i, 1);
        return true;
      }
      if (tree[i].children && tree[i].children.length > 0) {
        if (deleteNode(tree[i].children, targetKey)) {
          return true;
        }
      }
    }
    return false;
  }

  // 导入--------------------------------------------------------------------
  const importOpen = ref(false);
  function openImportModal() {
    importOpen.value = true;
    treeTitleSpan.value = 2;
  }
  function importModalClose() {
    importOpen.value = false;
    treeTitleSpan.value = 0;
  }

  onMounted(() => {
    // 展开全部
    expandAll(true);
  });
</script>

<style lang="less" scoped>
  html[data-theme='light'] {
    .lightOrDark1 {
      background-color: #ffffff;
    }
    .lightOrDark2 {
      background-color: #e0e5ed;
    }
    .lightOrDark3 {
      background-color: #ffffff;
    }
  }
  [data-theme='dark'] {
    .lightOrDark1 {
      background-color: #000000;
    }
    .lightOrDark2 {
      background-color: #000000;
    }
    .lightOrDark3 {
      background-color: #1f1f1f;
    }
  }
  .active-style {
    background-color: #e0e5ed;
    color: #0081ff;
  }

  ::v-deep .ant-tree {
    font-size: 18px !important;
  }
  ::v-deep .ant-popover-inner-content {
    padding: 0px !important;
  }
  ::v-deep .ant-tree-checkbox {
    font-size: 18px;
    align-self: auto !important;
  }

  .LayerTree {
    position: absolute;
    top: 0;
    left: 0;
    width: 356px;
    height: 100%;

    .title {
      height: 90px;
      margin-top: 5px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .title-button {
      border-radius: 5px;
      width: 70px;
      height: 85px;
      margin-left: 10px;
      margin-right: 10px;
      font-size: 20px;
    }

    .title-button-image {
      display: flex;
      justify-content: center;
      background-color: #0081ff;
      border-radius: 5px;
      margin-top: 10px;
      margin-left: 15px;
      width: 40px;
      height: 40px;
    }

    .title-button-span {
      display: flex;
      justify-content: center;
      margin-top: 5px;
      font-size: 16px;
    }

    .title-button-imagedown {
      display: flex;
      justify-content: center;
      color: gray;
      font-size: 10px;
    }
  }

  .content {
    display: block;
    width: 120px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .tree {
    height: calc(100% - 110px);
    // background-color: #e0e5ed;
    background-color: #ffffff;
    margin-top: 20px;
    border-radius: 10px;

    .tree-title {
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      margin-left: 10px;
      margin-right: 10px;
      background-color: #e0e5ed;
      height: 40px;
      font-size: 20px;
      display: flex;
      align-items: center;

      .tree-title-left {
        display: inline-flex;
        align-items: center;
        gap: 8px;
      }

      .tree-title-left::before {
        content: '';
        width: 8px;
        height: 8px;
        background-color: green;
        border-radius: 50%;
        margin-left: 10px;
      }

      .tree-title-right {
        position: absolute;
        right: 30px;
      }
    }

    .tree-content {
      margin-left: 10px;
    }
  }
</style>
