<template>
  <div>
    <a-card :class="{ [$style.tree]: true, [$style.single]: single }" bordered size="small">
      <a-input-search slot="title" v-model="searchValue" placeholder="搜索" @search="onSearch" />
      <a-checkbox slot="extra" v-model="isContainSub">含下级</a-checkbox>
      <sd-group-tree
        :default-selected-keys="['SD-CUR-GROUP']"
        :root-node="rootNode"
        :hierarchical="hierarchical"
        @update:selectedKeys="handleTreeSelect"
      />
    </a-card>
    <sd-picker-source-lazy-list
      v-if="key"
      :key="listKey + isContainSub"
      v-bind="$attrs"
      :single="single"
      :load-list-data="() => loadListData()"
      :show-search="false"
      v-on="$listeners"
    />
  </div>
</template>

<script>
import AddressBook from '@/addressbook/group-user-service'
import components from './_import-components/sd-picker-users-by-group-import'
export default {
  name: 'SdPickerUsersByGroup',
  metaInfo: {},
  components,
  inheritAttrs: false,
  props: {
    title: {
      type: String,
      default: '',
    },
    icon: {
      type: String,
      default: '',
    },
    rootNode: {
      type: [Object, Array],
      default: undefined,
    },
    hierarchical: {
      type: Boolean,
      default: false,
    },
    secretLevel: {
      type: String,
      default: '',
    },
    single: {
      type: Boolean,
      default: undefined,
    },
  },
  data() {
    return {
      key: '',
      isContainSub: false,
      searchValue: '',
      listKey: '',
    }
  },
  methods: {
    handleTreeSelect(key) {
      this.key = key[0]
      this.listKey = this.key
      this.searchValue = ''
    },
    loadListData() {
      if (this.searchValue) {
        let rootNode = this.rootNode
        if (rootNode && !Array.isArray(rootNode)) {
          rootNode = [rootNode]
        }
        return AddressBook.usersQuery(this.searchValue, [], {
          secretLevel: this.secretLevel,
          hierarchical: this.hierarchical,
          rootIds: rootNode?.map((i) => parseInt(i.id || i.code)),
        })
      }
      if (this.key) {
        return AddressBook.getChildNodes(this.key, {
          type: 'U',
          isContainSub: this.isContainSub,
          secretLevel: this.secretLevel,
          hierarchical: this.hierarchical,
        })
      }
    },
    onSearch() {
      this.listKey = this.searchValue
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.tree {
  position: absolute;
  top: -41px;
  left: -385px;
  width: 375px;
  height: calc(100% + 42px);
  div:global(.ant-card-body) {
    height: calc(100% - 42px);
    padding: 0;
    > div {
      height: 100%;
      overflow: auto;
    }
  }
  :global(.ant-card-head > .ant-card-head-wrapper > .ant-card-head-title) {
    padding: 0;
    margin-right: 4px;
  }
}
.tree.single {
  top: 0;
  height: 100%;
}
</style>
