<template>
  <div class="role">
    <div>
      <el-card class="myHeaderCard" style="height: 50px;display: flex;justify-content: flex-start;align-items: center">
        <el-row :span="24" class="header">
          <el-col :span="22" class="right" >
            <el-button size="small" type="primary" @click="addRole('form')">添加角色</el-button>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <el-row :span="24">
          <el-col :span="24">
            <el-table :data="roleData" style="width:100%" height="calc(100vh - 155px)" :default-sort="{prop: 'org_type', order: 'org_type'}">
              <el-table-column prop="org_type" label="机构类型" :formatter="formatter" min-width="150px">
                <template slot-scope="scope">
                  <span>{{ getOrgTypeLabel(scope.row.org_type) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色名称" min-width="150px" />
              <el-table-column label="操作" min-width="250px">
                <template slot-scope="scope">
                  <el-button size="small" type="primary" @click="addRoleAuth(scope.row)">权限配置</el-button>
                  <el-button size="small" type="primary" @click="editRole(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <el-dialog :title="isEdit ? '编辑角色' : '新增角色'" :visible.sync="dialogVisible" width="30%" class="myDialog1">
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="角色名:" prop="role">
          <el-input v-model="form.role" />
        </el-form-item>
        <el-form-item label="机构类型:">
          <el-select v-model="form.org_type" placeholder="请选择机构类型">
            <el-option v-for="item in orgList" :key="item.value" :label="item.v" :value="item.k">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="onSubmit('form')">确 定</el-button>
          <el-button size="small" @click="handleClose('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="'请为' + currentRow.role + '添加权限'" :visible.sync="isShow" width="30%" class="myDialog2">
      <div class="myChecked" >
        <Tree :tree-data="treeData" ref="tree" node-key="id" id="roleTree" :default-props="defaultProps" :showCheckbox="true"></Tree>
      </div>
      <span slot="footer">
        <div class="dialog-footer">
          <el-button size="small" @click="isShow = false">取 消</el-button>
          <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tree from "@/components/TreeControl/index.vue";
import {
  getRoleAPI,
  addRoleAPI,
  delRoleAPI,
  editRoleAPI,
  // addPermissionAPI,
  getpermissionAPI,
  editRoleAuthAPI,
  appCodesSearchAPI,
  getRolePermissionAPI
} from "@/api/superAdministrator/management";
export default {
  components: {
    Tree,
  },
  data() {
    return {
      id: '',
      roleData: [],
      defaultProps: {
        children: "son",
        label: "name",
      },
      name: '',
      rules: {
        role: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        org_type: [
          { required: true, message: "请输入机构名称", trigger: "blur" },
        ],
      },

      dialogVisible: false,
      form: {
        role: "",
        org_type: "0",
      },
      isShow: false,
      checked: true,
      isEdit: false,
      treeData: [], //权限树形结构的数据
      currentRow: {
        role: ''
      },
      // form.orgid: "0",
      // 0:业主机构；1:分销商；2:公司客户；3:个人客户；4：供应商
      orgList: [],
      page: 1,
      currentRowAuth: []
    };
  },
  created() {
    this.appCodesSearch();
    this.getRole();
  },
  methods: {
    formatter(row, column) {
      console.log(row);
      console.log(column);
      // return row.address;
    },
    getRole() { // 获取角色列表
      getRoleAPI({ page: this.page }).then((res) => {
        if (res.status == true) {
          // console.log(res);
          this.roleData = res.data.rows;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    //获取org_type
    appCodesSearch() {
      appCodesSearchAPI({
        kv: 1,
        codeid: "org_type",
      }).then(res => {
        this.orgList = res.data
      })
    },
    handleSubmit() {
      const authIds = this.$refs.tree.getCheckedKeys();
      var formdata = new FormData();
      formdata.append("roleid", this.currentRow.id);
      formdata.append("permid", JSON.stringify(authIds));
      editRoleAuthAPI(formdata).then((res) => {
        if (res.status == true) {
          this.isShow = false;
          this.$message({
            message: "权限编辑成功",
            type: "success",
          });
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    addRole() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.form = {
        role: "",
        org_type: "",
      };
    },
    onSubmit(formName) { // 添加角色&&编辑角色
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.isEdit) {// 添加
            addRoleAPI(this.form).then((res) => {
              if (res.status == true) {
                this.getRole();
                this.$message({
                  message: "角色添加成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          } else {// 编辑
            let params = {
              role: this.form.role,
              org_type: this.form.org_type,
              id: this.id
            }
            editRoleAPI(params).then((res) => {
              if (res.status == true) {
                this.getRole();
                this.$message({
                  message: "角色编辑成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          }
          this.dialogVisible = false;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
          return false;
        }
      });
      this.dialogVisible = false;
    },
    getOrgTypeLabel(val) {
      let label = '';
      const tempOrg = this.orgList.find((item) => { return item.k == val });
      if (tempOrg) {
        label = tempOrg.v
      } else {
        label = '未知机构'
      }
      return label
      // find
    },
    handleClose(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
    },
    delRole(row) { // 删除角色
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delRoleAPI({ id: row.id }).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "角色删除成功",
                type: "success",
              });
              this.getRole();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editRole(row) {  //编辑角色
      console.log(row);
      this.form = JSON.parse(JSON.stringify(row));
      this.isEdit = true;
      this.dialogVisible = true;
      this.id = row.id
    },
    getRolePermission(id) {
      getRolePermissionAPI({ roleid: id }).then(res => {
        this.currentRowAuth = res.data;
        // console.log(this.currentRowAuth);
        this.$refs.tree.setCheckedNodes(this.currentRowAuth)
      })
    },
    addRoleAuth(row) { // 添加树权限
      this.isShow = true;
      this.currentRow = row;
      getpermissionAPI().then((res) => {
        console.log(res);
        if (res.status) {
          this.treeData = res.data;
          this.getRolePermission(row.id);
        } else {
          this.treeData = [];
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-card__body{
  padding: 0;
}
.role {
  .myHeaderCard {
    margin-bottom: 5px;
    padding: 15px;
    .header {
      .left {
        text-align: left;
        .input-with-select {
          width: 60%;
          .searchSelect {
            width: 110px;
          }
          .searchSelectIcon {
            width: 30px;
          }
        }
      }
      .right {
        text-align: right;
        display: flex;
        justify-content: flex-end;
      }
    }

    .el-select .el-input {
      width: 30px;
    }
    .input-with-select .el-input-group__prepend {
      background-color: #fff;
    }
  }
  .myDialog2 {
    .myChecked {
      display: flex;
      flex-direction: column;
      line-height: 30px;
      height: 400px;
      overflow-y: scroll;
    }
    .dialog-footer {
      margin-left: 20%;
    }
  }
}
</style>
