<template>
  <div class="left-tree">
    <div class="btn-outer">
      <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="updateTreeNode('add')" size="mini">新增
      </el-button>
    </div>
    <el-tree :data="tree.data" :default-expand-all="true">
      <template #default="{ node, data }">
          <span class="custom-tree-node" :class="{'tree-node-checked': data.id === tree.checked_id}">
            <span class="tree-node-label" @click="renderTable(data)">
              <i class="el-icon-school"></i> {{ node.label }}
            </span>
            <span class="tree-node-options">
              <a @click="updateTreeNode('edit',data)"><i class="el-icon-edit-outline"></i></a>
              <el-popconfirm confirm-button-text='确定'
                             cancel-button-text='取消'
                             icon="el-icon-info"
                             icon-color="red"
                             title="确定删除此节点及其子节点吗？"
                             @confirm="removeNode(node, data)">
                <a slot="reference"><i class="el-icon-delete"></i></a>
              </el-popconfirm>
            </span>
          </span>
      </template>
    </el-tree>

    <!--    @closed="dialog_init"-->
    <!--    @open="form_clear_validate"-->

    <el-dialog
        :title="dialog.title"
        :close-on-click-modal="false"
        :visible.sync="dialog.visible"
        v-if="dialog.visible"
        :destroy-on-close="true"
        width="800px">
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="120px">
        <el-row>
          <el-col :span="24" v-if="dialog.type === 'add'">
            <el-form-item label="上级节点" prop="pid">
              <el-cascader
                  :options="tree.data"
                  :props="{ checkStrictly: true }"
                  clearable
                  filterable
                  placeholder="若不选默认添加为根节点"
                  v-model="form.pid"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model.number="form.sort"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="onSubmit('form')">提交</el-button>
              <el-button @click="onReset('form')">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { org_list_tree, org_add, org_edit, org_delete } from './api'
import { hdlx_list_tree, hdlx_add, hdlx_edit, hdlx_delete } from './api'

