<template>
  <a-drawer
    title="设备类型配置生成"
    placement="right"
    :width="isMobile ? screenWidth : screenWidth * 0.85"
    :visible="visible"
    @close="onClose"
  >
    <a-row :gutter="24">
      <a-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
        <div class="page-header-index-wide">
          <a-card :bordered="false">
            <div slot="title">
              <div v-show="changeflag" >
                <a-button v-show="treeData.length === 0" @click="showModal('eventAddRoot')">添加根节点</a-button>
                <a-divider v-show="treeData.length === 0" type="vertical" />
                <a-button v-show="treeData.length > 0" @click="showModal('eventAddSame')">添加同级</a-button>
                <a-divider v-show="treeData.length > 0" type="vertical" />
                <a-button v-show="treeData.length > 0" @click="showModal('eventAddSub')">添加下级</a-button>
                <a-divider v-show="treeData.length > 0" type="vertical" />
                <a-button v-show="treeData.length > 0" @click="showModal('eventModify')">修改</a-button>
                <a-divider v-show="treeData.length > 0" type="vertical" />
                <a-button v-show="treeData.length > 0" @click="eventDelete">删除</a-button>
              </div>
            </div>
            <a-tree
              :tree-data="treeData"
              @select="onEventTreeNodeSelected"
              :defaultExpandAll="true"
              :selectedKeys.sync="selectKeys"
              showLine >
              <template slot="custom" slot-scope="item">
                <div style="position: relative;float:left;">
                  {{ item.title }}
                </div>
                <div v-show="item.visibleModel" style="position: absolute;height:25px;top: 3%;left:3.8%" >
                  <a-input-group compact>
                    <a-input type="text" style="width: 30%" placeholder="名称" ref="myInput" v-model="nowchangetitle" />
                    <a-input type="text" style="width: 30%" placeholder="值" ref="myInput" v-model="nowchangevalue" />
                    <a-button
                      @click="handleOk(item)"
                      type="link">
                      保存
                    </a-button>
                    <a-divider type="vertical" />
                    <a-button
                      @click="handleCancel(item)"
                      type="link"
                    >取消</a-button>
                  </a-input-group>
                </div>
              </template>
            </a-tree>
          </a-card>
        </div>
      </a-col>
      <a-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
        <a-card :bordered="false" title="预览" size="small" style="overflow: auto">
          <json-viewer :copyable="{copyText: '复制', copiedText: '已复制'}" :value="treeData" :expand-depth="parseInt('100')" style="overflow: auto;max-height: 440px"></json-viewer>
        </a-card>
      </a-col>
    </a-row>
  </a-drawer>
</template>

<script>

import { mapState } from 'vuex'
import JsonViewer from 'vue-json-viewer'

