<template>
  <div>
    <a-card
      :body-style="{padding: '24px 32px'}"
      :bordered="false"
      title="组织架构"
    >
      <template slot="extra">
        <a-button type="primary" @click="openModal">新增</a-button>
      </template>
      <tree
        :tree-data="treeData"
        defaultExpandAll
        :replaceFields="replaceFields"
        @select="onSelect"
        @check="onCheck"
      >
        <span :slot="item.id" v-for="item in flatTreeData" :key="item.id">
          <div>
            <span>{{ item.title }}</span>
            <span style="margin-left: 10px" v-if="item.id === currentClickNode">
              <a @click.stop="handclick(item)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="你确定删除这个部门吗?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="deleteDepart(item)"

              >
                <a @click.stop="() => {}">删除</a>
              </a-popconfirm>
            </span>
          </div>
        </span>
      </tree>
    </a-card>

    <!-- 新增的树节点 -->
    <a-modal
      v-model="visible"
      :width="500"
      title="Basic Modal"
      @ok="postDepart"
      :confirm-loading="confirmLoading"
    >
      <div>
        <a-row class="department">
          <a-col :span="4">
            上级部门
          </a-col>
          <a-col
            :span="18"
          >
            <a-tree-select
              v-model="parentLabel"
              @select="selectTreeNode"
              treeNodeFilterProp="title"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择上级部门"
              allow-clear
              :tree-data="treeData"
              tree-default-expand-all
              :replaceFields="replaceFields"
            />
          </a-col>
        </a-row>

        <a-row class="department">
          <a-col :span="4">
            部门名称
          </a-col>
          <a-col
            :span="18"
          >
            <a-input
              v-model.trim="departLabel"
              placeholder="请输入部门名称" />
          </a-col>
        </a-row>
      </div>
    </a-modal>
    <a-modal
      v-model="editTreeNodeVisabled"
      title="编辑节点"
      @ok="putDepart"
      :confirm-loading="confirmLoading"
    >
      <a-input v-model="editTreeNodeValue" ></a-input>
    </a-modal>
  </div>

</template>

<script>
import { Tree } from 'ant-design-vue'
import { deleteDepart, getDepart, postDepart, putDepart } from '@/api/role'
export default {
  name: 'Organiza',
  components: {
    Tree
  },
  computed: {
      replaceFields () {
          return { children: 'children', title: 'label', key: 'id', value: 'label' }
      }
  },
  async created () {
    await this.getDepart()
    this.currentClickNode = this.treeData[0].id
  },
  watch: {
    currentClickNode () {
      this.$emit('currentClickNode', this.currentClickNode)
    }
  },
  data () {
      return {
        editTreeNodeValue: '',
        editTreeNodeId: '',
        editTreeNodeVisabled: false,
        flatTreeData: [],
        // tree选择
        treeExpandedKeys: [],
        parentId: '',
        parentLabel: '',
        // ---------------------------
        visible: false,
        confirmLoading: false,
        departLabel: '', // add or edit时 部门名称
        treeData: [],
        currentClickNode: ''
      }
  },
  methods: {
    // 编辑节点
    async putDepart () {
      const $par = {
        id: this.editTreeNodeId,
        label: this.editTreeNodeValue
      }
      this.confirmLoading = true
      const { code, data } = await putDepart($par)
      this.confirmLoading = false
      if (code === 0) {
        console.log(data)
        data ? this.$message.success('编辑成功') : this.$message.error('编辑失败')
      }
      this.editTreeNodeVisabled = false
      this.getDepart()
    },
    // 选择树节点
    selectTreeNode (value, node, extra) {
        console.log(value, node, extra)
        const { key } = extra.selectedNodes[0]
        this.parentId = key
    },
    // 删除部门
    async deleteDepart (item) {
      const { code, data } = await deleteDepart(item.id)
      if (code === 0) {
        console.log(data)
        data ? this.$message.success('删除成功') : this.$message.error('删除失败')
      }
      this.getDepart()
    },
    // 新增部门
    async postDepart () {
      const $par = {
        parentId: this.parentId,
        label: this.departLabel,
        children: [],
        id: ''
      }
      this.confirmLoading = true
      const { code, data } = await postDepart($par)
      this.confirmLoading = false
      if (code === 0) {
        console.log(data)
      }
      this.getDepart()
      this.visible = false
    },
    // 查询部门
    async getDepart () {
      const { code, data } = await getDepart()
      if (code === 0) {
        console.log(data)
        this.treeData = data
        this.transferTreeData()
      }
    },

    //  将树节点拍平, 便于使用slot自定义渲染树 , 同时把treeData全部加上slots
    transferTreeData () {
        const arr = []
        const recursionTreeData = (treeData) => {
            console.log(treeData, 1)
                treeData.forEach(item => {
                  console.log(item, 'item')
                    if (Array.isArray(item.children) && item.children.length > 0) {
                        recursionTreeData(item.children)
                    }
                    item.slots = { title: item.id }
                    const { label, id } = item
                    arr.push({ title: label, id })
                })
            }
        recursionTreeData(this.treeData)
        this.flatTreeData = arr
    },
    handleOk () {},
    handclick (item) {
        this.editTreeNodeValue = item.title
        this.editTreeNodeId = item.id
        this.editTreeNodeVisabled = true
    },
    // 当前选中的树节点的key
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
      this.currentClickNode = selectedKeys[0]
    },
    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
    },
    openModal () {
      this.visible = true
      this.departLabel = ''
    }
  }
}
</script>
<style scoped lang="less">
.department {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

::v-deep  .ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected {
    background-color: #fff;
}
</style>
