<template>
  <div>
    <el-form
            ref="form"
            :model="form"
            class="form-input">
      <el-form-item
              :name="$attrs.name"
              :rules="$attrs.props.rules"
              :class="{isRequired: !isRequired}"
              prop="newValue"
              class="item"
      >
        <div class="rule-list">
            <div class="list-box">
              <el-tree
                ref="tree"
                node-key="id"
                :data.sync="form.newValue.data"
                :props.sync="$attrs.props"
                :default-expand-all="true"
                @check="check"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
              <span> {{ data.name }} </span>
              <span class="btns">
                  <el-button
                          v-if="data.add"
                          type="text"
                          size="mini"
                          @click.native.stop="() => append(data)">
                    添加
                  </el-button>
                  <el-button
                          v-if="data.edit"
                          type="text"
                          size="mini"
                          @click.native.stop="() => remove(node, data)">
                    删除
                  </el-button>
                  <el-button
                          v-if="data.delete"
                          type="text"
                          size="mini"
                          @click.native.stop="handleEdit(node, data)">
                    编辑
                  </el-button>
                </span>
              </span>
                </el-tree>
                </div>
                <EditItem
                    v-if="isEditShow"
                    :visible.sync="isEditShow"
                    :value.sync="editItem"
                    :defaultValue="editItem"
                    @success="onEditItem"
                />
              </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import EditItem from './components/editItem'
  import { fields } from './components/editItem/fields'
  export default {
    name: 'ImNavManage2',
    components: {
      EditItem
    },
    props: {
      value: [String, Number, Array, Object]
    },
    created () {
      this.$nextTick(() => {
        // this.$utils.addIdByArr({ data: this.form.newValue.data })
      })
    },
    data () {
      return {
        form: {
          newValue: []
        },
        oldForm: null,
        isEditShow: false,
        editItem: '',
        editNode: fields // 正在编辑的节点
      }
    },
    computed: {
      isRequired () {
        return this.$attrs.props.rules && this.$attrs.props.rules.required
      },
      getNewForm () {
        const form = this.$_.cloneDeepWith(this.form.newValue)
        try {
          this.$utils.deleteIdByArr({ data: form.data })
        } catch (e) {
          console.log('去除id失败==>', e)
        }
        return form
      }
    },
    watch: {
      value: {
        handler (vl) {
          if (vl && typeof vl === 'string') {
            this.form.newValue = JSON.parse(vl)
          } else {
            this.form.newValue = vl
          }
        },
        deep: true,
        immediate: true
      },
      'form.newValue': {
        handler (vl) {
          this.$emit('onInput', vl)
          if (vl === '' && this.oldForm) {
            this.form = JSON.parse(this.oldForm)
          }
          this.isClearVilidate()
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      async onEditItem (item) {
        console.log('编辑内容1==>', item)

        const data = this.editItem
        const node = this.editNode
        const parent = node.parent
        const leafs = parent.data.leaf || parent.data
        const index = leafs.findIndex(d => d.unique === data.unique)
        console.log('编辑内容2==>', node, data, leafs[index], item.name)
        leafs[index].name = item.name
      },
      handleEdit (node, data) {
        console.log('handleEdit==>', node, data)
        this.isEditShow = true
        this.editItem = data
        this.editNode = node
      },
      check () {
        // 获取选中节点数组
        // const arr = this.$refs.tree.getCheckedNodes()
        // this.form.newValue = arr

        this.isClearVilidate()
      },
      append (data) {
        console.log('新增==>', data)
        const unique = Date.parse(new Date()) + Math.random()
        let add = true
        // 如果大于三级，不允许添加
        if(data.id && data.id.split('-') && data.id.split('-').length>=2){
            add = false
        }
        let id = ''
        if (!data.leaf || (data.leaf && data.leaf.length === 0)) {
          id = data.id + '-1'
            // 如果当前父级导航为 '导航分类'
            // 索引从0开始
            if(data.name === '导航分类'){
                id = '0'
                if(data.leaf){
                    id = data.leaf && `${data.leaf.length}`
                }
            }
          this.$set(data, 'leaf', [])
          data.leaf.push({ unique, id, name: '新增导航', add, edit: true, delete: true })
          return false
        }
        const preId = data.leaf[data.leaf.length - 1].id
        const lastNum = data.leaf.length+1
        id = preId.slice(0, preId.length - 1 ) + lastNum

        data.leaf.push({ unique, id, name: '新增', add, edit: true, delete: true })
      },
      remove (node, data) {
        console.log('删除节点==>', node, data)
        const parent = node.parent
        const leafs = parent.data.leaf || parent.data
        const index = leafs.findIndex(d => d.id === data.id)
        leafs.splice(index, 1)
      },
      // 时时校验-校验通过清除提示
      isClearVilidate () {
        if (this.isVilidate()) {
          const fn = setTimeout(() => {
            this.formClearValidate()
            clearTimeout(fn)
          }, 10)
        }
      },
      // 是否校验通过
      isVilidate () {
        // 所有路径都必须有数据
        let state = true
        if (this.isRequired) {
          if (typeof this.form.newValue === 'string' || (this.form.newValue.data && this.form.newValue.data.length === 0)) {
            state = false
          } else {
            this.form.newValue.forEach((v) => {
              if (!v.name) state = false
            })
          }
        }
        return state
      },
      validate () {
        let state = false
        // 判断字段是否数据正确，如果正确的话校验通过，否则校验不过
        this.oldForm = JSON.stringify(this.form)
        if (this.isVilidate()) {
          this.form.newValue = JSON.stringify(this.form.newValue)
        } else {
          this.form.newValue = ''
        }
        this.$refs.form && this.$refs.form.validate((res) => {
          state = res
        })
        return state
      },
      // 校验表单
      formValidate () {
        this.$refs.form && this.$refs.form.validate()
      },
      // 清除表单
      formClearValidate () {
        this.$refs.form && this.$refs.form.clearValidate()
      }
    }
  }
</script>

<style scoped>
  .warn{
    color: #ff2c2c;
    font-size: 12px;
  }
  .input-box .del >>> span{
    position: relative;
    top: -1px;
  }
  .box{
    width: 500px;
    color: #606266;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .content-box .box:last-of-type .content{
    margin-bottom: 0px;
  }
  .form-input{
    display: flex;
    flex-direction: row;
  }
  .item{
    display: flex;
    flex-direction: row;
    flex: 1;
    margin-bottom: 20px;
  }
  .row-content{
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  .row{
    display: flex;
    flex-direction: row;
    margin-bottom: 10px;
  }
  .row .name{
    margin-right: 10px;
  }
  .row .select-box{
    display: flex;
    flex-direction: column;
  }
  .row .select-box >>> .div{
    width: 220px;
    height: 40px;
  }

  .item >>> .iconfont{
    font-size: 22px;
  }
  .rule-list{
    display: flex;
    flex-direction: column;
    flex: 1px;
    padding: 10px 0px;
  }
  .form-input{
    display: flex;
    flex-direction: row;
  }
  .item{
    display: flex;
    flex-direction: row;
    flex: 1;
    margin-bottom: 20px;
  }
  .item >>> .el-form-item__content{
    /*width: 60%;*/
  }
  .isRequired{
    padding-left: 10px;
  }
  .btns{margin-left: 30px;}
  .list-box {
      border: 1px solid #f1f1f1;
      border-radius: 6px;
      padding: 12px 21px 12px 10px;
  }
</style>
