<template>
  <div class="tree-container x-tree-rows-wrapper" :class="wrapperClassObject" :style="config?.componentStyle || ''">
    <div class="tree-header">
      <span class="tree-title" :style="config.style">{{ title }}</span>
      <span class="tree-expand-all" @click="isToOpenAll" v-if="isShowOpen">
        {{ isExpanded ? '收起' : '全部展开' }}
      </span>
    </div>
    <div class="tree-list">
      <tree-node v-for="node in showData" :key="node.id" :node="node" :selected="node.selected" @toggle="toggleNode" />
    </div>
  </div>
</template>

<script>
import TreeNode from '@vue2-client/base-client/components/his/XTreeRows/TreeNode.vue'
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'

export default {
  name: 'XTreeRows',
  components: {
    TreeNode
  },
  props: {
    queryParamsName: {
      type: String,
      default: ''
    },
    isOpenAll: {
      type: Boolean,
      default: false
    },
    parameter: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 父组件索引
    ipanelIndex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      treeData: [
        // {
        //   id: '1',
        //   title: '体征',
        //   expanded: false,
        //   children: [
        //     {
        //       id: '1-1',
        //       title: '一般情况'
        //     },
        //     {
        //       id: '1-2',
        //       title: '皮肤粘膜'
        //     },
        //     {
        //       id: '1-3',
        //       title: '头颈',
        //       expanded: false,
        //       children: [
        //         {
        //           id: '1-3-1',
        //           title: '头部头部头部头部头部头部头部头部头部头部头部头部头部头部',
        //           expanded: false,
        //           children: [
        //             {
        //               id: '1-3-1-1',
        //               title: '123456'
        //             }
        //           ]
        //         },
        //         {
        //           id: '1-2-2',
        //           title: '颈部'
        //         }
        //       ]
        //     },
        //     {
        //       id: '1-4',
        //       title: '胸部'
        //     },
        //   ]
        // }
      ],
      isExpanded: false,
      showData: [],
      isShowOpen: true,
      title: '标题',
      config: {},
      lastSelectedNode: null // 记录最后选中的节点
    }
  },
  computed: {
    // 基于 $attrs 的样式类开关（参考 XInput.vue 模式）
    wrapperClassObject() {
      const attrs = this.$attrs || {}
      const classes = {}
      const booleanStyleKeys = ['user-entry']
      booleanStyleKeys.forEach(key => {
        const val = attrs[key]
        const truthy = val === true || val === '' || val === 'true'
        if (truthy) classes[`xtreerows-${key}`] = true
      })
      const size = attrs.size
      if (size && typeof size === 'string') classes[`xtreerows-size-${size}`] = true
      return classes
    }
  },
  mounted() {
    console.log('实例化')
    this.$emit('component-mounted', this) // 向父组件发送实例
  },
  methods: {
    /**
     * 递归查找匹配 title 的节点及其路径
     * @param {Array} nodes 要搜索的节点数组
     * @param {string} title 要匹配的标题
     * @param {Array} path 当前路径
     * @returns {Object|null} 包含节点和路径的对象
     */
    findNodeAndPathByTitle(nodes, title, path = []) {
      for (const node of nodes) {
        const currentPath = [...path, node]
        if (node.title === title) {
          return { node, path: currentPath }
        }
        if (node.children && node.children.length) {
          const found = this.findNodeAndPathByTitle(node.children, title, currentPath)
          if (found) return found
        }
      }
      return null
    },

    /**
     * 展开节点路径
     * @param {Array} path 节点路径
     */
    expandNodePath(path) {
      // 展开除最后一个节点外的所有节点（即所有父节点）
      for (let i = 0; i < path.length - 1; i++) {
        path[i].expanded = true
      }
    },
    searchTitleToggle(title) {
      // 清除之前选中的节点
      if (this.lastSelectedNode) {
        this.$set(this.lastSelectedNode, 'selected', false) // 改用Vue.set
      }
      const result = this.findNodeAndPathByTitle(this.showData, title)
      if (result) {
        if (result.node.children.length > 0) {
          this.toggleNode(result.node)
        } else {
          this.expandNodePath(result.path)
        }
        this.$set(result.node, 'selected', true) // 使用Vue.set确保响应性
        this.lastSelectedNode = result.node
        this.$emit('search-complete', {
          hasMatch: true,
          panelIndex: this.ipanelIndex // 接收父组件传入的面板索引
        })
        // 滚动到目标节点
        this.$nextTick(() => {
          this.scrollToNode(result.node.id)
        })
      } else {
        this.$emit('search-complete', { hasMatch: false })
      }
    },
    /**
     * 滚动到指定节点
     * @param {string} nodeId 节点ID
     */
    scrollToNode(nodeId) {
      const nodeElement = document.querySelector(`[data-node-id="${nodeId}"]`)
      if (nodeElement) {
        nodeElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
      }
    },
    toggleNode(node) {
      node.expanded = !node.expanded
      this.$emit('node-toggle', node)
    },
    isToOpenAll() {
      this.isExpanded = !this.isExpanded
      this.expandAllNodes(this.showData, this.isExpanded)
      this.$emit('isOpenAll', this.isExpanded)
    },
    expandAllNodes(nodes, expand) {
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          node.expanded = expand
          this.expandAllNodes(node.children, expand)
        }
      })
    },
    /**
     * 构建树数据
     * @param allData 子节点所有数据
     * @param gid 根节点id
     * @returns {*|*[]}
     */
    buildTreeByRootId(allData, gid) {
      // 1. 找到所有直接子节点
      const directChildren = allData.filter(item => item.pid === gid)
      if (directChildren.length === 0) return [] // 如果没有子节点，返回空数组
      // 2. 递归构建子树
      const buildTree = parentId => {
        const children = allData.filter(item => item.pid === parentId)
        return children.map(child => ({
          title: child.label,
          id: child.value,
          children: buildTree(child.value) // 递归处理子节点
        }))
      }
      // 3. 返回直接子节点的完整子树
      return directChildren.map(child => ({
        title: child.label,
        id: child.value,
        children: buildTree(child.value),
        expanded: false
      }))
    },
    init(config, parameterData) {
      getConfigByName(config, 'af-his', res => {
        this.isShowOpen = res.isShowOpen
        this.title = res.title
        this.config = res
        if (!res.isCheck) {
          this.showData = res.showData
          return
        }
        const parameter = { ...parameterData, ...this.parameter }
        runLogic(res.logicName, parameter, 'af-his').then(result => {
          if (result.isConstruction) {
            // 对数据重新构造
            this.showData = this.buildTreeByRootId(result.allData, result.gId)
          } else {
            this.showData = result
          }
        })
      })
    }
  },
  watch: {
    queryParamsName: {
      immediate: true,
      handler(newValue) {
        console.log(newValue)
        this.init(newValue, {})
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="less">
.tree-container {
  width: 100%;
  height: 320px;
  overflow-y: auto;
  overflow-x: auto;
  padding: 6px;
  box-sizing: border-box;
}
/* 自定义滚动条样式 */
.tree-container::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}
.tree-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 2px;
}
.tree-container::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}
.tree-list {
  font-size: 14px;
  min-width: 100%;
}

.tree-header {
  padding: 8px 4px;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 8px;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 1;
}

.tree-title {
  font-size: 16px;
  font-weight: 700;
  color: #5d5c5c;
}

.tree-expand-all {
  float: right;
  margin-right: 15px;
  font-size: 14px;
  font-weight: 400;
  color: #5d5c5c;
  cursor: pointer;
  user-select: none;
}

.tree-expand-all:hover {
  color: #989a9a;
}

/* user-entry 样式：字体与内容区域边距（参考需求） */
.x-tree-rows-wrapper {
  &.xtreerows-user-entry {
    padding: 14px 0 20px 47px;
    .tree-list {
      font-family: 'Source Han Sans', sans-serif;
      font-size: 16px;
      font-weight: normal;
      line-height: 18px;
      letter-spacing: 0em;
      font-feature-settings: 'kern' on;
      color: #313131;
    }
  }
}
</style>
