<template>
  <a-card :bordered="false">
    <a-row :gutter="24">
      <!-- 左侧菜单树列表 -->
      <a-col :span="8">
        <a-row :gutter="24" class="textCount">
          <a-icon type="info-circle" style="color: #1890FF;margin-right: 10px;" />
          <span>当前选择：<span style="color: #40a9ff;font-weight: 600;">{{ selectedMenu }}</span><span v-if="selectedKeys.length" class="imgSize" @click="cancelSel">取消选择</span></span>
        </a-row>

        <a-row :gutter="24" >
          <a-row :gutter="24" >
            <a-input-search placeholder="搜索" style="width: 100%" @change="onChange" id="register-onChange"/>
          </a-row>
          <a-tree
            @expand="onExpand"
            :treeData="getMenus"
            :expandedKeys="expandedKeys"
            :autoExpandParent="autoExpandParent"
            @select="onSelect"
            :selectedKeys="selectedKeys"
          >
            <template slot="title" slot-scope="{title}">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </a-row>
      </a-col>
      <!-- 右侧 -->
      <a-col :span="16" >

        <a-form :form="form" @submit="handleSubmit">
          <a-form-item label=" " :colon="false" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-button style="margin-right: 10px;" type="primary" icon="plus" @click="addChild" id="register-addChild">新增子分类</a-button>
            <a-button style="margin-right: 10px;background-color: #19be6b;color: #fff;" type="" icon="plus" @click="addTop" id="register-addTop">新增根节点</a-button>
            <a-button style="margin-right: 10px;background-color: red;color: #fff;" type="" icon="delete" @click="remove()" id="register-remove">删除</a-button>
          </a-form-item>
          <!-- 父路径 -->
          <a-form-item label="父路径" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              disabled
              placeholder=""
              id="register-parentPath"
              v-decorator="['formData.parentPath', {
                initialValue: formData.parentPath,
                rules: [] }]"
            />
          </a-form-item>
          <!-- 显示名称-->
          <a-form-item label="显示名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              placeholder="请输入节点显示名称30个字以内"
              id="register-dispname"
			  :maxLength="30"
			  allowClear
              v-decorator="['formData.dispname', {
                initialValue: formData.dispname,getValueFromEvent: $filterEmpty,
                rules: [{ required: true, message: '请输入节点显示名称30个字以内!' }] }]"
            />
          </a-form-item>
          <!-- 名称 -->
          <a-form-item label="编码" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              placeholder="请输入节点code"
              id="register-name"
			  allowClear
              v-decorator="['formData.name', {
                initialValue: formData.name,getValueFromEvent: $filterEmpty,
                rules: [{ required: true, message: '请输入节点code!' }] }]"
            />
          </a-form-item>

          <!-- 值 -->
          <a-form-item label="值" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              :maxlength="20"
              placeholder="请输入节点值"
			  allowClear
              id="register-value"
              v-decorator="['formData.value', {
                initialValue: formData.value,getValueFromEvent: $filterEmpty,
                rules: [{ required: true, message: '请输入节点值!' }] }]"
            />
          </a-form-item>

          <!-- 排序值 -->
          <a-form-item label="排序" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-input
              type="number"
              :maxlength="20"
			  allowClear
              id="register-index"
              placeholder="请输入正确的序号"
              v-decorator="['formData.index', {
                initialValue: formData.index,getValueFromEvent: $filterEmpty,
                rules: [{ required: true, message: '请输入正确的序号!' }] }]"
            />
          </a-form-item>

          <!-- 状态 -->
          <a-form-item label="是否启用" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-radio-group
              name="radioGroup"
              id="register-isEnable"
              v-decorator="[
                'formData.isEnable',
                {
                  initialValue: formData.isEnable,
                  rules: [{ required: true, message: '请选择状态!' }] },
              ]"
            >
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="备注" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
            <a-textarea
              v-decorator="[
                'formData.desc',
                { initialValue: formData.desc,getValueFromEvent: $filterEmpty,
                  rules: [] },
              ]"
			  :maxLength="500"
              style="min-height: 60px;"
              placeholder="输入内容为500个字以内"
              id="register-desc"
              autosize />
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
            <a-button type="primary" @click="handleSubmit()" id="register-handleSubmit">
              保存
            </a-button>
            <a-button :style="{ marginLeft: '8px' }" @click="reset" id="register-reset">
              重置
            </a-button>
          </a-form-item>
        </a-form>

      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import { listRegister, saveRegister, delRegisterNode } from '@/api/register'
import _ from 'lodash'

