<template>
  <div id="DgMenu" class="dg-menu">
    <h4 v-if="!collapse" id="test" :style="titleStyle">{{ prodtitle }}</h4>
    <!-- <el-menu @select="handleSelect" @open="handleOpenClose" @close="handleOpenClose" :default-active="activeIndex" v-rightMenu="menuData"> -->
    <el-menu
      :background-color="backgroundColor"
      :text-color="textColor"
      :default-active="activeIndex"
      :collapse="collapse"
      @select="handleSelect"
      @open="handleOpenClose"
      @close="handleOpenClose"
    >
      <template v-for="list in menuList">
        <dg-sub-menu
          :key="list[keyField]"
          :list="list"
          :key-field="keyField"
          :pkey-field="pkeyField"
          :title-field="titleField"
          :route-field="routeField"
        ></dg-sub-menu>
      </template>
    </el-menu>
  </div>
</template>

<script>
import DgSubMenu from './DgSubMenu.vue'

export default {
  name: 'DgMenu',
  components: {
    DgSubMenu,
  },
  props: {
    menuListData: {
      type: Array,
      default: () => [],
    },
    resRootData: {
      type: Array,
      default: () => [],
    },
    apiCode: {
      type: String,
      default: () => '',
    },
    collapse: {
      type: Boolean,
      default: () => false,
    },
    backgroundColor: {
      type: String,
      default: () => '',
    },
    textColor: {
      type: String,
      default: () => '',
    },
    root: {
      type: String,
      default: () => '',
    },
    rootVal: {
      type: Boolean,
      default: () => false,
    }, // 是否显示根节点
    titleStyle: {
      type: String,
      default: () => '',
    },
    keyField: {
      type: String,
      default: () => '',
    },
    pkeyField: {
      type: String,
      default: () => '',
    },
    titleField: {
      type: String,
      default: () => '',
    },
    routeField: {
      type: String,
      default: () => '',
    },
    queryTerms: {
      type: String,
      default: () => '',
    },
  },
  data() {
    return {
      treeNode: null,
      // activeIndex: this.$store.state.route.activeIndex,
      activeIndex: '',
      prodtitle: '',
      menuList: [],
      initialData: null,
      // 配置右键菜单
      menuData: {
        // 菜单box的样式   Menu box style
        boxStyle:
          'width:120px;background:#fff;border: 1px solid rgba(0, 0, 0, 0.1);z-index:999;box-shadow: 4px 5px 10px rgba(0, 0, 0, 0.2);background-clip: padding-box; padding: 5px;',
        // 菜单选项的样式 Style of menu options
        optionStyle: 'color:#000;line-height:30px;font-size: 12px;cursor: pointer;',
        menus: [
          {
            content: '创建',
            callback: 'createNode',
          },
          {
            content: '编辑',
            callback: 'editNode',
          },
          {
            content: '删除',
            callback: 'deletNode',
          },
        ],
      },
    }
  },
  watch: {
    menuListData() {
      this.getMenuListData()
    },
    queryTerms() {
      if (this.apiCode != '') {
        this.getData()
      }
    },
  },
  created() {
    // this.getData()
    if (this.apiCode != '') {
      this.getData()
    } else if (this.menuListData.length > 0) {
      this.getMenuListData()
    } else if (this.resRootData) {
      let newChildren = this.rootVal
        ? this.resRootData.filter((list) => list[this.keyField] === this.root)
        : this.resRootData.filter((list) => list[this.pkeyField] === this.root)
      this.menuList = this.parseMenuList(this.resRootData, newChildren)
    }
  },
  methods: {
    // 获取数据
    async getData() {
      let params = `command=init&limit=-1&start=0&root=${this.root}&para_order=order_num`
      if (this.queryTerms) params += `&${this.queryTerms}`
      let res = await this.$api.DgJsonStore({
        apiCode: this.apiCode,
        params: params,
      })
      this.initialData = res.root
      if (res.root.filter((list) => list[this.keyField] === this.root).length > 0) {
        this.prodtitle = res.root.filter((list) => list[this.keyField] === this.root)[0][this.titleField]
      }
      let newChildren = this.rootVal
        ? res.root.filter((list) => list[this.keyField] === this.root)
        : res.root.filter((list) => list[this.pkeyField] === this.root)
      this.menuList = this.parseMenuList(res.root, newChildren)
    },
    getMenuListData() {
      var res = this.menuListData
      this.initialData = res
      // console.log("menuListData: ",this.menuListData);

      if (res.filter((list) => list[this.keyField] === this.root).length > 0) {
        this.prodtitle = res.filter((list) => list[this.keyField] === this.root)[0][this.titleField]
      }
      let newChildren = this.rootVal
        ? res.filter((list) => list[this.keyField] === this.root)
        : res.filter((list) => list[this.pkeyField] === this.root)
      this.menuList = this.parseMenuList(res, newChildren)
    },
    // 根据树节点id获取该节点数据
    getTreeDataNodeById(treeNodeId) {
      if (this.initialData.root) {
        return this.initialData.root.filter((list) => list[this.keyField] === treeNodeId)[0]
      } else {
        return this.initialData.filter((list) => list[this.keyField] === treeNodeId)[0]
      }
    },
    // 选择节点触发事件
    handleSelect(treeNodeId) {
      // this.$store.dispatch('InitActiveIndex', treeNodeId)
      this.treeNode = this.getTreeDataNodeById(treeNodeId)
      let select = this.$emit('select', this.treeNode)
      if (this.treeNode[this.routeField] && !select._events.select) {
        this.$router.push({
          name: this.treeNode[this.routeField],
        })
      }
    },
    // 打开节点事件
    handleOpenClose(treeNodeId) {
      this.treeNode = this.getTreeDataNodeById(treeNodeId)
      let select = this.$emit('select', this.treeNode)
    },
    // 递归函数将取到的数据转变为带children的数据结构
    parseMenuList(menuList, children) {
      let newChildren = []
      return children.map((list) => {
        newChildren = menuList.filter((child) => child[this.pkeyField] === list[this.keyField])
        if (newChildren && newChildren.length > 0) {
          list.children = this.parseMenuList(menuList, newChildren)
        }
        return list
      })
    },
    // 右键菜单中的创建事件
    createNode() {
      this.$prompt('请输入节点名称', '创建', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: '邮箱格式不正确'
      })
        .then(({ value }) => {
          console.log(this.treeNode, value)
          // this.$message({
          // 	type: 'success',
          // 	message: '创建成功'
          // })
        })
        .catch(() => {
          this.$message({ type: 'info', message: '已取消创建' })
        })
    },
    // 右键菜单中的编辑事件
    editNode() {
      this.$prompt('请输入节点名称', '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: this.treeNode[this.titleField],
      })
        .then(({ value }) => {
          console.log(this.treeNode, value)
          this.$message({ type: 'success', message: '编辑成功' })
        })
        .catch(() => {
          this.$message({ type: 'info', message: '已取消编辑' })
        })
    },
    // 右键菜单中的删除事件
    deletNode() {
      this.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      })
        .then(() => {
          console.log(this.treeNode)
          this.$message({ type: 'success', message: '删除成功!' })
        })
        .catch(() => {
          this.$message({ type: 'info', message: '已取消删除' })
        })
    },
  },
}
</script>
