<template>
  <div>
    <a-input
      read-only
      :value="value"
      @change="(value) => $emit('change', value)"
      @click.native="select"
    />
    <a-modal title="请选择" :visible="visible" @ok="handleOk" @cancel="handleCancel">
      <a-tree
        checkable
        :load-data="loadTreeData"
        :tree-data="treeData"
        check-strictly
        :checked-keys="[...selectedKeys]"
        :selected-keys="[...selectedKeys]"
        @check="onChecked"
      />
    </a-modal>
  </div>
</template>

<script>
import cloneDeep from 'lodash.clonedeep'
import components from './_import-components/sd-tree-level-select-import'
function parseTreeData(data, flag) {
  // 设置树只有叶子节点可选
  const result = cloneDeep(data)
  const f = (arr, level) => {
    arr.forEach((a) => {
      if (a.children) {
        f(a.children, level + 1)
      }
      a.checkable = true
      a.title = a.name
      a.isLeaf = !a.children
      a.key = a.id
      a.level = level
    })
  }
  f(result, 0)
  return result
}

export default {
  name: 'SdTreeLevelSelect',
  metaInfo: {
    title: 'SdTreeLevelSelect',
  },
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    dataSource: {
      type: Array,
      default: undefined,
    },
  },
  data() {
    return {
      visible: false,
      /**
       * 表单项的值
       */
      value: undefined,
      selectedKeys: [],
      selectedLevel: '',
    }
  },
  computed: {
    treeData() {
      return parseTreeData(this.dataSource || [], this.allNodesSelectable)
    },
  },
  methods: {
    handleCancel() {
      this.visible = false
    },
    handleOk() {
      this.value = this.selectedLevel === '' ? '' : this.selectedLevel + 1
      this.visible = false
      this.$emit('change', this.value)
    },
    checkedByLevel(array, level) {
      let result = []
      array.forEach((item) => {
        if (item.level === level) {
          result.push(item.id)
        }
        if (level > item.level && item.children) {
          result = result.concat(this.checkedByLevel(item.children, level))
        }
      })
      return result
    },
    onChecked(checkedKeys, { checked, checkedNodes, node, event }) {
      if (checked) {
        this.selectedKeys = this.checkedByLevel(this.treeData, node.dataRef.level)
        this.selectedLevel = node.dataRef.level
      } else {
        this.selectedKeys = []
        this.selectedLevel = ''
      }
    },
    select() {
      this.visible = true
    },
    loadTreeData() {
      return Promise.resolve(this.treeData)
    },
  },
}
</script>

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