<template>
  <div>
    <a-menu mode="inline" :selectedKeys="selectedKeys" :openKeys="openKeys" :multiple="multiple" :disabled="see"
      @openChange="handleOpenChange" :style="{ overflowY: 'auto', height: `${height}` }">
      <menu-item-node v-for="node in treeData" :key="node.value" :node="node" @select="handleSelectFromNode"
        @edit="openEditGroup" @delete="confirmDeleteGroup" @add-child="openAddChildOf" />
    </a-menu>

    <div style="text-align: center;">
      <a-button type="link" @click.stop="openAddGroup(node)" style="margin: 0 10px 10px 10px;">
        添加根级
      </a-button>
    </div>

    <a-modal v-model:open="groupModalVisible" :closable="true" :maskClosable="true" :draggable="true"
      :title="groupInfo.isChild ? '添加子级' : '添加根级'">
      <a-form ref="formRef" :model="groupInfo">
        <a-form-item label="分组名称" :rules="[{ required: true, message: '请输入分组名称' }]">
          <a-input v-model:value="groupInfo.groupName" />
        </a-form-item>
      </a-form>

      <template #footer>
        <a-button @click="groupModalVisible = false">取消</a-button>
        <a-button type="primary" :loading="submitLoading" @click="submitGroup">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>
import MenuItemNode from "./MenuItemNode.vue";

export default {
  name: "PaasTreePanel",
  components: { MenuItemNode },
  computed: {
    see() {
      return this.$store?.forms?.see || false;
    }
  },
  props: {
    placeholder: String,
    multiple: Boolean,
    disabled: Boolean,
    open: Boolean,
    groupType: String,
    params: Object,
    checkable: Boolean,
    modelValue: [String, Array],
    height: { type: String, default: 'calc(100vh - 300px)' },
    listToTree: { type: Boolean, default: true },
  },
  emits: ['update:modelValue', 'change'],
  data() {
    return {
      selectedKeys: [],
      openKeys: [], // 当前展开的菜单 keys
      treeData: [],
      groupModalVisible: false,
      action: '',
      groupInfo: {},
      submitLoading: false,
      isInternalUpdate: false, // 防止watch重复触发
    };
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(newVal) {
        this.isInternalUpdate = true;
        this.selectedKeys = this.normalizeValue(newVal);
        this.$nextTick(() => {
          this.isInternalUpdate = false;
        });
      }
    },
    selectedKeys(newVal) {
      // 防止外部modelValue变化导致的重复触发
      if (this.isInternalUpdate) {
        return;
      }
      const val = this.multiple ? newVal : (newVal.length ? newVal[0] : null);
      this.$emit('update:modelValue', val);
      this.$emit('change', val);
    }
  },
  mounted() {
    this.getTreeData();
  },
  methods: {
    normalizeValue(input) {
      if (!input) return [];
      if (Array.isArray(input)) return input.filter(Boolean).map(String);
      if (typeof input === 'string') {
        return input.includes(',') ? input.split(',').filter(Boolean).map(String) : [input];
      }
      return [String(input)];
    },

    getTreeData() {
      this.$post('/system/sys-group/list', {
        page: { current: 1, size: 1000000 },
        ...this.params,
        groupType: this.groupType,
      }).then((res) => {
        const rows = res?.data?.data?.rows || [];
        this.treeData = this.listToTree ? this.$listToTree(rows) : rows;

        let defaultSelected;

        if (this.modelValue) {
          // 如果 modelValue 有值，则选中对应节点
          const key = Array.isArray(this.modelValue)
            ? String(this.modelValue[0])
            : String(this.modelValue);
          defaultSelected = this.findNodeByKey(this.treeData, key);
        }

        if (!defaultSelected && this.treeData.length > 0) {
          // 没有 modelValue，默认选中第一个子菜单或一级菜单
          const firstRoot = this.treeData[0];
          if (firstRoot.children && firstRoot.children.length > 0) {
            defaultSelected = firstRoot.children[0];
          } else {
            defaultSelected = firstRoot;
          }
        }

        if (defaultSelected) {
          // 设置 selectedKeys
          this.selectedKeys = [String(defaultSelected.value)];

          // 设置 openKeys 展开其祖先
          const ancestorKeys = this.findAncestorKeys(this.treeData, defaultSelected.value);
          this.openKeys = ancestorKeys;
        } else {
          this.selectedKeys = [];
          this.openKeys = [];
        }
      });
    },

    // 查找节点
    findNodeByKey(tree, key) {
      for (const node of tree) {
        if (String(node.value) === String(key)) return node;
        if (node.children && node.children.length) {
          const res = this.findNodeByKey(node.children, key);
          if (res) return res;
        }
      }
      return null;
    },

    // 查找祖先链
    findAncestorKeys(tree, key, path = []) {
      for (const node of tree) {
        const currentPath = [...path, String(node.value)];
        if (String(node.value) === String(key)) {
          return path; // 返回祖先链，不包含自身
        }
        if (node.children && node.children.length) {
          const res = this.findAncestorKeys(node.children, key, currentPath);
          if (res.length) return res;
        }
      }
      return [];
    },
    /** 控制只展开一个菜单 **/
    handleOpenChange(keys) {
      // keys 是当前所有展开的 keys，我们只保留最后一个
      const latestKey = keys.length ? keys[keys.length - 1] : null;
      this.openKeys = latestKey ? [latestKey] : [];
    },

    handleSelectFromNode(payload) {
      const { node } = payload;
      const key = String(node.value);

      // 找到祖先节点链
      const ancestorKeys = this.findAncestorKeys(this.treeData, key);

      if (node.children && node.children.length) {
        // 父节点点击：切换展开状态
        if (this.openKeys.includes(key)) {
          // 收起
          this.openKeys = this.openKeys.filter(k => k !== key);
        } else {
          // 展开，保持祖先路径展开
          this.openKeys = Array.from(new Set([...ancestorKeys, key]));
        }
        this.selectedKeys = [key]; // 可以选中父节点
        return;
      }

      // 叶子节点点击
      if (!this.multiple) {
        this.selectedKeys = [key];
      } else {
        const s = [...this.selectedKeys];
        const idx = s.indexOf(key);
        if (idx === -1) s.push(key);
        else s.splice(idx, 1);
        this.selectedKeys = s;
      }

      // 展开叶子的所有父节点
      this.openKeys = Array.from(new Set([...ancestorKeys]));
    },

    /**
     * 查找 key 的祖先链，返回数组
     * [顶级父, 二级父, ..., 直接父]
     */
    findAncestorKeys(tree, key, path = []) {
      for (const node of tree) {
        const currentPath = [...path, String(node.value)];
        if (String(node.value) === String(key)) {
          return path; // 返回祖先链
        }
        if (node.children && node.children.length) {
          const res = this.findAncestorKeys(node.children, key, currentPath);
          if (res.length) return res;
        }
      }
      return [];
    },

    confirmDeleteGroup(node) {
      this.$confirm({
        title: '确认删除该分组吗？',
        onOk: () => {
          this.$delete(`/system/sys-group/${node.value}`).then((res) => {
            if (res.data.code !== 200) {
              this.$message.error(res.data.msg);
              return;
            }
            this.selectedKeys = [];
            this.$message.success('删除成功');
            this.getTreeData();
          });
        },
      });
    },

    openAddGroup() {
      this.action = 'add';
      this.groupInfo = { isChild: false, groupName: '' };
      this.groupModalVisible = true;
    },

    openAddChildOf(parentNode) {
      this.action = 'add';
      this.groupInfo = { isChild: true, groupName: '', parentId: parentNode.value || parentNode.id };
      this.openKeys = [String(parentNode.value)];
      this.groupModalVisible = true;
    },

    openEditGroup(node) {
      this.action = 'edit';
      this.groupInfo = { ...node, groupName: node.label, id: node.id || node.value };
      this.groupModalVisible = true;
    },

    submitGroup() {
      if (!this.groupInfo.groupName || !this.groupInfo.groupName.trim()) {
        this.$message.error('请完整填写表单');
        return;
      }
      this.submitLoading = true;

      const payload = {
        ...this.groupInfo,
        groupType: this.groupType,
        groupId: this.action === 'add' && this.groupInfo.isChild
          ? (this.groupInfo.parentId || this.selectedKeys[0] || null)
          : null,
      };

      const api = this.action === 'add'
        ? this.$post('/system/sys-group', payload)
        : this.$put('/system/sys-group/edit', { ...payload, id: this.groupInfo.id });

      api.then((res) => {
        if (res.data.code === 200) {
          this.$message.success(this.action === 'add' ? '添加成功' : '修改成功');
          this.getTreeData();
          this.groupModalVisible = false;
        } else {
          this.$message.error(res.data.msg || '操作失败');
        }
      }).finally(() => {
        this.submitLoading = false;
      });
    },
  }
};
</script>

