<template>
  <a-card
    :class="[
      $style.treewrap,
      $style.ywlxtree,
      { [$style.collapse]: false, [$style.single]: false },
    ]"
  >
    <a-form-model>
      <a-form-model-item :label="null" prop="orgValue">
        <a-select
          v-model="allTreeDataKeys"
          show-search
          :filter-option="filterOption"
          @change="onSelectName"
        >
          <a-select-option v-for="item in allTreeData" :key="item.id" :value="item.id">
            {{ item.categoryName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
    <slot></slot>
    <a-empty v-if="empty" />
    <a-tree
      v-else
      ref="tree"
      :key="key"
      v-model="checkedKeys"
      :tree-data="treeData"
      :show-line="true"
      :replace-fields="replaceFields"
      :expanded-keys="expandedKeys"
      :default-selected-keys="defaultSelectedKeys"
      @select="treeSelect"
      @expand="onExpand"
    >
    </a-tree>
    <!-- 设置 -->
  </a-card>
</template>

<script>
import components from './_import-components/audit-model-tree-import'
import { generateTree, getTreeIds } from '@product/iam/audit/dataMarket/util'
import auditModelService from './audit-model-service'

export default {
  name: 'AuditModelTree',
  metaInfo: {
    title: 'AuditModelTree',
  },
  // 树结构数据

  components,

  data() {
    return {
      key: 0,
      allTreeDataKeys: null,
      // 分类加载状态
      replaceFields: {
        title: 'categoryName',
        key: 'id',
        children: 'children',
      },
      empty: true,
      expandedKeys: ['0'],
      // 原始数据列表
      // 树结构
      // 搜索数据结构
      searchInput: '',
      treeData: [],
      allTreeData: [],
      checkedKeys: [],
      defaultSelectedKeys: [],
    }
  },

  created() {
    this.initMineTreeData()
  },
  methods: {
    initMineTreeData() {
      // 获取分类数据信息
      auditModelService.getAuditModelTreeAll().then((res) => {
        // 存储搜索所需的数据
        this.allTreeData = res.data
        // 组装数据
        const nodeData = [
          {
            id: '0',
            categoryName: '全部分类',
            isLeaf: false,
            isroot: true,

            children: [],
          },
        ]
        if (res.data.length) {
          nodeData[0].children = res.data
        }
        // 根据props下的isEnd越大层级越深 0为最上级节点
        // props下的parentId代表父节点id
        // 根据上述数据生成多层嵌套的树形结构，该树形结构有多个根节点
        const generateTree = (data) => {
          const tree = []
          const temp = {}
          for (let i = 0; i < data.length; i++) {
            temp[data[i].id] = data[i]
          }
          for (let i = 0; i < data.length; i++) {
            if (temp[data[i].parentId] && data[i].id !== data[i].parentId) {
              if (!temp[data[i].parentId].children) {
                temp[data[i].parentId].children = []
              }
              temp[data[i].parentId].children.push(data[i])
            } else {
              tree.push(data[i])
            }
          }
          return tree
        }

        nodeData[0].children = generateTree(res.data)
        this.treeData = [...nodeData]

        this.key += 1
        this.empty = false
        this.spinning = false
      })
    },
    //
    refreshNode() {
      this.initMineTreeData()
      this.key += 1
    },
    // 点击选中
    // 点击取消
    treeSelect(selectedKeys, info) {
      if (selectedKeys.length === 0) {
        this.allTreeDataKeys = null
      }
      this.$emit('treeSelect', selectedKeys, info)
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.indexOf(input) >= 0
    },
    // 搜索数据
    onSelectName(val) {
      this.defaultSelectedKeys = [val]
      this.key++

      const onInfo = this.allTreeData.find((item) => item.id === val)
      // 根据当前节点id寻找所有上级节点id
      let parentId = onInfo.parentId
      while (parentId !== '0') {
        this.expandedKeys.push(parentId)
        const parentInfo = this.allTreeData.find((item) => item.id === parentId)

        parentId = parentInfo?.parentId || '0'
      }
      const onSelected = []

      onSelected.push({
        data: {
          props: {
            id: onInfo.id,
            text: onInfo.text,
            edit: true,
            props: {
              ...onInfo.props,
            },
          },
        },
      })
      // }
      this.$emit('treeSelect', [val], {
        selectedNodes: onSelected,
        node: {
          dataRef: {
            id: onInfo.id,
            text: onInfo.text,
            props: {
              isroot: false,
            },
          },
        },
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.spin {
  width: 100%;
  line-height: 30;
}
.ywlxtree {
  :global(.ant-tree-title) {
    display: inline-block;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-input-search) {
    margin: 8px 0;
    overflow: hidden;
  }
  .active {
    color: $primary-color;
  }
  :global(.ant-select) {
    width: 100%;
    overflow: hidden;
  }
}
.treewrap {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 20%;
  min-height: 100%;
  margin-right: $padding-lg;
  transition: width 0.2s;
  .fold {
    position: absolute;
    top: calc(50% - 30px);
    right: -15px;
    z-index: 2;
    width: 15px;
    height: 75px;
    padding: 0;
    border-radius: 0 10px 10px 0;
  }
  :global(.ant-tree) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-card-body) {
    background: $white;
  }
}
.collapse {
  width: 0;
  :global(.ant-card-body) {
    background: transparent;
    :global(.ant-empty) {
      display: none;
    }
  }
}
// 单选样式
.single {
  :global .ant-tree-checkbox {
    .ant-tree-checkbox-inner {
      border-radius: 100px;
      &::after {
        position: absolute;
        top: 3px;
        left: 3px;
        display: table;
        width: 8px;
        height: 8px;
        content: ' ';
        background-color: $primary-color;
        border: 0;
        border-radius: 8px;
        opacity: 0;
        transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);
        transform: scale(0);
      }
    }
    &.ant-tree-checkbox-checked {
      &::after {
        position: absolute;
        top: 16.67%;
        left: 0;
        width: 100%;
        height: 66.67%;
        content: '';
        border: 1px solid #1890ff;
        border-radius: 50%;
        animation: antRadioEffect 0.36s ease-in-out;
        animation-fill-mode: both;
      }
      .ant-tree-checkbox-inner {
        background-color: $white;
        &::after {
          opacity: 1;
          transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);
          transform: scale(1);
        }
      }
    }
  }
}
</style>
