<template>
  <div class="left-tree">
    <el-tree
      ref="tree"
      class="tree-style"
      :data="typeList"
      :props="defaultProps"
      default-expand-all
      highlight-current
      :expand-on-click-node="false"
      empty-text="暂无数据"
      node-key="id"
      @node-click="select"
    >
      <template #default="{ node }">
        <div class="custom-tree-node">
          <div :class="['text', { 'level2-text': node.level === 3 }]">
            {{ node.label }}
          </div>
          <el-popover
            :ref="`edit${node.data.id}`"
            placement="right"
            trigger="click"
            :visible-arrow="false"
            popper-class="poper-style"
            @show="selectPopId = node.data.id"
          >
            <!-- <div
              v-if="node.data.id || node.data.id === 0"
              class="item-line bottom-line"
              @click="handleBusinessDialog(node.data.id)"
            >
              新增业务表
            </div> -->
            <div
              v-if="node.level < 2"
              class="item-line"
              @click="handleTypeDialog('add', node.data.id)"
            >
              <!-- {{ node.data.id ? '新增子分类' : '新增分类' }} -->
              {{ '新增分类' }}
            </div>
            <div
              v-if="node.data.id"
              class="item-line"
              @click="handleTypeDialog('edit', node.data.id)"
            >
              修改分类
            </div>
            <div v-if="node.data.id" class="item-line" @click="delType(node.data)"> 删除分类</div>
            <!-- <i slot="reference" class="el-icon-more" /> -->
            <template v-slot:reference>
              <img class="more-icon" :src="moreImg" @click.stop="toShowPop(node.data.id)" />
            </template>
          </el-popover>
        </div>
      </template>
    </el-tree>
    <!-- 新增分类 弹窗 -->
    <TypeDialog
      :id="classifyId"
      v-model:visible="openTypeDialog"
      :type-list="treeTypeList"
      :type="typeDialogMode"
      @save="loadData"
    />
    <!-- 业务表 弹窗 -->
    <!-- <BusinessDialog
      v-model:visible="openBusinessDialog"
      :type-list="classifyTreeList"
      :type="businessDialogMode"
      :default-classify-id="defaultClassifyId"
      @save="loadData"
    /> -->
  </div>
</template>

<script>
import TypeDialog from './TypeDialog.vue'
// import BusinessDialog from './BusinessDialog.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { tree, delBusinessType } from '@common/src/api/system-config/field'
import moreImg from '@common/src/assets/imgs/more.png'

export default {
  name: 'LeftTree',
  components: {
    TypeDialog,
    // BusinessDialog,
    ElTree,
    ElPopover,
    // eslint-disable-next-line vue/no-unused-components
    ElMessageBox,
    // eslint-disable-next-line vue/no-unused-components
    ElMessage
  },
  data() {
    return {
      moreImg,
      defaultProps: {
        children: 'children',
        label: 'classifyName'
      },
      // typeList: [], // 业务表分类
      selectedItem: '',
      openTypeDialog: false,
      openBusinessDialog: false,
      typeDialogMode: '', // 分类弹窗的类型，add-新增，edit-修改
      businessDialogMode: 'add', // 业务表弹窗的类型，add-新增，edit-修改
      treeTypeList: [], // 新增业务表分类弹窗里的 上级分类 下拉树列表
      classifyTreeList: [], // 新增业务表弹窗里 所属分类 下拉树列表
      classifyId: null, // 传给分类弹窗
      typeList: [
        {
          id: null,
          classifyName: '所有业务表',
          children: []
        }
      ],
      defaultClassifyId: '', // 传给新增业务表弹窗，默认的分类
      selectPopId: ''
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      // 获取业务表分类列表
      const { data, success } = await tree()
      if (success) {
        const treeData = data || []
        // 渲染左侧树
        this.typeList[0].children = treeData
        // 给新增分类用
        this.treeTypeList = [...treeData]
        // 给新增业务表用
        this.classifyTreeList = [...treeData]
        this.$emit('getTypeList', treeData)
      }
    },
    select(item, node, i) {
      this.selectedItem = item.id
      this.$emit('selectType', item.id)
      console.log(
        this.selectPopId,
        `edit${this.selectPopId}`,
        this.$refs[`edit${this.selectPopId}`]
      )
      this.selectPopId !== '' && this.$refs[`edit${this.selectPopId}`].doClose()
    },
    // 新增/修改分类
    handleTypeDialog(type, id) {
      this.openTypeDialog = true
      this.typeDialogMode = type
      this.classifyId = id
    },
    // 新增业务表
    handleBusinessDialog(id) {
      this.openBusinessDialog = true
      this.defaultClassifyId = id
    },
    // 删除 分类
    delType(item) {
      ElMessageBox.confirm(
        '您确定要此分类吗？注意：删除后，此分类下所有的业务表将会被设置为“未分类”。',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        const { success, message } = await delBusinessType({
          id: item.id
        })
        if (success) {
          this.loadData()
        }
        ElMessage({
          type: success ? 'success' : 'error',
          message: message || (success && '删除成功!')
        })
      })
    },
    toShowPop(val) {
      console.log('toShowPop', val)
      console.log('this.selectPopId', this.selectPopId)
      this.$nextTick(() => {
        // 关闭之前点开的popover
        this.$refs[`edit${this.selectPopId}`].doClose()
        // 因为设置了阻止事件冒泡，所以需要手动将当前行选中
        this.$refs.tree.setCurrentKey(val)
        this.selectedItem = val
        this.$emit('selectType', val)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.left-tree {
  width: 274px;
  flex-shrink: 0;
  padding: 5px 16px 0 0;
  border: 1px solid #eee;

  .custom-tree-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 8px;
    height: 40px;
    width: 100%;
    line-height: 40px;

    .text {
      max-width: 180px;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .level2-text {
      max-width: 143px;
    }

    .more-icon {
      display: none;
    }

    &:hover .more-icon {
      display: block;
    }
  }
}
</style>
<style lang="less">
.poper-style {
  z-index: 1900 !important;
  padding: 10px 0;

  .item-line {
    height: 30px;
    line-height: 30px;
    // padding: 0 20px;
    &:hover {
      background: #f2f2f2;
      cursor: pointer;
    }
  }

  .bottom-line {
    border-bottom: 1px solid #e5e5e5;
  }
}
</style>
