<template>
  <a-card
    :class="[
      $style.treewrap,
      $style.ywlxtree,
      { [$style.collapse]: fold, [$style.single]: single },
    ]"
  >
    <!-- 选择部门 -->
    <a-tree-select
      v-if="isSelectDep"
      v-model="depvalue"
      :allow-clear="true"
      :tree-data="depOptions"
      @change="changedep"
    >
    </a-tree-select>
    <!-- 搜索框 -->
    <a-input-search
      v-if="isSearch"
      v-model="searchStr"
      placeholder=""
      allow-clear
      @change="onSearchChange"
    />
    <a-spin :spinning="spinning" :class="$style.spin" />
    <a-empty v-if="empty" />
    <a-tree
      v-else
      :key="refreshKey"
      ref="auditTree"
      v-model="checkedKeys"
      :block-node="false"
      :show-icon="true"
      :show-line="showLine"
      :check-strictly="true"
      :checkable="checkable"
      :disabled="disabled"
      :draggable="draggable"
      :tree-data="treeData"
      :replace-fields="replaceFields"
      :selected-keys="defaultSelectedKeys"
      :expanded-keys="expandedKeys"
      :default-expanded-keys="defaultTreeExpandedKeys"
      :load-data="onLoadData"
      @select="treeSelect"
      @check="treeCheck"
      @expand="onExpand"
      @dragenter="onDragEnter"
      @drop="onDrop"
    >
      <template v-slot:title="{ text, props }">
        <span v-if="text.indexOf(searchValue) > -1" :title="text">
          {{ text.substr(0, text.indexOf(searchValue)) }}
          <span :class="$style.active">{{ searchValue }}</span>
          {{ text.substr(text.indexOf(searchValue) + searchValue.length) }}
        </span>
        <span v-else :title="text">{{ text }}</span>
        <!-- 后台返回数量，如果有数量的话就显示 -->
        <span v-if="props.count > 0">（{{ props.count }}）</span>
      </template>
      <!-- 如果已配置负责人，则展示用户图标 -->
      <template slot="hasuser" slot-scope="item">
        <a-icon type="team" @click="showUser(item)" />
      </template>
    </a-tree>
    <a-button v-if="showPrimary" type="primary" :class="$style.fold" @click="foldClick">
      <a-icon :type="icontype" />
    </a-button>
  </a-card>
</template>

<script>
import AuditPermissionTreeMixins from './audit-permission-tree-mixins'
import auditPermissionTreeService from './audit-permission-tree-service'
import components from './_import-components/audit-permission-tree-import'

