<template>
  <div class="app-container my_menu">
    <el-form :inline="true">
      <el-form-item label="菜单名称">
        <el-input :maxLength="$inputMax"
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.visible" placeholder="菜单状态" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button
        type="info"
        plain
        icon="el-icon-sort"
        size="mini"
        @click="toggleExpandAll"
      >展开/折叠</el-button>
    </div>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      :default-expand-all="isExpandAll"
      row-key="MenuId"
      :tree-props="{children: 'Children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="MenuName" label="菜单名称" :show-overflow-tooltip="true" min-width="130px" />
      <el-table-column prop="icon" label="图标" align="center" min-width="100px">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.MenuIcon" />
        </template>
      </el-table-column>
      <el-table-column prop="ShowOrder" label="排序" min-width="60px" />
      <el-table-column prop="Path" label="路由" min-width="120px" show-overflow-tooltip />
      <el-table-column prop="ApiPath" label="接口名" min-width="180px" show-overflow-tooltip />
      <el-table-column prop="Component" label="组件路径" min-width="180px" :show-overflow-tooltip="true" />
<!--      <el-table-column prop="Redirect" label="重定向" min-width="180px" :show-overflow-tooltip="true" />-->
      <el-table-column prop="PermissionStr" label="权限标识" min-width="130px" :show-overflow-tooltip="true" />
      <el-table-column prop="PermissionStr" label="类型" min-width="80px" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.MenuType === 'M' ? '目录' : scope.row.MenuType === 'C' ? '菜单' : '权限点' }}
        </template>
      </el-table-column>
      <el-table-column label="显影" align="center" prop="CreateTime" min-width="80">
        <template slot-scope="scope">
          <el-tag v-if="!scope.row.IsDisplay" size="medium">显示</el-tag>
          <el-tag v-else size="warning">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启用" align="center" prop="CreateTime" min-width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsEnable" size="success">启用</el-tag>
          <el-tag v-else size="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:menu:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:menu:add']"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            v-hasPermi="['system:menu:delete']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                v-model="form.ParentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.MenuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">权限点</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.MenuType != 'F'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input :maxLength="$inputMax" slot="reference" v-model="form.MenuIcon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="form.MenuIcon"
                    slot="prefix"
                    :icon-class="form.MenuIcon"
                    class="el-input__icon"
                    style="height: 28px;width: 16px;margin-left: 6px;"
                  />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="MenuName">
              <el-input :maxLength="$inputMax" v-model="form.MenuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="ShowOrder">
              <el-input-number v-model="form.ShowOrder" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                是否外链
              </span>
              <el-radio-group v-model="form.IsExternalLink">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'" prop="path">
              <span slot="label">
                <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                路由地址
              </span>
              <el-input :maxLength="$inputMax" v-model="form.Path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType == 'C'" :span="12">
            <el-form-item prop="component">
              <span slot="label">
                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                组件路径
              </span>
              <el-input :maxLength="$inputMax" v-model="form.Component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType != 'F'" :span="12">
            <el-form-item prop="Redirect Path">
              <span slot="label">
                <el-tooltip content="重定向路由，如：`/system/user/index`" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                重定向
              </span>
              <el-input :maxLength="$inputMax" v-model="form.Redirect" placeholder="请输入重定向路由" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'M'">
              <el-input :maxLength="$inputMax" v-model="form.PermissionStr" placeholder="请输入权限标识" maxlength="100" />
              <span slot="label">
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                权限字符
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'M'">
              <el-input :maxLength="$inputMax" v-model="form.ApiPath" placeholder="接口名" />
              <span slot="label">
                <el-tooltip content="接口名" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                接口名
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType == 'C'">
              <span slot="label">
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                是否缓存
              </span>
              <el-radio-group v-model="form.IsCache">
                <el-radio :label="true">缓存</el-radio>
                <el-radio :label="false">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                是否隐藏
              </span>
              <el-switch
                v-model="form.IsDisplay"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <el-tooltip content="选择隐藏则不会在trials模块的TAB中显示，但仍然可以访问" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                Tab显隐
              </span>
              <el-switch
                v-model="form.IsInTabDisplay"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.MenuType != 'F'">
              <span slot="label">
                <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                菜单状态
              </span>
              <el-switch
                v-model="form.IsEnable"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType != 'F'" :span="24">
            <el-form-item label="LangMark">
              <el-input :maxLength="$inputMax" v-model="form.LanguageMark" placeholder="LangMark" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.MenuType != 'F'" :span="24">
            <el-form-item label="mate">
              <el-input :maxLength="$inputMax" v-model="form.Meta" type="textarea" placeholder="{ title: 'Setting', breadcrumb: false, role: [8, 1, 2, 3, 10] }" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuList, addOrUpdateMenu, deleteMenu } from '@/api/system/menu'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'

export default {
  name: 'Menu',
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 菜单状态数据字典
      visibleOptions: [],
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined
      },
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        MenuName: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        ShowOrder: [
          { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    console.log(this.hasPermi(['trials:trials-list:new', 'trials:trials-list:export1'], '&&'))
    this.getList()
    // this.getDicts("sys_show_hide").then(response => {
    //   this.visibleOptions = response.data;
    // });
  },
  methods: {
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    normalizer(node) {
      if (node.Children && !node.Children.length) {
        delete node.Children
      }
      return {
        id: node.MenuId,
        label: node.MenuName,
        children: node.Children
      }
    },
    toTree(arr, ParentId) {
      function loop(ParentId) {
        const res = []
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          item.hasChildren = false
          if (item.ParentId !== ParentId) {
            continue
          }
          item.Children = loop(item.MenuId)
          res.push(item)
        }
        return res
      }
      return loop(ParentId)
    },
    // 选择图标
    selected(name) {
      this.form.MenuIcon = name
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true
      getMenuList(this.queryParams).then(res => {
        this.menuList = this.toTree(res.Result, '00000000-0000-0000-0000-000000000000')
        const menu = { MenuId: '00000000-0000-0000-0000-000000000000', MenuName: '主类目', Children: [] }
        menu.Children = this.menuList
        this.menuOptions = Object.assign([], [menu])
        this.loading = false
      }).catch(function() {})
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      this.loading = true
      getMenuList({}).then(res => {
        const menu = { MenuId: '00000000-0000-0000-0000-000000000000', MenuName: '主类目', Children: [] }
        menu.Children = this.toTree(res.Result, '00000000-0000-0000-0000-000000000000')
        this.menuOptions = Object.assign([], [menu])
        this.loading = false
      }).catch(function() {})
    },
    // 菜单显示状态字典翻译
    visibleFormat(row, column) {
      if (row.MenuType === 'F') {
        return ''
      }
      return this.selectDictLabel(this.visibleOptions, row.visible)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        MenuId: null,
        ParentId: null,
        MenuType: 'M',
        MenuIcon: '',
        MenuName: '',
        Path: '',
        Component: '',
        ShowOrder: null,
        IsEnable: true,
        IsCache: false,
        IsDisplay: false,
        IsInTabDisplay: false,
        IsExternalLink: false,
        PermissionStr: '',
        Note: '',
        CreateTime: '',
        LanguageMark: null,
        Apipath: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.ParentId = row.MenuId
      }
      this.open = true
      this.title = '添加菜单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      this.form = Object.assign({}, row)
      this.open = true
      this.title = '修改菜单'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          addOrUpdateMenu(this.form).then(response => {
            this.$message.success('保存成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.MenuName + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteMenu(row.MenuId)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      }).catch(function() {})
    }
  }
}
</script>
<style lang="scss">
  .vue-treeselect div{
    line-height: 40px;
  }
</style>