export default {
  name: 'Menu',
  components: {
    STable, VSelect
  },
  props: {},
  data () {
    return {
      treeData: [],
      dataList: [],
      searchValue: '',
      actions: 'addTop', // addTop:添加一级分类,addChild：添加子分类，edit
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      selectedData: {}, // 被选中的节点数据
      selectedMenu: '', // 选择的树节点名
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'register' }),
      parentData: {}, // 父级菜单
      formData: {},
      formDataBack: {
        id: '',
        dispname: '',
        name: '',
        value: '',
        index: '',
        parentPath: '',
        isEnable: '',
        desc: '',
        parentId: '0'
      }

    }
  },
  computed: {
    getMenus () {
      this.generateList(this.treeData)
      return this.treeData
    }
  },
  methods: {
    initPage () {
      this.addTop()
      this.initTree()
    },
    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    onSelect (selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
      if (info.selected) {
        this.selectedData = info
        const data = info.selectedNodes[0].data.props
        this.selectedMenu = data.dispname
        this.formData = {
          id: data.id,
          dispname: data.dispname,
          name: data.name,
          value: data.value,
          index: data.index,
          parentPath: data.parentPath,
          isEnable: data.isEnable,
          desc: data.desc,
          parentId: data.parentId
        }
        this.formData.isEnable = Number(this.formData.isEnable)
        this.actions = 'edit'
      } else {
        this.selectedMenu = ''
        this.clear()
      }
    },
    generateList (data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        node.key = node.id
        node.title = node.dispname
        const key = node.title
        this.dataList.push({ key, title: key })
        node.scopedSlots = { title: 'title' }
        // node.slots = { icon: node.type == '0' ? 'file' : 'pushpin' }

        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    getParentKey (key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some(item => item.title == key)) {
            parentKey = node.key
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },
    onChange (e) {
      const value = e.target.value
      const expandedKeys = this.dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.title, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    // 初始化 查询Tree 数据
    initTree () {
      const _this = this
      listRegister().then(res => {
        if (res.status === '200') {
          const treeData = res.data
          if (treeData) {
            _this.treeData = treeData
          }
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    // 添加根节点
    addTop () {
      this.clear()
      this.actions = 'addTop'
      this.formData = _.cloneDeep(this.formDataBack)
    },
    // 添加子节点
    addChild () {
      if (!this.selectedKeys.length) {
        this.$message.warning('请先选择一个根节点')
      }

      this.actions = 'addChild'
      const currentNode = this.selectedData.selectedNodes[0].data.props
      this.formData = _.cloneDeep(this.formDataBack)
      this.formData.parentId = currentNode.id
      if (currentNode.parentId === 0) {
        this.formData.parentPath = currentNode.dispname
      } else {
        this.formData.parentPath = currentNode.parentPath + ' > ' + currentNode.dispname
      }
    },

    //  取消选择
    cancelSel () {
      this.selectedKeys = []
      this.selectedMenu = ''
      this.clear()
    },
    reset () {
      if (this.actions != 'addTop') {
        const data = {
          id: this.formData.id,
          parentId: this.formData.parentId,
          parentPath: this.formData.parentPath
        }
        console.log(data, 'data')
        this.formData = _.cloneDeep(this.formDataBack)
        this.formData.id = data.id
        this.formData.parentId = data.parentId
        this.formData.parentPath = data.parentPath
      }
      this.cancelSel()
    },
    // 清空列表
    clear () {
      this.form.resetFields()
      this.formData = _.cloneDeep(this.formDataBack)
    },

    // 删除数据
    remove () {
      if (!this.selectedKeys.length) {
        return this.$message.warning('您还未选择要删除的数据')
      }
      if (this.selectedData.node.$children.length) {
        return this.$message.warning('请先删除子节点')
      }
      const _this = this
      console.log(_this.formData.id, '_this.formData.id')
      this.$confirm({
        title: '警告',
        content: `确定要删除您选择的 ${_this.formData.dispname} 的数据吗?`,
        okText: '确定',
        cancelText: '取消',
        onOk () {
          delRegisterNode({
            id: _this.formData.id
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success('删除成功')
              _this.cancelSel()
              _this.initTree()
            }
          }).catch(() => {
            _this.$message.success('删除失败, 请稍后重试')
          })
        }
      })
    },

    // 保存提交
    handleSubmit () {
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values.formData, ' formData.type222222222')
          let params = {}
          if (this.actions === 'addTop') {
            params = Object.assign({}, values.formData)
          } else {
            params = Object.assign(_this.formData, values.formData)
          }
          saveRegister(params).then(res => {
            if (res.status + '' === '200') {
              _this.initTree()
              _this.cancelSel()
              this.$message.success(res.message ? res.message : '保存成功')
            } else {
              // this.$message.error(res.message ? res.message : '保存失败')
            }
          })
        }
      })
    }

  },
  mounted () {
    // this.initTree()
  },
  beforeCreate () {
    this.form = this.$form.createForm(this, { name: 'register' })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.initPage()
    })
  },
  watch: {

  }
}
</script>

<style>
  .menu-box::-webkit-scrollbar{
    width: 6px;
    height: 6px ;
  }

  .menu-box::-webkit-scrollbar-thumb{
    width: 6px;
    height: 6px ;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 2px #d1d1d1;
    background: #e4e4e4;
  }

  .textCount{
    border: 1px solid #91d5ff;
    background-color: #e6f7ff;
    border-radius: 5px;
    padding: 5px 10px 5px 20px;
    margin: 10px 0;
    color: rgba(0, 0, 0, 0.85);
  }
  .imgSize{
    color: #2d8cf0;
    margin-left: 10px;
    font-size: 14px;
  }

</style>
