<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-radio-group v-model="platform" size="small" @change="switchingPlatform">
          <el-radio-button :label="item.platformKey" v-for="(item, index) in moduleList" :key="index">{{item.platformName}}</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          :loading="refreshLoading"
          @click="handleRefresh"
        >刷新权限</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="menuList"
      row-key="menuId"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="icon" label="菜单名称" align="left" width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon" v-if="scope.row.icon" style="margin-right: 6px"/>
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="60"></el-table-column>
      <el-table-column prop="menuType" label="菜单类型">
        <template slot-scope="scope">
          <el-tag :type="scope.row.menuType === 'directory' ? '' : scope.row.menuType === 'component' ? 'success' : scope.row.menuType === 'link_inner' ? 'warning' : scope.row.menuType === 'link_outer' ? 'danger' : 'info'">{{scope.row.menuType === 'directory' ? '目录' : scope.row.menuType === 'component' ? '组件' : scope.row.menuType === 'link_inner' ? '内链' : scope.row.menuType === 'link_outer' ? '外链' : '按钮'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="enabled" label="Enable?" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled" disabled></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleAPIScope(scope.row)"
          >API权限</el-button>
          <el-button size="mini" 
            type="text" 
            icon="el-icon-edit" 
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-plus" 
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <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='directory'>目录</el-radio>
                <el-radio label='component'>组件</el-radio>
                <el-radio label='link_inner'>内链</el-radio>
                <el-radio label='link_outer'>外链</el-radio>
                <el-radio label='button'>按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.menuType !== 'button'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="form.icon"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <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="title">
              <el-input v-model="form.title" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType !== 'button'" label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType === 'directory' || form.menuType === 'component'">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType === 'button'" label="权限标识" prop="perms">
              <el-input v-model="form.perms" placeholder="请权限标识" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item v-if="form.menuType !== 'button'" label="Show？">
                  <el-radio-group v-model="form.hidden">
                    <el-radio :label="false">显示</el-radio>
                    <el-radio :label="true">隐藏</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Enable？">
                  <el-radio-group v-model="form.enabled">
                    <el-radio :label="true">正常</el-radio>
                    <el-radio :label="false">停用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </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>

    <!-- 分配角色API权限对话框 -->
    <el-dialog title="分配API权限" :visible.sync="openAPIScope" width="600px" append-to-body>
      <el-form :model="formApi" label-width="80px">
        <el-form-item label="API菜单">
          <el-tree
            :data="apiOptions"
            show-checkbox
            ref="api"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApiScope">确 定</el-button>
        <el-button @click="cancelApiScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMenu, getMenu, delMenu, addMenu, updateMenu, allOfTree, getModuleUser } from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import { getApiTrees, addRoleApis, getApis, refreshPower, getServer } from "@/api/system/api";
export default {
  name: "Menu",
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // api列表
      apiOptions: [],
      // api权限弹窗控制
      openAPIScope: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      formApi: {},
      // 表单参数
      form: {
        visible: null,
        platformType:"0"
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ],
        perms: [
          { required: true, message: '按钮的权限标识不能为空', trigger: 'blur' }
        ]
      },
      moduleList: [],
      platform: '',
      refreshLoading: false,
      serverList: [],
      sysDatas: []
    };
  },
  created() {
    this.getPlatform()
  },
  methods: {
    /** 刷新权限 */
    handleRefresh() {
      this.refreshLoading = true
      refreshPower().then(()=>{
        this.refreshLoading = false
        this.msgSuccess('刷新成功')
      }).catch(() => {
        this.refreshLoading = false
      })
    },
    getPlatform() {
      getModuleUser().then(res => {
        this.moduleList = res.data
        if(res.data.length > 0) {
          this.moduleList = res.data
          this.platform = res.data[0].platformKey
          this.getList();
        } else {
          this.loading = false;
        }
      })
      getServer().then(res => {
        this.serverList = res.data
        this.sysDatas = res.data.map(item => item.moduleKey)
      })
    },
    /** 切换平台 */
    switchingPlatform(e) {
      this.platform = e
      this.getList();
    },
    // 取消按钮 （API权限）
    cancelApiScope() {
      this.openAPIScope = false
      this.formApi = {}
    },
    /** 分配APi权限 */
    submitApiScope() {
      let checkedKeys = this.$refs.api.getHalfCheckedKeys();
      let halfCheckedKeys = this.$refs.api.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      this.sysDatas.forEach(item => {
        let index = checkedKeys.findIndex(c => c === item)
        if(index !== -1) {
          checkedKeys.splice(index, 1); 
        }
      })
      addRoleApis({...this.formApi, apiIds: [...checkedKeys]}).then(res => {
        if(res) {
          this.msgSuccess("分配成功");
          this.openAPIScope = false
          this.formApi = {}
          this.apiOptions = []
        }
      })
    },
    /** API权限按钮 */
    handleAPIScope(row) {
      let apiMenu = getMenu(row.menuId).then(response => {
        return response.data.apiIds
      });
      this.formApi = {roleId: row.menuId}
      getApis().then(res => {
        let options = []
        for (const key in res.data) {
          if (Object.hasOwnProperty.call(res.data, key)) {
            const element = res.data[key];
            if(element.length > 0) {
              let option = element.map(it => {
                let { id, name, subApis } = it
                let children = []
                if(subApis) {
                  children = subApis.map(item => {
                    let { id, name, parentId, httpMethod, url } = item
                    return {
                      label: name + `${parentId && ' - ' + url + ' - ' + httpMethod}`,
                      id
                    }
                  })
                }
                return {
                  label: name,
                  id,
                  children
                };
              })
              let sys = this.serverList.find(sy => sy.moduleKey === key)
              if (sys) {
                options.push({
                  label: sys.moduleName || '空',
                  id: sys.moduleKey || key,
                  // disabled: true,
                  children: option
                })
              }
            }
          }
        }
        this.apiOptions = [...options]
        apiMenu.then(res => {
          this.openAPIScope = true
          this.$nextTick(()=>{
            setTimeout(()=>{
                res.forEach((element) => {
                  let node = this.$refs.api.getNode(element);
                  if (node.isLeaf) {
                    this.$refs.api.setChecked(node, true);
                  }
                })
              },100)
          })
        })
      })
    },
    /** 查询API树结构 */
    getApiTreeselect() {
      return getApiTrees()
    },
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      allOfTree(this.platform).then(response => {
        this.menuList = this.handleTree(response.data, "menuId");
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.title,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      allOfTree(this.platform).then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, title: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: null,
        title: undefined,
        icon: undefined,
        menuType: 'directory',
        orderNum: 0,
        enabled: true,
        hidden: false,
        path: '',
        component: null,
        belongPlatform: this.platform
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList('platformType=0');
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.menuId) {
        this.form.parentId = row.menuId;
      } else {
        this.form.parentId = null;
      }
      this.open = true;
      this.title = "添加菜单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getMenu(row.menuId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改菜单";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = this.form
          params = { ...params, belongPlatform: this.platform, parentId: this.form.parentId == 0 ? null : this.form.parentId }
          if (params.menuId != undefined) {
            updateMenu(params.menuId, params).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addMenu(params).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.title + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMenu(row.menuId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    }
  }
};
</script>