<!--
 * @Author: Jason Liu
 * @Date: 2022-04-22 14:19:34
 * @Desc: 
-->
<template>
  <div class="role_set_container">
    <a-row :gutter="12">
      <a-col :span="6">
        <a-spin :spinning="loading">
          <div class="institution_list_container">
            <div class="search_list">
              <a-input-search
                allowClear
                v-model.lazy="name_key"
                :placeholder="$t('请输入机构名称')"
                @search="getInstitutionList"
              >
              </a-input-search>
            </div>
            <div class="institution_list">
              <vxe-table
                ref="institutionTree"
                show-overflow
                :show-header="false"
                border="outer"
                :row-config="{ isHover: true }"
                :tree-config="{
                  transform: true,
                  rowField: 'orgId',
                  parentField: 'parentOrg',
                  line: true,
                  expandAll: true,
                  trigger: 'cell',
                }"
                :row-class-name="getRoleRowClass"
                @cell-click="clickOrgRow"
                :data="institutionList"
                height="auto"
              >
                <vxe-column
                  field="orgName"
                  :title="$t('机构名称')"
                  tree-node
                ></vxe-column>
                <template #empty>
                  <a-empty
                    :image-style="{
                      height: '80px',
                    }"
                  >
                    <span slot="description">{{ $t("暂无数据") }}</span>
                  </a-empty>
                </template>
              </vxe-table>
            </div>
          </div>
        </a-spin>
      </a-col>
      <a-col :span="18">
        <a-spin :spinning="roleLoading">
          <div class="role_list_container">
            <a-row :gutter="[12, 12]" class="role_tool">
              <a-col class="label_title" :span="16">
                <a-input-search
                  allowClear
                  :placeholder="$t('请输入角色名称')"
                  class="role_input"
                  v-model="pager.queryParams.roleName"
                  @search="searchRoleList"
                />
              </a-col>
              <a-col :span="8" align="right">
                <a-button type="primary" icon="search" @click="searchRoleList">{{
                  $t("查询")
                }}</a-button>
                &nbsp;
                <a-button
                  type="primary"
                  icon="plus"
                  @click="editRole({ row: {} })"
                  v-w-auth-code="'add'"
                  >{{ $t("新增") }}</a-button
                >
              </a-col>
            </a-row>
            <div class="role_list">
              <vxe-table
                show-overflow
                show-header-overflow
                border
                resizable
                :loading="roleLoading"
                :row-config="{ isHover: true }"
                :data="roleList"
                height="auto"
                @cell-dblclick="editRole"
              >
                <vxe-column type="seq" :title="$t('序号')" width="50" align="center">
                </vxe-column>
                <vxe-column field="sysRole.roleName" :title="$t('角色名称')">
                </vxe-column>
                <vxe-column field="sysRole.remark" :title="$t('角色描述')"> </vxe-column>
                <vxe-column :title="$t('操作')" width="300" align="center">
                  <template #default="{ row }">
                    <div class="operate">
                      <a-button
                        class="btn"
                        type="link"
                        @click="editRole({ row: row })"
                        v-w-auth-code="'edit'"
                        >{{ $t("编辑") }}</a-button
                      >
                      <a-button
                        class="btn"
                        type="link"
                        @click="assignUser(row)"
                        v-w-auth-code="'assign'"
                        >{{ $t("分配用户") }}</a-button
                      >
                      <a-button
                        class="btn"
                        type="link"
                        @click="authorizationToRole(row)"
                        v-w-auth-code="'auth'"
                        >{{ $t("授权") }}</a-button
                      >
                      <a-popconfirm
                        :title="$t('确定要删除吗')"
                        :ok-text="$t('是')"
                        :cancel-text="$t('否')"
                        placement="left"
                        @confirm="deleteRole(row)"
                        v-w-auth-code="'delete'"
                      >
                        <a-button class="btn a_danger" type="link">{{
                          $t("删除")
                        }}</a-button>
                      </a-popconfirm>
                    </div>
                  </template>
                </vxe-column>
                <template #empty>
                  <a-empty
                    :image-style="{
                      height: '80px',
                    }"
                  >
                    <span slot="description">{{ $t("暂无数据") }}</span>
                  </a-empty>
                </template>
              </vxe-table>
            </div>
            <vxe-pager
              background
              :current-page.sync="pager.pageNum"
              :page-size.sync="pager.pageSize"
              :total="total"
              @page-change="getRoleList"
              :layouts="['Total', 'PrevJump', 'JumpNumber', 'NextJump', 'FullJump']"
            >
            </vxe-pager>
          </div>
        </a-spin>
      </a-col>
    </a-row>

    <a-modal
      :title="$t('角色信息')"
      :visible="visible"
      :confirm-loading="loading"
      :destroy-on-close="true"
      @ok="saveRole"
      @cancel="visible = false"
      :ok-text="$t('保存')"
      :cancel-text="$t('取消')"
    >
      <a-form-model
        ref="ruleForm"
        :model="info"
        :rules="rules"
        :label-col="layout.labelCol"
        :wrapper-col="layout.wrapperCol"
      >
        <a-form-model-item :label="$t('角色名称')" prop="roleName">
          <a-input v-model="info.roleName" :placeholder="$t('请输入角色名称')" />
        </a-form-model-item>
        <a-form-model-item :label="$t('角色描述')" prop="remark">
          <a-input
            v-model="info.remark"
            :placeholder="$t('请输入角色描述')"
            type="textarea"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <assignUser :show.sync="assignInfo.show" :info="assignInfo.info"></assignUser>
    <permission-assignment
      v-model="grantInfo.show"
      :role-id="grantInfo.roleId"
      :as-name="grantInfo.roleName"
    />
  </div>