<style scoped>
/* 移除菜单右边的线条 */
:deep(.ant-menu-inline) {
  border-right: none !important;
  background: #fafafa !important;
  border-radius: 8px;
  padding: 8px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow-y: auto !important;
}

/* 移除菜单的边框和阴影 */
:deep(.ant-menu) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.ant-menu-item) {
  margin: 2px 8px !important;
  border-radius: 6px;
  padding: 8px 12px !important;
  font-weight: 400;
}

:deep(.ant-menu-submenu-title) {
  margin: 2px 8px !important;
  border-radius: 6px;
  padding: 8px 12px !important;
  font-weight: 500;
}

/* 优化选中效果 */
:deep(.ant-menu-item-selected) {
  background-color: #1890ff !important;
  color: white !important;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
}

/* 优化子菜单样式 */
:deep(.ant-menu-sub) {
  background: #fafafa !important;
  border-radius: 6px;
  margin: 0 8px !important;
  padding: 4px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

:deep(.ant-menu-sub .ant-menu-item) {
  margin: 2px 4px !important;
  padding-left: 24px !important;
  font-weight: 400;
}

/* 优化滚动条样式 */
:deep(.ant-menu-inline::-webkit-scrollbar) {
  width: 6px;
}

:deep(.ant-menu-inline::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.ant-menu-inline::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.ant-menu-inline::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 优化添加根级按钮 */
:deep(.ant-btn.dashed) {
  margin-top: 16px;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  border-color: #d9d9d9;
}

:deep(.ant-btn.dashed:hover) {
  border-color: #d9d9d9;
  color: inherit;
  background-color: transparent;
  box-shadow: none;
}

/* 优化模态框样式 */
:deep(.ant-modal) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

:deep(.ant-modal-header) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
  border-radius: 12px 12px 0 0;
}

:deep(.ant-modal-title) {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

:deep(.ant-modal-body) {
  padding: 24px;
  background: white;
}

:deep(.ant-modal-footer) {
  border-top: 1px solid #f0f0f0;
  padding: 16px 24px;
  background: #fafafa;
  border-radius: 0 0 12px 12px;
}

/* 优化下拉菜单样式 */
:deep(.ant-dropdown-menu) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 1px solid #f0f0f0;
  padding: 4px 0;
}

:deep(.ant-dropdown-menu-item) {
  padding: 8px 16px;
  margin: 0;
  border-radius: 0;
}

:deep(.ant-dropdown-menu-item:hover) {
  background-color: transparent;
  color: inherit;
}
</style>
