<template>
  <div class="template_content">
    <!-- 主体内容 -->
    <div class="content_box">
      <!-- 表格操作 -->
      <div class="table_top">
        <a-button
          icon="plus"
          type="primary"
          class="btn_right_margin"
          @click="showModal('')"
        >添加</a-button>
      </div>
      <a-table
        :columns="columns"
        :dataSource="data"
        :loading="loading"
        :pagination="pagination"
        bordered
        size="small"
        rowKey="id"
        @change="handleTableChange"
      >
        <template slot="action" slot-scope="text, record">
          <a-button
            icon="edit"
            type="primary"
            class="btn_margin"
            @click="showModal(record)"
          >编辑</a-button>
          <a-button
            icon="delete"
            type="danger"
            class="btn_margin"
            @click="deleteRow(record)"
          >删除</a-button>
          <a-button
            icon="cluster"
            type="link"
            class="btn_margin"
            @click="menuAuthModal(record)"
          >菜单权限</a-button>
        </template>
      </a-table>
    </div>
    <!-- 添加及编辑弹窗 -->
    <a-modal :title="modalTitle" v-model="modalVisible" :footer="null">
      <a-form :form="modalForm" @submit="modalHandleSubmit">
        
        <a-form-item label="角色名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
            v-decorator="[
          'name',{rules: [{required: true, message: '角色名称不能为空'}]}
        ]"
            placeholder="请输入角色名称"
          />
        </a-form-item>
        <a-form-item label="角色代码" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
            v-decorator="[
          'code',{rules: [{required: true, message: '角色代码不能为空'}]}
        ]"
            placeholder="请输入角色代码"
          />
        </a-form-item>
        
        <a-form-item :wrapper-col="{ span: 19, offset: 5 }">
          <a-button type="primary" html-type="submit">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 菜单权限弹窗 -->
    <a-modal
      title="菜单权限"
      v-model="menumodalVisible"
      :footer="null"
      destroyOnClose
    >
      <a-tree
        checkable
        :treeData="menuTreeData"
        :defaultCheckedKeys="menuDefaultCheckedKeys"
        :replaceFields="menuReplaceFields"
        defaultExpandAll
        @check="this.onMenuCheck"
      />
      <div class="btn-box">
        <a-button type="primary" @click="saveMenu">保存</a-button>
      </div>
    </a-modal>
    
  </div>
