<template>
  <div id="XTreeOne">
    <component-layout-one :siderProps="{width: leftWidth,collapsible: collapsible,collapsedWidth: collapsedWidth,theme: 'light'}">
      <template slot="left">
        <div class="bg-white pd-20" :style="{height: treeHeight}">
          <a-input-search style="margin-bottom: 8px" placeholder="Search" allow-clear @change="onChange" />
          <a-tree
            :tree-data="searchData"
            @select="onSelect">
            <template #title="{ title }">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </div>
      </template>
      <div style="margin-left: 12px">
        <slot></slot>
      </div>
    </component-layout-one>
  </div>
</template>

<script>
  import ComponentLayoutOne from '@vue2-client/layouts/ComponentLayoutOne'
  export default {
    name: 'XTreeOne',
    components: { ComponentLayoutOne },
    props: {
      // 左侧宽度
      leftWidth: {
        type: [Number, String],
        default: () => {
          return 200
        }
      },
      // 左侧是否可收起
      collapsible: {
        type: Boolean,
        default: true
      },
      // 左侧收起后宽度
      collapsedWidth: {
        type: Number,
        default: 0
      },
      // Tree 树形控件数据
      // array<{key, title, children, [disabled, selectable]}>
      treeData: {
        type: Array,
        required: true
      },
      treeHeight: {
        type: String,
        default: '85vh'
      }
    },
    data () {
      return {
        // 用于展示筛选出的数据
        searchData: [],
        // 查询值
        searchValue: ''
      }
    },
    created () {
      this.init()
    },
    mounted () {
    },
    watch: {
      'treeData' () {
        this.init()
      }
    },
    methods: {
      init () {
        // 添加title插槽
        for (const index of this.treeData.keys()) {
          this.treeData[index].scopedSlots = { title: 'title' }
        }
        this.searchData = Object.assign([], this.treeData)
      },
      onChange (e) {
        const name = e.target.value
        this.searchValue = name
        this.searchData = []
        for (const row of this.treeData) {
          if (row.title.indexOf(name) > -1) {
            this.searchData.push(row)
          }
        }
      },
      onSelect (selectedKeys, e) {
        this.$emit('onSelect', selectedKeys, e)
      }
    }
  }
</script>

<style lang="less" scoped>
  .pd-20 {
    padding: 20px;
  }
  /deep/ .ant-tree-switcher-icon svg{
    width: 1.5em;
    height: 1.5em;
  }
</style>
