<template>
  <div>
    <a-spin :spinning="spinningtree" :class="$style.spin" />
    <a-empty v-if="empty" />
    <a-tree
      v-else
      :key="key"
      ref="caseTree"
      v-model="checkedKeys"
      :block-node="false"
      :show-icon="true"
      :show-line="true"
      :check-strictly="true"
      :checkable="false"
      :draggable="false"
      :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"
      @drop="onDrop"
    >
      <template v-slot:title="{ text, props }">
        <span v-if="text.indexOf(searchValue) > -1">
          {{ text.substr(0, text.indexOf(searchValue))
          }}<span :class="$style.active">{{ searchValue }}</span
          >{{ text.substr(text.indexOf(searchValue) + searchValue.length) }}</span
        ><span v-else>{{ 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-form-model :model="interForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 15 }">
        <a-form-model-item label="阶段名称" required>
          <a-select v-model="interForm.stageField">
            <a-select-option v-for="item in stage" :key="item.code" :value="item.code">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model> -->
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import LawService from '../law-service'
import components from './_import-components/law-case-tree-import'

export default {
  name: 'LawCaseTree',
  metaInfo: {
    title: 'LawCaseTree',
  },
  components,
  props: {
    // 默认选中节点
    caseType: {
      type: String,
      default: '',
    },
    caseStage: {
      type: String,
      default: '',
    },
    defaultTopNodeText: {
      type: String,
      default: '案件进展阶段',
    },
    defaultTopNodeId: {
      type: String,
      default: '0',
    },
  },
  data() {
    return {
      empty: false,
      spinningtree: true,
      treeData: [],
      dataList: [], // 数组dataList，搜索要用
      defaultTreeExpandedKeys: ['0'],
      defaultSelectedKeys: ['0'],
      checkedKeys: [], // 选中的节点数据
      replaceFields: {
        title: 'text',
        key: 'ids',
      },
      expandedKeys: ['0'],
      searchValue: '',
      searchStr: '',
      key: 0,
      // 树
    }
  },
  mounted() {
    this.initTreeData()
  },
  methods: {
    // 点击地址树展开时调用
    onLoadData(treeNode) {
      let caseType = ''
      let caseStage = ''
      if (treeNode.dataRef.props.parentId === 'root') {
        caseType = treeNode.dataRef.id
      } else {
        caseType = treeNode.dataRef.props.parentId
        caseStage = treeNode.dataRef.id
      }
      return LawService.getCaseTree(caseType, caseStage).then((res) => {
        if (treeNode.dataRef.id !== '0') {
          res.data.forEach((d) => {
            d.props.parentName = treeNode.dataRef.text
            d.props.caseType = treeNode.dataRef.props.parentId
            d.ids = d.id + '_' + treeNode.dataRef.id
          })
          treeNode.dataRef.children = res.data
          this.treeData = this.transformData([...this.treeData])
          this.generateList(this.treeData)
        }
      })
    },
    // 初始化地址树
    initTreeData() {
      LawService.getCaseTree(this.caseType, this.caseStage).then((res) => {
        this.spinningtree = false
        if (res.data.length) {
          res.data.forEach((r) => {
            r.ids = r.id + '_0'
          })
          const treeNode = [
            {
              id: this.caseStage === '' ? this.defaultTopNodeId : this.caseStage,
              ids: this.caseStage === '' ? this.defaultTopNodeId : this.caseStage,
              text: this.defaultTopNodeText,
              leaf: true,
              props: {
                parentId: this.caseStage === '' ? 'root' : this.caseType,
              },
              children: res.data,
              key: this.defaultTopNodeId,
            },
          ]
          this.treeData = this.transformData(treeNode)
          this.expandedKeys = this.defaultTreeExpandedKeys
          this.generateList(this.treeData)
          this.empty = false
        } else {
          this.empty = true
        }
      })
    },
    transformData(data) {
      return data.map((d) => {
        const { children, ...rest } = d
        return {
          ...rest,
          children: children && this.transformData(children),
          scopedSlots: { title: 'title' },
        }
      })
    },
    // 处理搜索用的dataList
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.id
        const title = node.text
        const props = node.props
        this.dataList.push({ key, id: key, title: title, props })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },

    // 点击树
    treeSelect(selectedKeys, info) {
      this.defaultSelectedKeys = selectedKeys
      this.$emit('treeSelect', [...selectedKeys], info)
    },

    /***
     * 选中复选框时的事件
     */
    treeCheck(allKeys, echecked) {
      // echecked.checkedNodes 选中的所有节点信息为数组   .data.props 获取详细信息
      // echecked.node.dataRef  当前选中的节点信息
      if (this.single) {
        this.checkedKeys.checked = []
        this.checkedKeys.checked = [echecked.node.dataRef.id]
      }
      this.$emit('checkedKeys', echecked.node.dataRef, echecked.checkedNodes)
    },
    onExpand(expandedKeys) {
      // 用户点击展开时，取消自动展开效果
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    // 拖拽节点方法
    onDrop(info) {
      // 被插入节点信息
      const dropKey = info.node.eventKey
      const dropNode = info.node.dataRef
      // 拖拽节点信息
      const dragKey = info.dragNode.eventKey
      const dragNode = info.dragNode.dataRef

      const dropPos = info.node.pos.split('-')
      // -1表示之前 0表示合并 1表示之后
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      // 分类合并至事项内
      if (dropNode.props.isroot && (dropPosition === 1) | (dropPosition === -1)) {
        message.info('不能将分类拖拽至与根节点同层级', 1)
        return false
      }
      // 如果被插入节点是末级节点，并且是合并方式的时候，则不可以执行
      if (dropPosition === 0) {
        if (dropNode.props.isEnd === '1') {
          message.info('被插入节点是末级节点,不可执行', 1)
          return false
        }
      }
      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 = {
        nodeId: dragNode.id,
        targetnodeType: dropNode.props.isroot ? 'root' : 'category', // category/root
        targetnodeId: dropNode.id,
        position: dropPosition, // -1 0 1  之前 合并 之后
      }

      LawService.dragNode(dragParams).then((res) => {
        if (!res) {
          message.info(dropNode.text + '节点下存在相同分类编号，拖拽失败')
        }
      })
    },
  },
}
</script>

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