<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="keyword" placeholder="请输入关键字" class="filter-item"/>
      <el-button type="primary" class="filter-item" icon="el-icon-search" @click="btn_search">搜索</el-button>
      <el-button v-permission="'HY_add'" type="primary" class="filter-item" icon="el-icon-plus" @click="btn_add">添加</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="menuData"
      :eval-func="func"
      :eval-args="args"
      :expand-all="false"
      row-key='id'
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      border
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)">
      <el-table-column label="菜单名称" align="center" width="200">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="菜单链接" align="center">
        <template slot-scope="scope">
          {{ scope.row.path }}
        </template>
      </el-table-column>
      <el-table-column label="菜单代码" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column :formatter="formatterTarget" prop="target" label="菜单类型" align="center" width="100"/>
      <el-table-column label="是否启用" align="center" width="100">
        <template slot-scope="scope">
          <i v-if="scope.row.stateFlag === 1" class="el-icon-success target_color1"/>
          <i v-else-if="scope.row.stateFlag === 0" class="el-icon-warning target_color2"/>
        </template>
      </el-table-column>
      <el-table-column label="介绍" align="center">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center" class-name="oparate_btn" fixed="right">
        <template slot-scope="scope">
          <el-button v-permission="'HY_edit'" size="mini" plain type="primary" @click="btn_edit(scope.row)">编辑</el-button>
          <el-button v-permission="'HY_modulebutton'" size="mini" plain type="primary" @click="btn_button(scope.row)">按钮管理</el-button>
          <el-button v-permission="'HY_delete'" size="mini" plain type="danger" @click="btn_delete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getMenuLists, deleteMenu } from '@/api/systemSetup/roleSetting/menuSetup'
import treeTable from '@/components/TreeTable'
import treeToArray from './customEval'
import addOrEditMenu from './components/addOrEditMenu'
import menuBtn from './menuBtn'
export default {
  name: 'MenuSetup',
  components: {
    treeTable
  },
  data() {
    return {
      loading: true,
      func: treeToArray,
      expandAll: true,
      args: [null, null],
      keyword: '',
      menuData: [],
      parentids: []
    }
  },
  created() {
    this.getDatas()
    document.onkeyup = (e) => {
      if (e.keyCode === 13) {
        this.getDatas()
      }
    }
  },
  methods: {
    getDatas() {
      const keyword = this.keyword.replace(/\s+/g, '')
      getMenuLists(keyword).then(response => {
        this.loading = false
        this.menuData = this.$options.methods.buildTree(response.rows)
      })
    },
    formatterTarget(row, column) {
      let targetTxt = ''
      switch (row.target) {
        case 'expand':
          targetTxt = '无页面'
          break
        case 'iframe':
          targetTxt = '框架页'
          break
        case 'open':
          targetTxt = '弹出页'
          break
        case 'blank':
          targetTxt = '新窗口'
          break
        default:
          break
      }
      return targetTxt
    },
    btn_search() {
      this.getDatas()
    },
    btn_add() {
      this.$layer.iframe({
        content: {
          content: addOrEditMenu, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': '' }// props//该方法会自动添加一个key为layerid的值， 该值为创建层的id， 可以直接使用
        },
        area: ['80%', '90%'],
        shadeClose: false,
        title: '添加菜单'
      })
    },
    btn_edit(row) {
      console.log("row",row)
      this.parentids = []
      if (row.parent) {
        this.getParents(row.parent)
      } else {
        this.parentids.push('000000000000000000000000')
      }
      this.$layer.iframe({
        content: {
          content: addOrEditMenu, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': row.id, 'parentidArr': this.parentids }// props
        },
        area: ['80%', '90%'],
        title: '编辑菜单'
      })
    },
    btn_button(row) {
      this.$layer.iframe({
        content: {
          content: menuBtn, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': row.id }// props
        },
        area: ['80%', '90%'],
        title: `${row.name} 的按钮管理`
      })
    },
    btn_delete(editId) {
      this.$confirm('此操作将永久删除当前菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMenu(editId).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.getDatas()
            this.$message.success('删除成功!')
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    /**
			 * 将一维的扁平数组转换为多层级对象
			 * @param  {[type]} list 一维数组，数组中每一个元素需包含id和parent_id两个属性
			 * @return {[type]} tree 多层级树状结构
			 */
    buildTree(list) {
      const temp = {}
      const tree = {}
      for (const j in list) {
        temp[list[j].F_Id] = list[j]
      }
      for (const i in temp) {
        // if (temp[i].F_ParentId !== '000000000000000000000000') {
        if (temp[i].F_ParentId !== 0) {
          if (!temp[temp[i].F_ParentId].childnodes) {
            temp[temp[i].F_ParentId].childnodes = {}
          }
          temp[temp[i].F_ParentId].childnodes[temp[i].F_Id] = temp[i]
        } else {
          tree[temp[i].F_Id] = temp[i]
        }
      }
      return this.filterMenuDatas(tree)
    },
    // 处理数据格式
    filterMenuDatas(menudatas) {
      const accessedRouters = []
      let j = -1
      for (const i in menudatas) {
        j++
        if (menudatas[i].F_ParentId === '000000000000000000000000') {
          accessedRouters.push({
            id: menudatas[i].F_Id,
            path: menudatas[i].F_OptUrl,
            code: menudatas[i].F_MenuCode,
            name: menudatas[i].F_MenuName,
            target: menudatas[i].F_Target, // 菜单类型
            stateFlag: menudatas[i].F_State, // 是否启用
            remark: menudatas[i].F_Remark, // 介绍
            children: []
          })
        } else {
          accessedRouters.push({
            id: menudatas[i].F_Id,
            path: menudatas[i].F_OptUrl,
            code: menudatas[i].F_MenuCode,
            name: menudatas[i].F_MenuName,
            target: menudatas[i].F_Target,
            stateFlag: menudatas[i].F_State,
            remark: menudatas[i].F_Remark
          })
        }
        if (menudatas[i].childnodes) {
          accessedRouters[j].children = this.filterMenuDatas(menudatas[i].childnodes)
        }
      }
      return accessedRouters
    },
    // 获取父级id
    getParents(poptions) {
      this.parentids.unshift(poptions.id)
      console.log("poptions",poptions);
      if (poptions.parent) {
        this.getParents(poptions.parent)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.target_color1 {
		color: #13ce66;
		font-size: 16px;
	}

	.target_color2 {
		color: #ff4949;
		font-size: 16px;
	}
</style>
