<template>
  <div style="padding: 20px">
    <el-input
      type="text"
      style="width:340px"
      placeholder="请输入节点名称/代码"
      prefix-icon="el-icon-search"
      clearable
      v-model.trim="search"
      @change="getMenuList"></el-input>
    <el-button type="primary" style="float:right;margin-left:10px" @click="onEditMenu()">新建节点</el-button>
    <el-button type="primary" style="float:right;" @click="onExpandChange">收起/展开子节点</el-button>
    <el-table style="margin-top:20px" v-if="showTable" :data="menuList" :default-expand-all="expand" row-key="menuId" tooltip-effect="dark">
      <el-table-column label="节点名称" prop="menuName" show-overflow-tooltip :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="页面code" prop="code" show-overflow-tooltip :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="父级code" prop="parentCode" show-overflow-tooltip :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column :label="appType == 1 ? '好办版本' : '应用版本'" prop="hbVersion" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="操作" width="320px">
        <template slot-scope="{ row }">
          <el-button type="text" @click="onEditMenu(row)">编辑</el-button>
          <el-button type="text" @click="onEditMenu(row, true)">新建子节点</el-button>
          <el-button type="text" @click="toPermissionList(row)">{{row.operationItemFlag == 1 ? '编辑权限项' : '新建权限项'}}</el-button>
          <el-button v-if="!Array.isArray(row.children) || row.children.length == 0" type="text" @click="onDelMenu(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="editMenu.show"
      :title="`${editMenu.menuId ? '编辑' : '新建'}${editMenu.isSubMenu ? '子' : ''}节点`"
      width="600px"
      @closed="onEditMenuClose">
      <el-form :model="editMenu" :rules="editMenuRules" ref="editMenu" label-width="105px" @submit.native.prevent>
        <el-form-item label="好办版本" prop="hbVersion" v-if="appType == 1 || appType == 3">
          <el-select v-model="editMenu.hbVersion" style="width: 440px">
            <el-option v-for="el in haobanVersionList" :key="el.versionCode" :value="el.versionCode" :label="el.versionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用版本" prop="hbVersion" v-else>
          <el-select v-model="editMenu.hbVersion" style="width: 440px">
            <el-option v-for="el in appVersionList" :key="el.versionCode" :value="el.versionCode" :label="el.versionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点名称" prop="menuName">
          <el-input
            type="text"
            placeholder="请输入节点名称"
            style="width: 440px"
            maxlength="20"
            show-word-limit
            v-model.trim="editMenu.menuName"></el-input>
        </el-form-item>
        <el-form-item label="节点code" prop="code">
          <el-input
            type="text"
            placeholder="请输入节点code"
            style="width: 440px"
            maxlength="40"
            show-word-limit
            v-model.trim="editMenu.code"></el-input>
        </el-form-item>
        <el-form-item v-if="editMenu.parentCode != ''" label="父级code" >
          <el-input
            type="text"
            placeholder="请输入节点code"
            style="width: 440px"
            maxlength="200"
            show-word-limit
            disabled
            :value="editMenu.parentCode"></el-input>
        </el-form-item>
        <el-form-item label="节点路径">
          <el-input
            type="text"
            placeholder="请输入节点路径"
            style="width: 440px"
            maxlength="200"
            show-word-limit
            v-model.trim="editMenu.menuUrl"></el-input>
        </el-form-item>
        <el-form-item label="图标" v-if="appType == 1 || appType == 2">
          <el-input
            type="text"
            placeholder="请输入节点图标"
            style="width: 440px"
            maxlength="64"
            show-word-limit
            v-model.trim="editMenu.menuIcon"></el-input>
        </el-form-item>
        <el-form-item label="打开方式" v-if="appType == 1">
          <el-radio-group v-model="editMenu.openType">
            <el-radio :label="0">当前页</el-radio>
            <el-radio :label="1">新开页</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="作为菜单" v-if="appType == 1 || appType == 2">
          <el-radio-group v-model="editMenu.menuFlag">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限适用">
          <el-radio-group v-model="editMenu.roleRange">
            <el-radio :label="1">管理员权限集</el-radio>
            <el-radio :label="2">管理员和门店适用</el-radio>
            <el-radio :label="3">门店适用</el-radio>
            <el-radio :label="4">超管</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="editMenu.show = false">取消</el-button>
        <el-button type="primary" :loading="editMenu.loading" @click="onEditMenuSave">{{ editMenu.menuId ? '保存' : '新建' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { emojiToStr } from '@/common/js/public.js';
import api from '@/api/permission.js';

const { getMenuList, addMenu, editMenu, delMenu, haobanVersionList, appVersionList } = api;
// 主要功能
// 搜索 done
// 收起、展开节点 done
// 新建节点 done
// 编辑 done
// 新建子节点 done
// 新建权限项跳转 done
// 查看权限项跳转 done
// 删除 done
// 好办版本、应用版本接口联调

export default {
  name: 'MenuList',
  props: {
    appType: [ String, Number ]
  },
  data() {
    return {
      haobanVersionList: [],
      appVersionList: [],
      search: '', // 查询条件
      expand: false, // 是否展示子节点 true：展示 false：不展示
      showTable: true,
      // 节点列表数据
      menuList: [],
      // 新建节点、新建子节点、编辑节点弹窗相关的数据
      editMenu: {
        show: false, // 是否展示编辑节点的弹窗
        loading: false, // 编辑节点弹窗的确定按钮提交时loading
        isSubMenu: false, // 是否是子节点 true：是子节点 false：不是子节点
        parentCode: '',
        menuId: '',
        menuName: '',
        parentId: '',
        hbVersion: '',
        code: '',
        menuUrl: '',
        menuIcon: '',
        openType: 0, // 0当前页1新开页
        menuFlag: 1, // 是否作为节点1是0否
        roleRange: 1, // 1管理员适用2管理员和门店适用3门店适用
      },
      editMenuRules: {
        hbVersion: [ { required: true, message: '请选择好办版本', trigger: 'change' } ],
        menuName: [ { required: true, message: '页面名称不能为空', trigger: 'blur' } ],
        code: [ { required: true, message: '页面code不能为空', trigger: 'blur' } ]
      }
    };
  },
  mounted() {
    this.menuList = [];
    this.initData();
  },
  methods: {
    initData() {
      haobanVersionList().then(res => {
        this.haobanVersionList = res.result || [];
      });
      appVersionList().then(res => {
        this.appVersionList = res.result || [];
      });
      this.getMenuList();
    },
    // 获取节点列表数据
    getMenuList() {
      const params = {
        menuId: '',
        appType: this.appType,
        keyword: this.search
      };
      getMenuList(params).then(res => {
        this.menuList = this.flatDataToTree(res.result || []);
      });
    },
    // 收起、展开子节点
    onExpandChange() {
      this.showTable = false;
      this.$nextTick(() => {
        this.expand = !this.expand;
        this.showTable = true;
      });
    },
    // 新建节点、新建子节点、编辑节点弹窗打开
    onEditMenu(menuData, isSubMenu) {
      const { parentCode, parentId, menuId, menuName, hbVersion, code, menuUrl, menuIcon, openType, menuFlag, roleRange } = menuData || {};
      // 新建子节点
      if (isSubMenu) {
        Object.assign(this.editMenu, {
          isSubMenu: true,
          parentCode: code,
          parentId: menuId
        });
      }

      // 编辑节点、编辑子节点
      if (!isSubMenu && menuId) {
        Object.assign(this.editMenu, {
          parentCode,
          parentId,
          menuId,
          menuName,
          hbVersion,
          code,
          menuUrl,
          menuIcon,
          openType: openType ? openType : 0,
          menuFlag: menuFlag ? menuFlag : 0,
          roleRange: roleRange ? roleRange : 1
        });
      }
      Object.assign(this.editMenu, { show: true });
    },
    // 新建节点、新建子节点、编辑节点弹窗关闭
    onEditMenuClose() {
      Object.assign(this.editMenu, {
        isSubMenu: false,
        parentCode: '',
        menuId: '',
        menuName: '',
        parentId: '',
        hbVersion: '',
        code: '',
        menuUrl: '',
        menuIcon: '',
        openType: 0,
        menuFlag: 1,
        roleRange: 1
      });
      this.$nextTick(this.$refs.editMenu.clearValidate);
    },
    // 新建节点、新建子节点、编辑节点弹窗保存
    onEditMenuSave() {
      this.$refs.editMenu.validate(vali => {
        if (!vali) return;
        const { isSubMenu, menuId, menuName, parentId, parentCode, hbVersion, code, menuUrl, menuIcon, openType, menuFlag, roleRange } = this.editMenu;
        const params = {
          menuName: emojiToStr(menuName),
          hbVersion,
          code: emojiToStr(code),
          menuUrl: emojiToStr(menuUrl),
          menuIcon: emojiToStr(menuIcon),
          openType,
          menuFlag,
          roleRange
        };
        if (parentId) {
          params.parentId = parentId;
        }
        this.editMenu.loading = true;
        // 编辑节点
        if (!isSubMenu && menuId) {
          params.menuId = menuId;
          editMenu(params).then(succ.bind(this, '保存成功！')).finally(() => this.editMenu.loading = false);
        } else {
          params.appType = this.appType;
          params.parentCode = parentCode;
          // 新建节点、新建子节点
          addMenu(params).then(succ.bind(this, '新建成功！')).finally(() => this.editMenu.loading = false);
        }
        function succ(msg) {
          this.editMenu.show = false;
          this.$message.success(msg);
          this.getMenuList();
        }
      });
    },
    // 删除节点
    onDelMenu(menuData) {
      const { menuId, menuName } = menuData;
      this.$confirm(`确定删除【 ${menuName} 】吗？`, '提示', { type: 'warning' }).then(() => {
        delMenu({ menuId }).then(res => {
          this.$message.success('删除成功！');
          this.getMenuList();
        });
      });
    },
    // 跳转到权限项列表页
    toPermissionList(menuData) {
      const { menuId } = menuData;
      this.$router.push(`/permission-list?menuId=${menuId}&appType=${this.appType}`);
    },
    flatDataToTree(data) {
      return data.filter(el => {
        // 返回当前节点下的子节点
        const children = data.filter(item => item.parentId == el.menuId);
        if (children.length > 0) {
          el.children = children; // 如果存在子级，则给父级添加一个children属性，并赋值
        }
        return el.parentId == 0;
      });
    },
  }
};
</script>
<style lang="less" scoped>
.el-radio-group {
  .el-radio {
    line-height: 32px;;
  }
}
</style>
