<template>
  <div>
    <el-card class="no-bottom">
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        inline
      >
        <el-form-item
          label="控件名称:"
          prop="name"
        >
          <el-input v-model="searchForm.name" />
        </el-form-item>
        <el-form-item
          label="分类:"
          prop="type"
        >
          <el-select v-model="searchForm.type" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option
              v-for="(option, index) in allOptions"
              :key="index"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="margin-top-20">
      <div class="buttons-group" style="margin-bottom: 20px">
        <el-button v-permission="'MenuMgr_add'" type="primary" icon="el-icon-plus" @click="addRow">增加控件</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        row-key="rowKey"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column
          type="index"
          label="序号"
          width="50px"
          align="center"
        />
        <el-table-column
          prop="name"
          label="控件名称"
          min-width="160px"
        />
        <el-table-column
          label="类型"
          align="center"
          width="90px"
        >
          <template slot-scope="props">
            <el-tag size="mini" :type="tagType(props.row.type)">{{ tagName(props.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNum"
          label="排序"
          width="90px"
        />
        <el-table-column
          prop="menuCode"
          label="MenuCode"
          min-width="130px"
        />
        <el-table-column
          prop="perms"
          label="API"
          min-width="160px"
          show-overflow-tooltip
        />
        <el-table-column
          prop="url"
          label="前端路由"
          min-width="160px"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          width="140px"
          align="center"
        >
          <template slot-scope="props">
            <el-button
              v-permission="'MenuMgr_update'"
              type="text"
              :disabled="props.row.type === -1"
              @click="updateMenu(props.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              v-permission="'SysMgr_delete'"
              title="确定要删除此条记录吗？"
              :disabled="props.row.type === -1"
              @onConfirm="deleteMenu(props.row.id)"
            >
              <el-button
                slot="reference"
                type="text"
                :disabled="props.row.type === -1"
              >
                删除
              </el-button>
            </el-popconfirm>
            <el-button v-if="false" v-permission="'MenuMgr_info'" type="text">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        :title="add ? '增加权限' : '编辑权限'"
        :visible.sync="dialogVisible"
        width="700px"
      >
        <el-form
          ref="menuForm"
          :model="menuForm"
          label-width="90px"
          :rules="menuRules"
        >
          <el-form-item
            label="控件名称:"
            prop="name"
          >
            <el-input v-model="menuForm.name" />
          </el-form-item>
          <el-form-item
            label="类型:"
            prop="type"
          >
            <el-select v-model="menuForm.type" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="父级:"
            prop="parentId"
          >
            <el-cascader
              v-model="menuForm.parentId"
              :options="menuOptions"
              :props="{ value: 'rowKey', label: 'name', checkStrictly: true, emitPath: false }"
              clearable
              style="width: 100%"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item
            label="MenuCode:"
            prop="perms"
          >
            <div style="display: flex">
              <el-input v-model="menuForm.menuCode" />
              <el-tooltip class="item" effect="dark" content="用做前端权限管理" placement="top-end">
                <div style="padding-left: 12px;padding-right: 12px">
                  <i class="el-icon-info" />
                </div>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item
            label="API:"
            prop="perms"
          >
            <div style="display: flex">
              <el-input v-model="menuForm.perms" :disabled="menuForm.type === 0" />
              <el-tooltip class="item" effect="dark" content="所调用的api地址" placement="top-end">
                <div style="padding-left: 12px;padding-right: 12px">
                  <i class="el-icon-info" />
                </div>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item
            label="前端路由:"
            prop="url"
          >
            <div style="display: flex">
              <el-input v-model="menuForm.url" :disabled="menuForm.type === 2" />
              <el-tooltip class="item" effect="dark" content="页面对应的前端路由地址" placement="top-end">
                <div style="padding-left: 12px;padding-right: 12px">
                  <i class="el-icon-info" />
                </div>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item
            label="排序:"
            prop="orderNum"
          >
            <el-input-number
              v-model="menuForm.orderNum"
              :min="1"
              :max="100"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveMenu">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import { getMenuList, deleteMenu, addMenu, updateMenu } from '@/api/system-management/menu-management'
import _ from 'lodash'

export default {
  name: 'AccessManagement',
  data() {
    return {
      searchForm: {
        name: null,
        type: null
      },
      pageForm: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      menuRules: {
        parentId: [
          { required: true, message: '请选择父级', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入控件名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ]
      },
      tableData: [],
      dialogVisible: false,
      add: true,
      menuForm: {
        parentId: null,
        name: null,
        url: null,
        type: null,
        orderNum: 1,
        perms: null,
        menuCode: null
      },
      options: [
        {
          label: '菜单',
          value: 0
        },
        {
          label: '页面',
          value: 1
        },
        {
          label: '按键',
          value: 2
        }
      ],
      allOptions: [
        {
          label: '系统',
          value: -1
        },
        {
          label: '菜单',
          value: 0
        },
        {
          label: '页面',
          value: 1
        },
        {
          label: '按键',
          value: 2
        }
      ],
      menuOptions: [],
      currentMenu: null
    }
  },
  watch: {
    'menuForm.type'(val) {
      // this.menuForm.parentId = null
      this.menuOptions = this.filterButton(this.tableData, val)
      if (val === 2) {
        this.menuForm.url = null
      }
      if (val === 0) {
        this.menuForm.perms = null
      }
    }
  },
  created() {
    this.getMenuList()
  },
  methods: {
    resetForm() {
      this.$refs.searchForm.resetFields()
    },
    search() {
      // 获取完整数据
      getMenuList()
        .then(res => {
          const { data } = res
          this.tableData = data
          // 过滤关键字
          let filter = (this.searchForm.name === null) ? this.tableData : this.filter(this.tableData)
          // 返回一维数组
          const flatten = (this.searchForm.type === null) ? filter : this.flatten(filter)
          // 过滤分类
          filter = (this.searchForm.type === null) ? flatten : _.filter(flatten, v => v.type === this.searchForm.type)
          this.tableData = (this.searchForm.name === null) ? filter : this.filter(filter)
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    flatten(array) {
      const arr = []
      array.forEach(v => {
        arr.push(v)
        if (v.children && v.type !== this.searchForm.type) {
          arr.push(...this.flatten(v.children))
        }
      })
      return arr
    },
    filter(array) {
      const arr = []
      array.forEach(v => {
        if (v.name.indexOf(this.searchForm.name) >= 0) {
          arr.push(v)
        } else if (v.children) {
          arr.push(...this.filter(v.children))
        }
      })
      return arr
    },
    filterButton(array, val) {
      const arr = []
      array.forEach(v => {
        const { rowKey, name, children, type } = v
        if (children && type < val - 1) {
          arr.push({
            rowKey,
            name,
            type,
            children: this.filterButton(children, val)
          })
        } else {
          arr.push({
            rowKey,
            name,
            type
          })
        }
      })
      return arr
    },
    getMenuList() {
      getMenuList()
        .then(res => {
          const { data } = res
          this.tableData = data
          this.menuOptions = this.filterButton(this.tableData, 2)
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    handleChange() {},
    addRow() {
      this.add = true
      this.dialogVisible = true
      this.menuForm = {
        parentId: null,
        name: null,
        url: null,
        type: null,
        orderNum: 1,
        perms: null,
        menuCode: null
      }
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val
    },
    updateMenu(row) {
      this.currentMenu = row
      const { name, url, type, orderNum, perms, parentRowKey, menuCode } = row
      this.menuForm = {
        name,
        url,
        type,
        orderNum,
        perms,
        menuCode,
        parentId: parentRowKey
      }
      this.menuForm.parentId = parentRowKey
      this.add = false
      this.dialogVisible = true
    },
    saveMenu() {
      this.$refs.menuForm.validate()
        .then(_ => {
          const { name, url, type, orderNum, perms, parentId, menuCode } = this.menuForm
          const params = {
            name,
            url,
            type,
            orderNum,
            perms,
            menuCode: menuCode.trim(),
            parentRowKey: parentId
          }
          if (this.add) {
            addMenu(params)
              .then(res => this.$message.success('操作成功'))
              .then(_ => {
                this.getMenuList()
                this.dialogVisible = false
              })
              .catch(err => {
                this.$message.error('操作失败')
                console.error(err.message)
              })
          } else {
            params.id = this.currentMenu.id
            updateMenu(params)
              .then(res => this.$message.success('操作成功'))
              .then(_ => {
                this.getMenuList()
                this.dialogVisible = false
              })
              .catch(err => {
                this.$message.error('操作失败')
                console.error(err.message)
              })
          }
        })
        .catch(_ => {})
    },
    deleteMenu(id) {
      deleteMenu({ id: id })
        .then(res => {
          this.$message.success('操作成功')
          this.getMenuList()
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    tagType(data) {
      const typeName = {
        '-1': 'danger',
        '0': '',
        '1': 'success',
        '2': 'warning'
      }
      return typeName[data]
    },
    tagName(data) {
      const tagName = {
        '-1': '系统',
        '0': '菜单',
        '1': '页面',
        '2': '按钮'
      }
      return tagName[data]
    }
  }
}
</script>

<style scoped>

</style>