export default {
  name: 'AuditPermissionTree',
  metaInfo: {
    title: 'AuditPermissionTree',
  },
  components,
  mixins: [AuditPermissionTreeMixins],
  props: {
    // 默认选中节点
    // selectedKeys: {
    //   type: Array,
    //   default: function() {
    //     return [1]
    //   },
    // },
    // 是否开启搜索
    isSearch: {
      type: Boolean,
      default: false,
    },
    // 是否显示复选框
    checkable: {
      type: Boolean,
      default: false,
    },
    // 是否可以拖拽
    draggable: {
      type: Boolean,
      default: false,
    },
    // 是否显示连线
    showLine: {
      type: Boolean,
      default: false,
    },
    // 根节点名称
    topNodeText: {
      type: String,
      default: 'XX科技',
    },
    // 地址树接口数据源
    treeparams: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 默认展开节点id
    defaultExpandedKeys: {
      type: Array,
      default: () => {
        return ['0']
      },
    },
    // 是否显示部门选择下拉框
    isSelectDep: {
      type: Boolean,
      default: false,
    },
    // 部门下拉框列表值
    depOptions: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 部门下拉框默认值
    defaultDepValue: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 是否显示隐藏按钮
    showPrimary: {
      type: Boolean,
      default: true,
    },
    // 地址树是否单选
    single: {
      type: Boolean,
      default: false,
    },
    refreshKey: {
      type: Number,
      default: 0,
    },
    // 复选框是否失效
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      defaultTreeExpandedKeys: ['1'],
      defaultSelectedKeys: ['1'],
      selectedKeys: ['1'],
      depvalue: [], // 选择的组织数据
      checkedKeys: [], // 选中的节点数据
      treeData: [],
      dataList: [], // 数组dataList，搜索要用
      spinning: true,
      empty: false,
      icontype: 'left',
      fold: false,
      replaceFields: {
        title: 'text',
        key: 'id',
      },
      expandedKeys: ['1'],
      backupsExpandedKeys: [],
      autoExpandParent: false,
      searchValue: '',
      searchStr: '',
      defaultTopNodeText: 'XX科技',
      defaultTopNodeId: '1',
      key: 1,
    }
  },
  created() {},
  methods: {
    onDragEnter(info) {
      // expandedKeys 需要受控时设置
      this.expandedKeys = info.expandedKeys
    },
    // 拖拽节点方法
    onDrop(info) {
      // 被插入节点信息
      const dropKey = info.node.eventKey
      // 拖拽节点信息
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      // -1表示之前 0表示合并 1表示之后
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.id === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = this.treeData

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj)
        })
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj)
        })
      } else {
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.treeData = data

      // 拖拽完成，调用接口
      const dragParams = {
        configId: this.treeparams.configId,
        id: dragKey,
        targetId: dropKey,
        position: dropPosition,
      }
      auditPermissionTreeService.dragNode(dragParams).then((res) => {
        console.log(res)
      })
    },

    // 点击地址树展开时调用
    onLoadData(treeNode) {
      let moduleId = ''
      if (this.treeparams.type === 'SJ') {
        moduleId = 'iamOrg'
      } else if (this.treeparams.type === 'FK') {
        moduleId = 'iamOrg2'
      }
      const params = {
        moduleId: moduleId,
        isDisabled: this.treeparams.isDisabled,
      }
      return auditPermissionTreeService.getCategoryTree(treeNode.dataRef.id, params).then((res) => {
        treeNode.dataRef.children = res.data
        this.treeData = this.transformData([...this.treeData])
        this.generateList(this.treeData)
        // 更新宽度
        setTimeout(() => {
          this.fnchangewidth()
        }, 500)
      })
    },
    // 初始化地址树
    initTreeData(depId) {
      let topDepId = null
      let moduleId = ''
      if (this.treeparams.type === 'SJ') {
        moduleId = 'iamOrg'
      } else if (this.treeparams.type === 'FK') {
        moduleId = 'iamOrg2'
      }
      const params = {
        moduleId: moduleId,
        isDisabled: this.treeparams.isDisabled,
      }
      auditPermissionTreeService.getParentOrgInfo(params).then((res) => {
        if (res.data.length > 0) {
          const treeNode = []
          this.defaultTopNodeId = res.data[0].id
          // if (this.topNodeText) {
          //   this.defaultTopNodeText = this.topNodeText
          // } else {
          this.defaultTopNodeText = res.data[0].text
          // }
          this.defaultTreeExpandedKeys = [res.data[0].id]
          this.defaultSelectedKeys = [res.data[0].id]
          this.selectedKeys = [res.data[0].id]
          // 根节点信息
          // const treeNode = [
          //   {
          //     id: this.defaultTopNodeId,
          //     text: this.defaultTopNodeText,
          //     leaf: false,
          //     props: {
          //       isroot: true,
          //     },
          //     children: [],
          //     key: this.defaultTopNodeId,
          //   },
          // ]
          // res.data.forEach((i, index) => {
          for (var fi = 0; fi < res.data.length; fi++) {
            topDepId = !depId ? res.data[fi].id : depId
            var i = res.data[fi]
            treeNode.push({
              id: i.id,
              text: i.text,
              leaf: false,
              props: i.props,
              children: [],
              key: i.id,
            })
          }
          var fni = 0
          treeNode.forEach((i) => {
            auditPermissionTreeService.getCategoryTree(i.id, params).then((res1) => {
              this.spinning = false
              fni = fni + 1
              if (res1.data.length) {
                i.children = res1.data
              }
              if (fni === treeNode.length) {
                this.treeSelect([treeNode[0].id], {
                  node: { dataRef: { id: treeNode[0].id, text: treeNode[0].text }, checked: false },
                  selected: true,
                })
                this.treeData = this.transformData(treeNode)
                this.expandedKeys = this.defaultTreeExpandedKeys
                this.generateList(this.treeData)
                this.empty = false
              }
            })
          })
        } else {
          this.empty = true
          this.spinning = 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: 600px;
  margin-right: $padding-lg;
  transition: width 0.2s;
  .fold {
    position: absolute;
    top: calc(50% - 30px);
    right: -15px;
    z-index: 2;
    width: 18px;
    height: 75px;
    padding: 0;
    border-radius: 0 10px 10px 0;
  }
  :global(.ant-tree) {
    width: 100% !important;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-card-body) {
    height: 100%;
    background: $white;
    // overflow: auto;
  }
}
.collapse {
  width: 0;
  margin-right: 55px;
  :global(.ant-card-body) {
    background: transparent;
    // overflow: auto;
    :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>
