<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        placeholder="请输入（角色名、标识）查询"
        style="width: 300px;"
        class="filter-item"
        v-model="listQuery.keywords"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-has="'sysOrg:combobox'"
        placeholder="组织"
        clearable
        class="filter-item"
        v-model="listQuery.orgId"
      >
        <el-option
          v-for="item in orgList"
          :key="item.identify"
          :label="item.name"
          :value="item.orgId"
        >
        </el-option>
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-circle-plus"
        @click="handleCreate"
        >新建</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="角色ID" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色唯一标识" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleKey }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type | typeFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column label="组织名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.orgName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.createTime | parseTime("{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="260">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          ></el-button>
          <el-button
            v-if="scope.row.type != -1 && scope.row.type != 0"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          ></el-button>
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-s-data"
            @click="handleRoleRes(scope.row)"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <swPage
      v-if="total > 0"
      key="2"
      :listQuery="listQuery"
      :total="total"
      pos="btmRight"
      @retPage="retPage"
    ></swPage>

    <!-- 新增或编辑对话框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="midData"
        label-position="right"
        label-width="90px"
        style="width: 70%; margin-left:50px;"
      >
        <el-form-item label="ID" v-show="isUpdate">
          <el-input v-model="midData.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="midData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="midData.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogResVisible" title="资源授权" top="2px">
      <el-tabs type="border-card">
        <el-tab-pane label="resourceAuthorization">
          <el-form
            ref="contactForm"
            label-position="left"
            label-width="100px"
            style="width: 400px; margin-left:50px; "
          >
            <el-form-item label="资源">
              <el-tree
                :data="resTree"
                :props="defaultProps"
                @check-change="handleCheckBoxClick"
                :show-checkbox="sureFlag"
                node-key="resId"
                ref="resTree"
                default-expand-all
                highlight-current
                style="background-color: #ecf5ff"
              >
              </el-tree>
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="sureFlag"
                type="primary"
                @click="handleUpdateRoleRes()"
                >确认</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="数据权限">
          <el-form
            ref="dataForm"
            label-position="left"
            label-width="120px"
            style="width: 400px; margin-left:50px;"
          >
            <el-form-item label="敏感数据">
              <el-checkbox-group v-model="sensitiveDataKey">
                <el-checkbox label="purchase_price">成本价</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="saveRoleSensitiveData()"
            >确认</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import waves from "@/directive/waves";
import swPage from "@/views/common/swPage";

import {
  fetchList,
  getRoleResTree,
  createRole,
  updateRole,
  getRoleById,
  deleteRole,
  saveRoleRes,
  saveRoleDataAuth
} from "@/api/auth/role";
import { orgCombobox } from "@/api/auth/org";

const typesOptions = [
  { key: -1, display_name: "平台管理员" },
  { key: 0, display_name: "组织管理员" },
  { key: 1, display_name: "普通角色" }
];

const typesKeyValue = typesOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "roleIndex",
  directives: {
    waves
  },
  components: {
    swPage
  },
  filters: {
    typeFilter(key) {
      return typesKeyValue[key];
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      resTree: null,
      dialogResVisible: false,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        keywords: null
      },
      dialogFormVisible: false,
      dialogStatus: "",
      midData: {
        roleId: "",
        roleName: "",
        remark: ""
      },
      textMap: {
        update: "编辑",
        create: "新建"
      },
      isUpdate: false,
      typesOptions,
      //用户数据
      roleData: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      currentRoleId: "",
      rules: {
        roleName: [{ required: true, message: "请填写名称", trigger: "change" }]
      },
      sureFlag: true, //是否可编辑
      orgList: [], //组织列表
      sensitiveDataKey: [] //数据授权
    };
  },
  created() {
    var orgQuery = sessionStorage
      .getItem("userBtns")
      .includes("sysOrg:combobox");
    if (orgQuery) {
      console.log("orgQuery=" + orgQuery);
      this.getorgList();
    }
    this.getList();
  },
  methods: {
    getorgList() {
      orgCombobox().then(response => {
        this.orgList = response.data;
      });
    },
    retPage() {
      //分页
      this.getList();
    },
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCreate() {
      this.resetMidData();
      this.dialogFormVisible = true;
      this.dialogStatus = "create";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate(row) {
      this.resetMidData();
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      this.isUpdate = true;
      // 获取角色详情
      getRoleById(row.roleId).then(response => {
        this.midData = response.data;
      });
    },
    handleRoleRes(row) {
      this.currentRoleId = row.roleId;
      //加载组织树
      let query = {
        roleId: this.currentRoleId
      };
      // request -> /sysOrgRoleRes/list
      getRoleResTree(query).then(response => {
        this.sureFlag = response.data.sureFlag;
        this.resTree = response.data.list;
        let checkedButton = response.data.buttonSelectedList;
        if (checkedButton != null && checkedButton.length > 0) {
          this.$refs.resTree.setCheckedKeys(checkedButton);
        }
      });
      this.dialogResVisible = true;
    },
    handleCheckBoxClick(data, checked, node) {},
    resetMidData() {
      this.midData = {
        roleId: "",
        roleName: "",
        remark: ""
      };
    },
    handleUpdateRoleRes() {
      // 全选和半选的全部传给后台
      var checkedKeys = this.$refs.resTree
        .getCheckedKeys(false)
        .concat(this.$refs.resTree.getHalfCheckedKeys());
      var roleResData = {
        roleId: this.currentRoleId,
        resIdSet: checkedKeys
      };
      console.log(roleResData);
      saveRoleRes(roleResData).then(() => {
        this.dialogResVisible = false;
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 3000
        });
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          createRole(this.midData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 3000
            });
            //重新加载数据
            this.getList();
          });
        }
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          updateRole(this.midData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 3000
            });
            //重新加载数据
            this.getList();
          });
        }
      });
    },
    handleDelete(row) {
      deleteRole(row.roleId).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 3000
        });
        const index = this.list.indexOf(row);
        this.list.splice(index, 1);
      });
    },
    saveRoleSensitiveData() {
      var data = {
        roleId: this.currentRoleId,
        sensitiveDataKeys: this.sensitiveDataKey
      };
      saveRoleDataAuth(data).then(reponse => {
        this.$notify({
          title: "成功",
          message: "设置成功",
          type: "success",
          duration: 2000
        });
      });
    }
  }
};
</script>

<style scoped></style>
