
<template>
  <div class="app-container calendar-list-container">
    <basic-container>

          <el-table
            :data="list"
            border
            style="width: 100%"
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column prop="dictName" label="角色名字" >
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  v-if="roleManager_btn_perm"
                  type="text"
                  size="small"
                  icon="el-icon-plus"
                  @click="handlePermission(scope.row)"
                  >权限
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-pagination
            style="text-align: center"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page.sync="page.pageNum"
            :page-size="page.pageSize"
            layout="total,prev, pager, next, jumper"
            :total="page.total"
          >
          </el-pagination> -->
    </basic-container>



    <el-dialog
      :visible.sync="dialogPermissionVisible"
      :close-on-click-modal="false"
      title="分配权限"
    >
      <div class="dialog-main-tree">
        <el-tree
          ref="menuTree"
          :data="treeData"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          node-key="id"
          highlight-current
          show-checkbox
        />
        <!-- default-expand-all -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="updatePermession(orgType)"
          >更 新
        </el-button>
        <el-button type="default" size="small" @click="cancal()"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addObj,
  delObj,
  fetchList,
  fetchRoleTree,
  permissionUpd,
  putObj,
} from "@/api/admin/role";
import { tableOption } from "@/const/crud/admin/role";
import { fetchTree } from "@/api/admin/dept";
import { fetchMenuTree } from "@/api/admin/menu";
import { mapGetters } from "vuex";

export default {
  name: "TableRole",
  data() {
    return {
      searchForm: {},
      tabselect: "0",
      agentList: [], //代理商
      orgList: [],
      orgId: "",
      agentId: "",
      selectKeys: [],
      tableOption: tableOption,
      dsScopeData: [],
      treeData: [],
      checkRole: [],
      filterText: "",
      treeDataList: [],
      checkedKeys: [],
      checkedDsScope: [],
      searchMsg: {
        roleName: "",
        lockFlag: "",
      },
      defaultProps: {
        label: "name",
        value: "id",
      },
      formTitle: "新增",
      orgCode: "",
      defaultProps1: {
        label: "name",
        value: "id",
      },
      treeOption: {
        nodeKey: "aid",
        addBtn: false,
        defaultCheckedKeys: [1],
        menu: false,
        props: {
          label: "name",
          value: "aid",
        },
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      menuIds: "",
      list: [],
      listLoading: true,
      dialogFormVisible: false,
      form: {
        roleName: "", //角色名称
        // dsType: "", //数据权限
        roleDesc: "", //描述
        orgCode: "", //公司
        lockFlag: "0", //状态
      },
      addFlag: true,
      rules: {
        roleName: [
          { required: true, message: "请填写角色名称", trigger: "blur" },
        ],
        // dsType: [
        //   { required: true, message: "请选择数据权限", trigger: "blur" },
        // ],
      },
      editFlag: false,
      roleId: undefined,
      roleCode: undefined,
      rolesOptions: undefined,
      dialogPermissionVisible: false,
      roleManager_btn_add: false,
      roleManager_btn_edit: false,
      roleManager_btn_del: false,
      roleManager_btn_perm: false,
    };
  },
  async created() {
    this.roleManager_btn_add = this.permissions["sys_role_add"];
    this.roleManager_btn_edit = this.permissions["sys_role_edit"];
    this.roleManager_btn_del = this.permissions["sys_role_del"];
    this.roleManager_btn_perm = this.permissions["sys_role_perm"];
    this.getTableList()
    // this.getTreeDataList()//获取部门树
  },
  watch: {
  },
  computed: {
    ...mapGetters(["elements", "permissions"]),
  },
  methods: {
    getTableList(){
      this.$api.api.userDict({
        dictType:1,
      }).then(res=>{
        console.log(res);
        this.list=res.data
      })
    },
    cancal() {
      this.dialogPermissionVisible = false;
    },
    handlePermission(row) {
      console.log(row.dictValue);
      this.$api.api.fetchRoleTree(row.dictValue)
        .then((response) => {
          this.checkedKeys = response.data;
          return fetchMenuTree();
        })
        .then((response) => {
          this.treeData = response.data;
          // 解析出所有的太监节点
          this.checkedKeys = this.resolveAllEunuchNodeId(
            this.treeData,
            this.checkedKeys,
            []
          );
          this.dialogPermissionVisible = true;
          this.orgType = row.dictValue;
          // this.roleCode = row.roleCode;
        });
    },
    filterNode(value, data) {
      // console.log(value,data);
      // return
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /**
     * 解析出所有的太监节点id
     * @param json 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i];
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp);
        } else {
          temp.push(idArr.filter((id) => id === item.id));
        }
      }
      return temp;
    },
    // filterNode(value, data) {
    //   if (!value) return true
    //   return data.label.indexOf(value) !== -1
    // },
    getNodeData(data, done) {
      done();
    },
    create(row, done, loading) {
      if (this.form.dsType === 1) {
        this.form.dsScope = this.$refs.scopeTree.getCheckedKeys().join(",");
      }
      addObj(...this.form, ...{ orgCode: this.orgCode })
        .then(() => {
          this.getList();
          done();
          this.$notify.success("创建成功");
        })
        .catch(() => {
          loading();
        });
    },
    handleSelectionChange(e) {
      this.checkRole = [];
      console.log(e);
      e.map((item) => {
        this.checkRole.push(item.roleId);
      });
    },
    updatePermession(orgType) {
      this.menuIds = "";
      this.menuIds = this.$refs.menuTree
        .getCheckedKeys()
        .join(",")
        .concat(",")
        .concat(this.$refs.menuTree.getHalfCheckedKeys().join(","));
        this.$api.api.permissionUpd(orgType, this.menuIds).then(() => {
        this.dialogPermissionVisible = false;
        this.$notify.success("修改成功");
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  .el-dialog {
    width: 61% !important;
    .dialog-main-tree {
      max-height: 400px;
      overflow-y: auto;
    }
  }
  .el-form-item__label {
    width: 20% !important;
    padding-right: 20px;
  }
  .el-form-item__content {
    margin-left: 20% !important;
  }
}