export default {
  // 父组件传参 树的类型
  props: {
    treeType: {
      type: String,
      required: true
    }
  },
  data() {
    const common_data = {
      "zzjg": {
        name: '组织架构',
        form: {
          objName: 'user_org',
          pid: 'uo_pid',
          id: 'uo_id',
          name: 'uo_name',
          sort: 'uo_sort'
        },
        getTree: org_list_tree,
        addTreeNode: org_add,
        editTreeNode: org_edit,
        delTreeNode: org_delete
      },
      "hdlxgl": {
        name: '活动类型',
        form: {
          objName: 'hdpb_hdlx',
          pid: 'hh_pid',
          id: 'hh_id',
          name: 'hh_name',
          sort: 'hh_sort',
        },
        getTree: hdlx_list_tree,
        addTreeNode: hdlx_add,
        editTreeNode: hdlx_edit,
        delTreeNode: hdlx_delete
      }
    }
    const validatePID = (rule, value, callback) => {
      if (this.treeType === 'zzjg' && !value ) {
        callback(new Error('组织架构不可为空'))
      } else {
        callback()
      }
    }
    return {
      common_data,
      // 弹出层
      dialog: {
        title: '',
        visible: false,
        type: 'add'
      },
      form: {
        pid: '',
        name: '',
        sort: 0
      },
      // 树相关数据
      tree: {
        checked_id: '',
        data: []
      },
      // 表单验证规则
      rules: {
        pid: [
          // {required: true, message: '上级节点不可为空'},
          {validator: validatePID, trigger: 'blur'}
        ],
        name: [
          {required: true, message: '名称不可为空'},
        ],
        sort: [
          {required: true, message: '排序不可为空'},
          {type: 'number', message: '排序必须为数字值'}
        ]
      },
    }
  },
  created() {
    this.getTreeData()
  },
  computed: {
    // 当前树对象
    nowTree() {
      return this.common_data[this.treeType]
    },
  },
  // 弹出层标题
  watch: {
    "dialog.type": {
      handler: function (newVal) {
        let typeName = newVal === 'add' ? '新增' : '编辑'
        this.dialog.title = this.nowTree.name + typeName
      },
      immediate: true
    },
    "dialog.visible": {
      handler: function (newVal) {
        !newVal ? this.form = {pid: '', name: '', sort: 0} : null
      },
      immediate: true
    }
  },
  methods: {
    // 获取树的数据
    getTreeData() {
      this.nowTree.getTree()
          .then(res => {
            if (res.code === '1') {
              this.tree.data = res.data.one_info
            }
          })
    },
    // 更新节点
    updateTreeNode(action, data) {
      this.dialog.type = action
      if (action === 'edit' && data) {
        this.form.name = data.label
        this.form.sort = data.sort * 1
        this.tree.checked_id = data.id
      }
      this.dialog.visible = true
    },
    // 删除节点
    removeNode(node, data) {
      const params = {
        [this.nowTree.form.id]: data.id
      }
      this.nowTree.delTreeNode(params)
          .then(res => {
            if (res.code === '1') {
              this.$message.success(res.msg)
              this.getTreeData()
            }
          })
    },
    // 提交表单
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 处理表单参数格式
          const formData = {
            pid: this.form.pid[this.form.pid.length - 1],
            name: this.form.name,
            sort: this.form.sort
          }
          const form_params = {
            [this.nowTree.form.pid]: formData.pid,
            [this.nowTree.form.name]: formData.name,
            [this.nowTree.form.sort]: formData.sort,
          }
          const params = {
            issubmit: 1,
            [this.nowTree.form.objName]: form_params
          }
          switch (this.dialog.type) {
              // 添加节点
            case "add":
              this.nowTree.addTreeNode(params)
                  .then(res => {
                    if (res.code === '1') {
                      this.$message.success('操作成功')
                      this.getTreeData()
                      this.dialog.visible = false
                    }
                  })
              break
              // 编辑节点
            case "edit":
              params[this.nowTree.form.id] = this.tree.checked_id
              this.nowTree.editTreeNode(params)
                  .then(res => {
                    if (res.code === '1') {
                      this.$message.success('操作成功')
                      this.getTreeData()
                      this.dialog.visible = false
                    }
                  })
              break
          }
        } else {
          return false;
        }
      });

    },
    // 重置表单
    onReset(formName) {
      this.$refs[formName].resetFields();
    },
    // 弹出层重置
    dialog_init() {
      this.form = {pid: '', name: '', sort: 0}
    },
    // 清除表单校验
    form_clear_validate() {
      const form_ref = this.$refs['form']
      if (form_ref) {
        form_ref.clearValidate()
      }
    },
    // 暴露方法
    renderTable(data) {
      this.tree.checked_id = data.id
      this.$emit('renderTable', {'msg': data})
    },
  }
}
</script>

<style scoped>
.btn-outer {
  text-align: center;
  padding: 10px 20px;
}

.add-btn {
  width: 80%;
}

::v-deep .el-tree {
  color: #666;
  background-color: inherit;
}


::v-deep .el-cascader {
  display: block;
}

.left-tree {
  display: inline-block;
  /*width: 280px;*/
  width: 100%;
  height: calc(100vh - 130px);
  background: #F9FBFC;
  border-radius: 6px;
  overflow: auto;
}

.custom-tree-node {
  width: 100%;
  /*display: flex;*/
  /*justify-content: space-between;*/
  overflow: hidden;
  position: relative;
}

.tree-node-checked {
  color: #265CD4;
  background-color: #F4F8FE;
}

.custom-tree-node:hover {
  background-color: #F4F8FE;
}

.tree-node-label {
  display: inline-block;
  max-width: calc( 100% - 40px );
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tree-node-options {
  display: none;
  position: absolute;
  right: 0;
}

.custom-tree-node:hover > .tree-node-options {
  display: inline-block;
}
</style>
