<template>
  <div style="padding: 20px">
    <div style="text-align: right">
      <el-button type="primary" @click="editAuth.show = true">新建权限项</el-button>
    </div>
    <el-table style="margin-top: 20px" :data="authList">
      <el-table-column label="权限名称" prop="authItemName" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="包含操作项" prop="operationItemCount" :formatter="(row, col, val) => val + '个' || '--'"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="text" @click="onEditAuthOpen(row)">编辑</el-button>
          <el-button type="text" @click="onDelAuth(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="editAuth.show" :title="editAuth.authItemId ? '编辑权限项' : '新建权限项'" width="590px" @closed="onEditAuthClose">
      <el-form :model="editAuth" :rules="editAuthRule" ref="editAuth" label-width="110px">
        <el-form-item label="权限项名称" prop="authItemName">
          <el-input
            type="text"
            placeholder="请输入权限项名称"
            style="width: 440px"
            maxlength="20"
            show-word-limit
            v-model.trim="editAuth.authItemName"
          ></el-input>
        </el-form-item>
        <el-form-item label="包含操作项" prop="operationItemIds">
          <el-select v-model="editAuth.operationItemIds" collapse-tags multiple clearable style="width:332px">
            <el-option v-for="el in operationList" :key="el.operationItemId" :value="el.operationItemId" :label="el.operationItemName"></el-option>
          </el-select>
          <el-button type="text" style="margin-left: 24px" @click="toOperationList">添加操作项</el-button>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="editAuth.show = false">取消</el-button>
        <el-button type="primary" :loading="editAuth.loading" @click="onEditAuthSave">{{ editAuth.authItemId ? '保存' : '新建' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { addAuthItem, editAuthItem, delAuthItem, getAuthItemList, getOperationItemList } = api;
// 新建权限项 done
// 编辑权限项 done
// 删除权限项 done
// 添加操作项跳转 done

export default {
  name: 'PermissionList',
  data() {
    return {
      bread: [
        { path: '/menu-config', name: '权限配置'},
        { name: '权限项'}
      ],
      menuId: '',
      appType: '',
      // 操作项列表
      operationList: [],
      // 权限项列表
      authList: [],
      // 新建、编辑权限项弹窗相关的数据
      editAuth: {
        show: false,
        loading: false,
        authItemId: '', // 权限项id
        authItemName: '', // 权限项名称
        operationItemIds: [] // 包含的操作项id
      },
      editAuthRule: {
        authItemName: [{ required: true, message: '权限项名称不能为空', trigger: 'blur' }],
        operationItemIds: [{ required: true, message: '请至少选择一个操作项', trigger: 'change' }]
      }
    }
  },
  created() {
    const { menuId, appType } = this.$route.query;
    if (!menuId) {
      return this.$router.go(-1);
    }
    this.menuId = menuId;
    this.appType = appType;
    this.initData();
    this.$emit('updateBread', this.bread)
  },
  methods: {
    initData() {
      // 获取权限项列表
      this.getAuthItemList();
      this.getOperationItemList(1);
    },
    // 获取当前节点下的操作项
    getOperationItemList(pageNum) {
      if (pageNum == 1) {
        this.operationList = [];
      }
      getOperationItemList({ menuId: this.menuId, pageSize: 20, pageNum }).then(res => {
        const { totalPage, result } = res.result || {};
        this.operationList = this.operationList.concat(result || []);
        if (pageNum + 1 <= totalPage) {
          this.getOperationItemList(pageNum + 1);
        }
      })
    },
    // 获取权限项列表
    getAuthItemList() {
      getAuthItemList({ menuId: this.menuId }).then(res => {
        this.authList = res.result || [];
      })
    },
    // 编辑权限项弹窗打开
    onEditAuthOpen(authData) {
      const { authItemId, authItemName, operationItemList } = authData;
      Object.assign(this.editAuth, {
        show: true,
        operationItemIds: Array.isArray(operationItemList) ? operationItemList.map(el => el.operationItemId) : [],
        authItemId,
        authItemName,
      })
    },
    // 新建、编辑权限项弹窗关闭
    onEditAuthClose() {
      Object.assign(this.editAuth, {
        authItemId: '',
        authItemName: '',
        operationItemIds: []
      });
      this.$nextTick(this.$refs.editAuth.clearValidate);
    },
    // 新建、编辑权限项弹窗保存
    onEditAuthSave() {
      this.$refs.editAuth.validate(vali => {
        if (!vali) return;
        const { authItemId, authItemName, operationItemIds } = this.editAuth;
        const params = {
          authItemName: emojiToStr(authItemName),
          operationItemIds: operationItemIds.join(','),
          menuId: this.menuId
        }
        this.editAuth.loading = true;
        if (authItemId) {
          params.authItemId = authItemId;
          editAuthItem(params).then(succ.bind(this, '保存成功！')).finally(() => this.editAuth.loading = false);
        } else {
          addAuthItem(params).then(succ.bind(this, '新建成功！')).finally(() => this.editAuth.loading = false);
        }
        function succ(msg) {
          this.$message.success(msg);
          this.editAuth.show = false;
          this.getAuthItemList();
        }
      })
    },
    // 删除权限项
    onDelAuth(authData) {
      const { authItemId, authItemName } = authData;
      this.$confirm(`确定删除【 ${authItemName} 】吗？`, '提示', { type: 'warning' }).then(() => {
        delAuthItem({ authItemId }).then(res => {
          this.$message.success('删除成功！');
          this.getAuthItemList();
        })
      })
    },
    // 去操作项列表页
    toOperationList() {
      this.$router.push(`/operation-list?type=${this.appType}`);
    }
  }
}
</script>