</template>
<script>
const $appService = require("w-vue-basis/src/api/appService");
const $userService = require("w-vue-basis/src/api/userService");
const assignUser = require("./components/assignUser.vue").default;
const permissionAssignment = require("../appManagement/permissionAssignment").default;
export default {
  components: { assignUser, permissionAssignment },
  data() {
    return {
      loading: false,
      name_key: "",
      institutionList: [],
      selectRow: {},
      roleLoading: false,
      pager: {
        pageNum: 1,
        pageSize: 15,
        queryParams: {
          deptId: undefined,
          roleName: undefined,
          F_isDel_eq: 0,
          ORDER_createTime_asc: "0",
        },
      },
      total: 0,
      roleList: [],
      visible: false,
      info: {
        deptId: undefined,
        roleName: undefined,
        remark: undefined,
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      rules: {
        roleName: [{ required: true, message: $t("请输入角色名称"), trigger: "blur" }],
      },
      assignInfo: {
        show: false,
        info: {},
      },
      //授权信息
      grantInfo: {
        show: false,
        roleId: undefined,
        roleName: undefined,
      },
      isPermitOperate: false,
      viewSetButton: false,
    };
  },
  created() {
    this.getInstitutionList();
  },
  methods: {
    /**
     * @Author: y_zp
     * @description: 获取机构列表
     */
    getInstitutionList() {
      this.loading = true;
      $appService
        .getSysOrgTree({
          queryParams: { F_orgName_like: this.name_key },
          pageNum: 1,
          pageSize: 1000000,
        })
        .then((req) => {
          this.loading = false;
          this.institutionList = req.data;
          if (this.institutionList.length > 0) {
            this.selectRow = this.institutionList[0];
            this.pager.queryParams.deptId = this.institutionList[0].orgId;
            this.getRoleList();
          }
        })
        .finally(() => {
          this.$refs.institutionTree.setAllTreeExpand(true);
        });
    },
    /**
     * @Author: y_zp
     * @description: 点击机构
     */
    clickOrgRow({ row }) {
      // if (row.parentOrg != "0" && row.orgId != this.selectRow.orgId) {
      this.selectRow = row;
      this.pager.queryParams.deptId = row.orgId;
      this.getRoleList();
      // }
    },
    /**
     * @Author: y_zp
     * @description: 样式信息
     */
    getRoleRowClass(e) {
      return e.row.orgId == this.selectRow.orgId ? "row--current" : "";
    },
    /**
     * @Author: Jason Liu
     * @description: 查询角色列表
     */
    searchRoleList() {
      this.pager.pageNum = 1;
      this.getRoleList();
    },
    /**
     * @Author: y_zp
     * @description: 获取角色列表
     */
    getRoleList() {
      this.roleLoading = true;
      $appService
        .getRoleDeptList({ ...this.pager })
        .then((req) => {
          this.total = Number(req.count);
          this.roleList = req.data;
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * @Author: Jason Liu
     * @description: 新增/编辑角色
     */
    async editRole({ row }) {
      if (row.roleId) {
        let isOperate = (await this.permitOperateFun(row.roleId)) || false;
        if (!isOperate) {
          return false;
        }
        this.visible = true;
        this.info = {
          deptId: row.deptId,
          roleId: row.roleId,
          roleName: row.sysRole.roleName,
          remark: row.sysRole.remark,
          roleKey: row.sysRole.roleKey,
          roleSort: row.sysRole.roleSort,
        };
      } else {
        this.visible = true;
        this.info = {
          deptId: this.selectRow.orgId,
          roleName: undefined,
          remark: undefined,
          roleKey: "",
          roleSort: 0,
        };
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 删除角色
     */
    async deleteRole(row) {
      let isOperate = (await this.permitOperateFun(row.roleId)) || false;
      if (!isOperate) {
        return false;
      }
      this.loading = true;
      $appService
        .deleteRole({ id: row.roleId })
        .then((req) => {
          this.$message.success($t("角色删除成功"));
          this.getRoleList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * @Author: Jason Liu
     * @description: 保存角色信息
     */
    saveRole() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          $appService
            .saveRole(this.info)
            .then((req) => {
              this.$message.success($t("角色保存成功"));
              this.visible = false;
              this.getRoleList();
            })
            .finally(() => {});
        }
      });
    },

    /**
     * @Author: y_zp
     * @description: 分配用户
     */
    assignUser(row) {
      this.assignInfo = {
        show: true,
        info: row,
      };
    },
    /**
     * @Author: Jason Liu
     * @description: 角色授权
     */
    async authorizationToRole(row) {
      let isOperate = (await this.permitOperateFun(row.roleId)) || false;
      if (!isOperate) {
        return false;
      }
      this.grantInfo = {
        show: true,
        roleId: row.roleId,
        roleName: row.sysRole.roleName,
      };
    },
    /**
     * @Author: y_zp
     * @description: 是否容许操作
     */
    permitOperateFun(roleId) {
      return $userService
        .isPermitOperate(roleId)
        .then((req) => {
          return true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style lang="less" scoped>
.role_set_container {
  .institution_list_container {
    background: #fff;
    height: calc(100vh - 104px);
    padding: 16px;
    .search_list {
      margin-bottom: 12px;
    }
    .institution_list {
      height: calc(100% - 40px);
    }
  }
  .role_list_container {
    background: #fff;
    height: calc(100vh - 104px);
    padding: 16px;
  }
  .role_tool {
    font-size: 14px;
    font-weight: 400;
    color: #000000;
    line-height: 32px;

    .role_input {
      width: 200px;
      margin-right: 16px;
    }
  }
  .role_list {
    width: 100%;
    height: calc(100vh - 230px);
    display: inline-block;
    margin-top: 12px;
    .btn {
      padding: 0 6px;
    }
  }
}
</style>
