<template>
  <el-dialog
    v-loading="loading"
    v-if="dialogVisible"
    :append-to-body="appendToBody"
    :visible.sync="dialogVisible"
    :fullscreen="fullscreen"
    title="编辑">
    <el-input v-model="filterText" placeholder="输入关键字进行过滤"/>
    <div style="margin-top: 10px">
      <el-tree
        ref="tree"
        :data="data"
        :props="defaultProps"
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        node-key="id"
        default-expand-all
        draggable>
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <el-button type="text" size="mini" @click="() => append(data)">添加下一级</el-button>
            <el-button
              :disabled="node.disabled === '1'"
              type="text"
              size="mini"
              @click="() => edit(data)">编辑</el-button>
            <el-button
              :disabled="node.disabled === '1'"
              type="text"
              size="mini"
              @click="() => remove(node, data)">删除</el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="goBack">取 消</el-button>
      <el-button type="primary" @click="addLabel">添加新根节点</el-button>
      <el-button v-if="!fullscreen" @click="implementFullscreen(true)">全 屏</el-button>
      <el-button v-if="fullscreen" @click="implementFullscreen(false)">推出全屏</el-button>
      <el-button type="primary" @click="saveTree">确 定</el-button>
    </div>
    <edit-son-label ref="editSonLabel" append-to-body @getResult="getResult"/>
  </el-dialog>
</template>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-divider--vertical {
  height: 100%;
}
</style>

<script>
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import uploadFile from '../../../components/UploadFile'
import { requestFN } from '@/utils/request'
import editSonLabel from './editSonLabel'

let id = 1000

export default {
  components: { uploadFile, Pagination, editSonLabel },
  directives: { waves },
  props: {
    appendToBody: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'NAME'
      },
      filterText: '',
      primogenitor: '',
      newPrimogenitor: '',
      options: [],
      addFlag: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      fullscreen: false,
      deleteIds: '',
      TYPE: '',
      v: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    init(e) {
      this.dialogVisible = true
      this.TYPE = e.TYPE
      this.choosePrimogenitor()
    },
    goBack() {
      this.dialogVisible = false
      this.clear()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.NAME.indexOf(value) !== -1
    },
    append(data) {
      const newChild = { BUS_LABEL_FACTORY_ID: id++, label: 'test', children: [] }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    },
    edit(data) {
      this.$refs.editSonLabel.init(data)
    },
    remove(node, data) {
      this.$confirm('确定要删除节点吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.BUS_LABEL_FACTORY_ID === data.BUS_LABEL_FACTORY_ID)
        this.deleteIds = this.deleteIds + ',' + data.BUS_LABEL_FACTORY_ID
        children.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    getResult(e) {
      if (e && e.root && e.root === '1') {
        const newChild = { BUS_LABEL_FACTORY_ID: id++, IS_ANCESTORS_FLAG: '1', label: 'test', children: [], NAME: e.NAME }
        this.data.push(newChild)
      }
      this.data = this.analysis(JSON.parse(JSON.stringify(this.data)), e)
    },
    analysis(arr, e) {
      const index = arr.findIndex(item => item.BUS_LABEL_FACTORY_ID === e.BUS_LABEL_FACTORY_ID)
      if (index === -1) {
        for (const arrKey in arr) {
          (arr[arrKey].children && arr[arrKey].children.length > 0) && this.analysis(arr[arrKey].children, e)
        }
      }
      return arr
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class='custom-tree-node'>
          <span>{node.label}</span>
          <span>
            <el-button size='mini' type='text' on-click={() => this.append(data)}>添加下一级</el-button>
            <el-button size='mini' type='text' on-click={() => this.remove(node, data)}>删除</el-button>
          </span>
        </span>)
    },
    openMeter() {
      this.addFlag = true
    },
    save() {
      this.addFlag = false
      this.loading = true
      requestFN(
        '/labelFactory/addAncestors',
        {
          NAME: this.newPrimogenitor,
          TYPE: this.TYPE
        }
      ).then((data) => {
        if (data.code !== '0') {
          this.$message.error(data.errorMessage)
        } else {
          this.$message.success('保存成功')
        }
        this.loading = false
      }).catch((e) => {
        this.loading = false
      })
    },
    saveTree() {
      this.sort(this.data)
      if (this.data === null || this.data.length <= 0) {
        this.$message.error('不能删除根节点或保存项目为空')
        return
      }
      this.loading = true
      requestFN(
        '/labelFactory/saveTree',
        {
          tree: JSON.stringify(this.data),
          TYPE: this.TYPE
        }
      ).then((data) => {
        this.loading = false
        this.dialogVisible = false
        this.$message.success('保存成功')
        this.clear()
      }).catch((e) => {
        this.loading = false
        this.$message.error(e)
      })
    },
    sort(arr) {
      for (const arrKey in arr) {
        arr[arrKey].SORT = arrKey
        if (arr[arrKey].children && arr[arrKey].children.length > 0) this.sort(arr[arrKey].children)
      }
    },
    clear() {
      this.addFlag = false
      this.options = []
      this.primogenitor = ''
      this.newPrimogenitor = ''
      this.data = []
      this.filterText = ''
    },
    choosePrimogenitor() {
      requestFN(
        '/labelFactory/tree',
        {
          IS_ANCESTORS_FLAG: '1'
        }
      ).then((data) => {
        this.loading = false
        this.data = data.tree
      }).catch((e) => {
        this.loading = false
      })
    },
    implementFullscreen(e) {
      this.fullscreen = e
    },

    addLabel() {
      this.$refs.editSonLabel.init({ root: '1' })
    }
  }
}

</script>
