<template>
  <div class="dg-dict-tree">
    <dg-tree
      ref="tree"
      api-code="sysDictTree"
      :root="dimCode"
      node-key="ROWCODE"
      pnode-key="PARENTCODE"
      label="ROWNAME"
      :show-screen="true"
      :default-expand-all="false"
      :expand-on-click-node="false"
      placeholder="输入关键字进行过滤"
      :node-buttons="nodeButtons"
      :tree-list-data.sync="data"
      @click="handleNodeClick"
    >
    </dg-tree>

    <el-button v-if="showAdd" icon="el-icon-plus" class="topic-add" @click="showFormDrawer('insert')"></el-button>

    <dg-drawer :title="title" :visible.sync="visible" append-to-body destroy-on-close @confirm="handleFormSubmit">
      <dg-form ref="form" :form-data="form" :form-items="formItems" :rules="formRules" label-position="top"></dg-form>
    </dg-drawer>
  </div>
</template>

<script>
function getUUID() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  let id = ''
  for (var i = 0; i < 32; i++) {
    var index = parseInt(Math.random() * 61)
    id += chars[index]
  }
  return id
}

export default {
  name: 'DgDictTree',
  props: {
    dimCode: {
      type: String,
      required: true,
    },
    dimName: {
      type: String,
      required: true,
    },
    operation: {
      type: [String, Object],
      default: '',
    },
    showTopAdd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      data: [],
      form: {},
      formItems: [
        { label: '上级节点', value: '_PARENT', editer: 'input', placeholder: '上级节点', disabled: true },
        { label: '节点名称', value: 'ROWNAME', editer: 'input', placeholder: '节点名称', disabled: false },
      ],
      formRules: {
        ROWNAME: { required: true, message: '请输入节点名称' },
      },
      type: 'insert',
      title: '新增节点',
      visible: false,
    }
  },
  computed: {
    nodeButtons() {
      const { operation } = this
      const buttons = typeof operation === 'string' ? operation.split(',') : Object.keys(operation)

      const map = {
        sibling: { title: '添加同级节点', icon: 'el-icon-plus', fn: this.addBrotherNode },
        child: { title: '添加子级节点', icon: 'el-icon-folder-add', fn: this.addChildNode },
        edit: { title: '编辑节点', icon: 'el-icon-edit', fn: this.editNode },
        delete: { title: '删除节点', icon: 'el-icon-delete', fn: this.deleteNode },
      }
      return buttons
        .map((key) => {
          if (!map[key.trim()]) return ''
          return {
            ...map[key.trim()],
            ...operation[key],
          }
        })
        .filter(Boolean)
    },
    showAdd() {
      return this.showTopAdd && this.data.every(({ ROWCODE }) => !ROWCODE)
    },
  },
  methods: {
    handleNodeClick(...args) {
      this.$emit('node-click', ...args)
    },
    addBrotherNode(h, { node, data }) {
      this.showFormDrawer('insert', {
        PARENTCODE: data.PARENTCODE,
        _PARENT: node.parent.data.ROWNAME,
      })
    },
    addChildNode(h, { data }) {
      this.showFormDrawer('insert', {
        PARENTCODE: data.ROWCODE,
        _PARENT: data.ROWNAME,
      })
    },
    editNode(h, { data }) {
      this.showFormDrawer('update', { ...data })
    },
    async deleteNode(h, { data }) {
      try {
        await this.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })

        this.request('delete', data)
      } catch (e) {
        //
      }
    },
    showFormDrawer(type, data) {
      const { dimName, dimCode } = this
      const { ID, PARENTCODE = dimCode, _PARENT = dimName, ROWCODE = getUUID(), ROWNAME = '' } = data
      this.form = {
        ID,
        DIMCODE: dimCode,
        DIMNAME: dimName,
        PARENTCODE,
        _PARENT,
        ROWCODE,
        ROWNAME,
      }
      this.type = type
      this.title = type === 'update' ? '编辑节点' : '新增节点'
      this.visible = true
    },
    async handleFormSubmit() {
      const valid = await new Promise((resolve) => {
        this.$refs.form.$refs.sonFormData.validate((v) => resolve(v))
      })

      if (!valid) return

      const { type, form } = this
      this.request(type, form)
    },
    async request(command, data) {
      const { success } = await this.$api.DgJsonStore({
        apiCode: 'sysDictMember',
        params: {
          command: command,
          records: JSON.stringify([data]),
        },
      })

      if (success) {
        this.$message.success('数据操作成功！')
        this.$refs['tree'].getData()
        this.visible = false
        this.$emit('updated', command, data)
      }
    },
  },
}
</script>