</template>
<script>
// 导入接口
import {
  addObj,
  delObj,
  fetchList,
  putObj,
  fetchRoleMenuIds,
  permissionUpd
} from "@/api/admin/role";
import { fetchMenuTree } from "@/api/admin/menu";
import { disposereq } from "@/utils/util";
let columns = [
  {
    title: "角色名称",
    dataIndex: "name",
    align: "center"
  },
  {
    title: "角色代码",
    dataIndex: "code",
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    align: "center"
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];

export default {
  data() {
    return {
      name: "",
      loading: true,
      searchPage: {
        pageIndex: 1,
        pageSize: 10,
        name: ""
      },
      columns: columns,
      data: [],
      pagination: {
        showQuickJumper: true,
        showSizeChanger: true
      },
      modalVisible: false,
      modalTitle: '添加',
      modalForm: this.$form.createForm(this, { name: "coordinated" }),
      rowData: {},
      menumodalVisible: false,
      menuTreeData: [],
      menuDefaultCheckedKeys: [],
      allMenuCheckedKeys: [],
      menuReplaceFields: {
        children: "children",
        title: "name",
        key: "id"
      },
      tmpMenuIds: []
    };
  },
  // 创建完毕
  created() {
    this.getList(this.searchPage);
    this.GetAllMenu();
  },
  // 即将更新渲染
  beforeUpdate() {

  },
  methods: {
    // 获取角色
    getList(pageData) {
      fetchList(pageData)
        .then(res => {
          this.loading = false;
          if (res.code == 200) {
            this.data = res.data;
            const pager = { ...this.pagination };
            pager.current = pageData.pageIndex;
            pager.total = res.count;
            this.pagination = pager;
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          this.$message.info(err);
        });
    },
    // 获取所有菜单
    GetAllMenu() {
      fetchMenuTree()
        .then(res => {
          if (res.resp_code == 200) {
            // console.log(res.datas)
            this.menuTreeData = res.datas.roots;
            this.deepList(res.datas.roots);
            // console.log(this.menuTreeData)
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          this.$message.info(err);
        });
    },
    // 获取选中菜单
    GetCheckMenu(roleId) {
      fetchRoleMenuIds(roleId)
        .then(res => {
          // console.log(this.tmpMenuIds)
          this.allMenuCheckedKeys = res.datas
          let result = [...new Set(this.tmpMenuIds)].filter((item) => new Set(eval(res.datas)).has(item));
          // console.log(result)
          this.menuDefaultCheckedKeys = result
          this.menumodalVisible = true;
        })
        .catch(err => {
          this.$message.info(err);
        });
    },
    deepList(data){
     data.map((item) => {
     if (item.children && item.children.length > 0) {
           this.deepList(item.children);
        } else {
            //test数组存放  
            this.tmpMenuIds.push(item.id);
        }
      });
    },

    // 表格数据变化触发事件
    handleTableChange(pagination, filters, sorter) {
      const searchPage = { ...this.searchPage };
      searchPage.current = pagination.current;
      searchPage.size = pagination.pageSize;
      this.loading = true;
      this.getList(searchPage);
    },
    // 搜索事件
    handleSubmit() {
      const searchPage = { ...this.searchPage };
      this.loading = true;
      this.getList(searchPage);
    },
    // 显示对话框
    showModal(row) {
      this.modalVisible = true;
      // 判断添加或者编辑
      if (row == "") {
        this.modalTitle = '添加';
        this.modalType = "add";
        this.$nextTick(() => {
          this.modalForm.setFieldsValue({
            name: "",
            code: ""
          });
        });
      } else {
        this.modalTitle = '编辑';
        this.modalType = "edit";
        
        this.$nextTick(() => {
          this.modalForm.setFieldsValue({
            name: row.name,
            code: row.code
          });
          this.rowData = row;
        });

      }
    },
    // 删除行数据
    deleteRow(row) {
      console.log(row)
      delObj([row.id])
        .then(res => {
          this.loading = false;
          if (res.resp_code == 200) {
            this.$message.success('删除成功');
            const searchPage = { ...this.searchPage };
            this.loading = true;
            this.getList(searchPage);
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          this.$message.info(err);
        });
    },
    // 对话框
    modalHandleSubmit(e) {
      e.preventDefault();
      this.modalForm.validateFields((err, values) => {
        if (!err && this.modalType == "add") {
          // console.log(values)
          addObj(values)
            .then(res => {
              if (res.resp_code == 200) {
                this.modalVisible = false;
                this.$message.success('保存成功');
                const searchPage = { ...this.searchPage };
                this.loading = true;
                this.getList(searchPage);
              } else {
                this.$message.info(res.resp_msg);
              }
            })
            .catch(err => {
              this.$message.info(err);
            });
        } else if (!err && this.modalType == "edit") {
          this.rowData.name = values.name;
          this.rowData.code = values.code;
          putObj(this.rowData)
            .then(res => {
              if (res.resp_code == 200) {
                this.modalVisible = false;
                this.$message.success('保存成功');
                const searchPage = { ...this.searchPage };
                this.loading = true;
                this.getList(searchPage);
              } else {
                this.$message.info(res.resp_msg);
              }
            })
            .catch(err => {
              this.$message.info(err);
            });
        }
      });
    },
    // 显示菜单权限
    menuAuthModal(row) {
      this.GetCheckMenu(row.id);
      this.roleId = row.id;
    },
    onMenuCheck(selectedKeys, info) {
      this.menuDefaultCheckedKeys = selectedKeys;
      this.allMenuCheckedKeys = selectedKeys.concat(info.halfCheckedKeys);
    },
    // 保存菜单
    saveMenu() {
      // console.log(this.allMenuCheckedKeys)
      permissionUpd(this.roleId, this.allMenuCheckedKeys)
        .then(res => {
          if (res.resp_code == 200) {
            this.menumodalVisible = false;
            this.$message.success('保存成功');
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          this.$message.info(err);
        });
    },
  
  }
};
</script>
<style>
.search_box {
  width: 100%;
  box-sizing: border-box;
  padding: 14px;
  background-color: #fff;
}
.template_content {
  background-color: #f0f2f5;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.content_box {
  width: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 14px;
}
.table_top {
  padding-bottom: 14px;
}
.btn_margin {
  margin: 0px 5px;
}
.btn_right_margin {
  margin-right: 10px;
}
.btn-box {
  margin-top: 20px;
}
</style>