<template>
  <div :class="$style.selectUser">
    <a-input-search
      enter-button
      placeholder="需要查询的用户"
      :loading="searchConfirmLoading"
      @search="handleSearch"
      @change="handleSearchChange"
    />
    <a-tree
      v-show="!showSearchResults"
      v-if="treeData"
      v-model="checkedKeys"
      :load-data="onLoadData"
      :tree-data="treeData"
      :checkable="true"
      :default-expanded-keys="defaultExpandedKeys"
      :check-strictly="true"
      @check="onCheck"
    />
    <a-table
      v-show="showSearchResults"
      :columns="columns"
      :row-key="(record) => record.account"
      :data-source="searchResults"
      :pagination="pagination"
      :loading="loading"
      :row-selection="{ type: 'radio', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    ></a-table>
  </div>
</template>

<script>
import navService from './nav-service'
import components from './_import-components/sd-nav-user-import'

const rootId = -1
const parseTreeData = (deps) => {
  return deps.map((dep) => {
    return {
      key: dep.id,
      title: dep.text,
      isLeaf: dep.leaf,
      checkable: dep.leaf,
      account: dep.props.type === 'U' ? dep.props.account : '',
    }
  })
}
export default {
  name: 'SdNavUser',
  metaInfo: {
    title: 'SdNavUser',
  },
  components,
  model: {
    prop: 'selectedUserKey',
    event: 'change',
  },
  props: {
    selectedUser: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      treeData: null,
      defaultExpandedKeys: ['-1'],
      checkedKeys: [],
      searchResults: [],
      pagination: {
        current: 1,
        pageSize: 10,
        showTotal: (total) => {
          return `共${total}条`
        },
        showSizeChanger: true,
        showQuickJumper: true,
      },
      loading: false,
      searchConfirmLoading: false,
      columns: [
        {
          title: '代码',
          dataIndex: 'account',
        },
        {
          title: '名称',
          dataIndex: 'name',
        },
        {
          title: '所属单位',
          dataIndex: 'parentPathName',
        },
      ],
      showSearchResults: false,
      searchValue: '',
      selectedRowKeys: [],
    }
  },
  watch: {
    checkedKeys(val) {
      if (val.checked.length > 1) {
        val.checked.halfChecked = val.checked.shift()
      }
    },
  },
  created() {
    navService.getAllGroups(rootId).then((data) => {
      const key = 'G' + data.id
      this.treeData = [
        {
          title: data.name,
          key: key,
          checkable: false,
        },
      ]
      this.defaultExpandedKeys = [key]
    })
  },
  methods: {
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        navService.getChildrenByGroupId({ parent: treeNode.dataRef.key }).then((deps) => {
          treeNode.dataRef.children = parseTreeData(deps)
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    handleSearch(val) {
      this.searchConfirmLoading = true
      this.searchValue = val
      this.pagination.current = 1
      this.pagination.pageSize = 10
      this.queryUsers()
    },
    handleSearchChange(e) {
      if (e.target.value === '') {
        this.showSearchResults = false
      }
    },
    handleTableChange(pagination) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.queryUsers()
    },
    queryUsers() {
      const pagination = this.pagination
      this.loading = true
      const params = {
        expressions: [
          {
            dataType: 'exps',
            expressionsValue: [
              {
                dataType: 'str',
                name: 'account',
                op: 'like',
                stringValue: `%${this.searchValue}%`,
              },
              {
                dataType: 'str',
                name: 'name',
                op: 'like',
                stringValue: `%${this.searchValue}%`,
              },
            ],
            op: 'or',
          },
        ],
        maxResults: pagination.pageSize,
        startPosition: pagination.pageSize * (pagination.current - 1),
      }
      navService.queryUsers(params).then((data) => {
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.loading = false
        this.searchConfirmLoading = false
        this.searchResults = data.datas
        this.pagination = pagination
        this.showSearchResults = true
      })
    },
    onCheck(checkedKeys, info) {
      this.checkedKeys = checkedKeys
      const treeNodeProps = info.checkedNodes[info.checkedNodes.length - 1]?.data.props
      this.$emit('change', { account: treeNodeProps?.account, name: treeNodeProps?.title })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      // 优先组织树选择
      if (this.checkedKeys.length === 0) {
        this.$emit('change', { account: selectedRows[0]?.account, name: selectedRows[0]?.name })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.select-user {
  :global(.ant-tree-checkbox-inner) {
    border-radius: 50%;
  }
  :global(.ant-tree-checkbox-checked .ant-tree-checkbox-inner) {
    background: #fff;
  }
  :global(.ant-tree-checkbox-checked .ant-tree-checkbox-inner::after) {
    top: 50%;
    left: 50%;
    width: 8px;
    height: 8px;
    content: ' ';
    background-color: $primary-color;
    border: 0;
    border-radius: 50%;
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
  :global(.ant-tree-checkbox-checked .ant-tree-checkbox-inner:hover) {
    border: 0;
  }
  :global(.ant-tree-checkbox-checked::after) {
    border: 0;
  }
}
</style>