export default {
  name: 'LogDetailsView',
  data () {
    return {
      // 页面宽度
      screenWidth: document.documentElement.clientWidth,
      selectKeys: [],
      treeData: [],
      eventSelectedNode: null,
      // 当前操作类型
      operate: '',
      // 新建节点中的值
      nowchangetitle: '',
      // 新建节点中的值
      nowchangevalue: '',
      // 操作按钮显示控制
      changeflag: true
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  components: {
    JsonViewer
  },
  methods: {
    showModal (operate) {
      if (!this.eventSelectedNode && this.treeData.length > 0) {
        this.$message.warning('请选择节点后进行操作')
        return
      }
      if (operate === 'eventAddSame' && this.eventSelectedNode && !this.eventSelectedNode.$parent.dataRef && this.treeData.length > 0) {
        this.$message.warning('不能给根节点添加同级')
        return
      }
      this.changeflag = false
      this.operate = operate
      switch (this.operate) {
        case 'eventAddRoot':
          this.eventAddRoot()
          break
        case 'eventAddSame':
          this.eventAddSame()
          break
        case 'eventAddSub':
          this.eventAddSub()
          break
        case 'eventModify':
          this.nowchangetitle = this.eventSelectedNode.dataRef.title
          this.nowchangevalue = this.eventSelectedNode.dataRef.value
          this.setvisibleModel(true, 'visibleModel')
          break
        default:
          this.$message.warning('未获取到操作指令')
      }
    },
    handleOk (item) {
      if (this.operate === 'eventModify') {
        this.eventModify()
      } else {
        this.eventSelectedNode.dataRef.title = this.nowchangetitle
        this.eventSelectedNode.dataRef.value = this.nowchangevalue
      }
      this.setvisibleModel(false, 'visibleModel')
      this.clearnodename()
    },
    setvisibleModel (flag, value) {
      const dataRef = this.eventSelectedNode.dataRef
      this.$set(dataRef, value, flag)
    },
    handleCancel (item) {
      if (this.operate === 'eventModify') {
        this.setvisibleModel(false, 'visibleModel')
      } else if (this.operate === 'eventAddRoot') {
        this.treeData = []
      } else {
        this.searchitem(item, this.treeData)
      }
      this.clearnodename()
    },
    searchitem (option, arr, type = 'delete') {
      // 递归删除树中某个节点
      for (let s = 0; s < arr.length; s++) {
        if (arr[s].key === option.key) {
          if (type === 'delete') {
            arr.splice(s, 1)
          }
          break
        } else if (arr[s].children && arr[s].children.length > 0) { // 递归条件
          this.searchitem(option, arr[s].children)
        }
      }
    },
    clearnodename () {
      this.operate = ''
      this.nowchangetitle = ''
      this.nowchangevalue = ''
      this.changeflag = true
    },
    onClose () {
      this.$emit('update:visible', false)
    },
    onEventTreeNodeSelected (seleteKeys, e) {
      if (e.selected) {
        this.eventSelectedNode = e.node
        return
      }
      this.eventSelectedNode = null
    },
    eventAddRoot () {
      this.$set(this.treeData, 'children', [])
      this.treeData.push({
        title: '',
        value: '',
        key: new Date().getTime(),
        scopedSlots: { title: 'custom' },
        visibleModel: true
      })
    },
    eventAddSame () {
      // 查找父级
      const dataRef = this.eventSelectedNode.$parent.dataRef
      if (!dataRef.children) {
        this.$set(dataRef, 'children', [])
      }
      dataRef.children.push({
        title: '',
        value: '',
        key: new Date().getTime(),
        scopedSlots: { title: 'custom' },
        visibleModel: true
      })
    },
    eventAddSub () {
      const dataRef = this.eventSelectedNode.dataRef
      if (!dataRef.children) {
        this.$set(dataRef, 'children', [])
      }
      this.eventSelectedNode.vcTree.$data._expandedKeys.push(dataRef.key)
      dataRef.children.push({
        title: '',
        value: '',
        key: new Date().getTime(),
        scopedSlots: { title: 'custom' },
        children: [],
        visibleModel: true
      })
    },
    eventModify () {
      const dataRef = this.eventSelectedNode.dataRef
      // this.$set(dataRef, 'children', [])
      dataRef.title = this.nowchangetitle
      dataRef.value = this.nowchangevalue
    },
    eventDelete () {
      if (!this.eventSelectedNode.$parent.dataRef) {
        this.treeData = []
        return
      }
      const parentDataRef = this.eventSelectedNode.$parent.dataRef
      // 判断是否是顶层
      const children = parentDataRef.children
      const currentDataRef = this.eventSelectedNode.dataRef
      const index = children.indexOf(currentDataRef)
      children.splice(index, 1)
    },
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    }
  },
  computed: {
    ...mapState('setting', ['isMobile'])
  }
}
</script>
<style lang="less" scoped>
.ant-tree-title {
  width: 100%;
}
.title {
  float: left;
}
.ant-card-body {
  .ant-tree {
    line-height: 3;
    li {
      position: relative;
    }
  }
}
.ant-card-body .but_type {
  float: right;
  position: absolute;
  right: 40px;
}
</style>
