<template>
  <div v-if="userName === '系统管理员'">
    <el-container>
      <!--搜索-->
      <el-header class="searchBox">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.name" placeholder="姓名" />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="searchForm.account" placeholder="账号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchBtn">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
          <el-button
            style="float: right"
            type="warning"
            icon="el-icon-circle-plus-outline"
            @click="add"
          >
            立即创建
          </el-button>
        </el-form>
      </el-header>

      <!--表格-->
      <el-main class="tableBox">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="id" label="序列号" width="100" />
          <el-table-column prop="account" label="账号" width="150" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="createTime" label="创建时间" width="200" />
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button type="text" size="small" @click="dele(scope.row.id)"
                >删除</el-button
              >
              <el-button type="text" size="small" @click="empower(scope.row.id)"
                >角色</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page.sync="searchForm['pageNum']"
            :page-sizes="[20, 50, 100, 300]"
            :page-size="searchForm['pageSize']"
            layout="total, sizes, pager"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>

    <!--新增抽屉-->
    <el-drawer
      ref="addDrawer"
      title="新增用户"
      size="30%"
      :before-close="addHandleClose"
      :with-header="false"
      :visible.sync="addDialog"
      direction="rtl"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <span>新增用户</span>
        <el-form :model="addForm" :rules="rules" ref="ruleForm">
          <el-form-item label="账号" label-width="80px" prop="account">
            <el-input v-model="addForm.account" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" label-width="80px" prop="passwordHash">
            <el-input v-model="addForm.passwordHash" autocomplete="off" />
          </el-form-item>
          <el-form-item label="姓名" label-width="80px" prop="name">
            <el-input v-model="addForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机号" label-width="80px" prop="phone">
            <el-input v-model="addForm.phone" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="$refs.addDrawer.closeDrawer()"
            >{{ loading ? "提交中 ..." : "确 定" }}
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!--编辑抽屉-->
    <el-drawer
      ref="editDrawer"
      title="编辑角色"
      size="30%"
      :before-close="editHandleClose"
      :with-header="false"
      :visible.sync="editDialog"
      direction="rtl"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <span>编辑角色</span>
        <el-form :model="editForm">
          <el-form-item label="账号" label-width="80px">
            <el-input v-model="editForm.account" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" label-width="80px">
            <el-input v-model="editForm.passwordHash" autocomplete="off" />
          </el-form-item>
          <el-form-item label="姓名" label-width="80px">
            <el-input v-model="editForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机号" label-width="80px">
            <el-input v-model="editForm.phone" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="$refs.editDrawer.closeDrawer()"
            >{{ loading ? "提交中 ..." : "确 定" }}
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!--授权弹窗-->
    <el-dialog title="授权" :visible.sync="showEmp">
      <el-transfer
        v-model="myAuth"
        :data="allAuth"
        :titles="['未授权', '已授权']"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEmp = false">取 消</el-button>
        <el-button type="primary" @click="postList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  <div v-else style="margin: 50px 30px; text-align: center">
    您没有当前页面操作权限
  </div>
</template>

<script>
import { post, get } from "@/api/common";

export default {
  name: "RoleList",
  data() {
    return {
      allAuth: [],
      myAuth: [],
      loading: false,
      editDialog: false,
      addDialog: false,
      showEmp: false,
      userId: "",
      userName: "",
      searchForm: {
        name: "",
        account: "",
        pageSize: 20,
        pageNum: 1,
      },
      addForm: {
        name: "",
        account: "",
        passwordHash: "",
        phone: "",
      },
      editForm: {
        name: "",
        account: "",
        phone: "",
      },
      tableData: [],
      total: 5000,
      rules: {
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        passwordHash: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
    };
  },
  created() {
    var that = this;
    that.search();
    let userName = this.$store.state.user.name;
    get("/sysUser/page", { name: userName })
      .then((res) => {
        var list = res.data.list;
        if (
          list.length === 1 &&
          list[0].sysRoleList[0].description === "管理员角色"
        ) {
          this.userName = "系统管理员";
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    async search() {
      // 同步搜索
      await get("/sysUser/page", this.searchForm)
        .then((res) => {
          this.tableData = res.data.list;
          this.total = res.data.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    searchBtn() {
      // 搜索按钮
      this.search();
    },
    reset() {
      // 重置
      this.searchForm = {
        authUrl: "",
        authName: "",
        pageSize: 20,
        pageNum: 1,
      };
      this.search();
    },
    add() {
      // 新增
      this.addDialog = true;
    },
    addHandleClose(done) {
      // 新增数据
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.loading) return;
          if (!/^1[3456789]\d{9}$/.test(this.addForm.phone)) {
            this.$message.error("手机号格式错误!");
            this.addForm.phone = "";
            return false;
          }
          this.$confirm("确定要提交吗？")
            .then((_) => {
              done();
              this.addDialog = true;
              post("/sysUser/create", this.addForm)
                .then((res) => {
                  if (res.code === 10000) this.reset();
                  setTimeout(() => {
                    this.addDialog = false;
                  }, 400);
                })
                .catch((err) => {
                  console.log(err);
                });
            })
            .catch((_) => {
              this.addDialog = false;
            });
        }
      });
    },
    edit(e) {
      // 编辑
      this.editForm = e;
      this.editDialog = true;
    },
    editHandleClose(done) {
      // 修改数据
      if (this.loading) return;
      this.$confirm("确定要提交吗？")
        .then((_) => {
          done();
          this.editDialog = true;
          delete this.editForm.sysRoleList;
          post("/sysUser/update/" + this.editForm.id, this.editForm)
            .then((res) => {
              if (res.code === 10000) this.reset();
              setTimeout(() => {
                this.editDialog = false;
              }, 400);
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((_) => {
          this.editDialog = false;
        });
    },
    dele(e) {
      // 删除
      this.$confirm("确定要删除么？").then((_) => {
        post("/sysUser/delete", { ids: [e] }).then((res) => {
          if (res.code === 10000) this.reset();
        });
      });
    },
    empower(e) {
      this.showEmp = true;
      this.userId = e;
      get("/sysUser/getUserRole", { userId: e }).then((res) => {
        this.myAuth = res.data;
      });
      get("/sysRole/list").then((res) => {
        this.allAuth = res.data;
      });
    },
    postList() {
      post("/sysUser/setUserRole", {
        userId: this.userId,
        roleIdList: this.myAuth,
      }).then((res) => {
        if (res.code === 10000) this.showEmp = false;
      });
    },
    cancelForm() {
      // 关闭抽屉
      this.loading = false;
      this.editDialog = false;
      this.addDialog = false;
      clearTimeout(this.timer);
    },
    handleSizeChange(e) {
      // 单页数量
      this.searchForm.pageSize = e;
      this.searchForm.pageNum = 1;
      this.search();
    },
    handleCurrentChange(e) {
      // 跳页
      this.searchForm.pageNum = e;
      this.search();
    },
  },
};
</script>

<style scoped lang="scss">
.searchBox {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: #bfbfbf 0 0 2px;
  height: unset !important;

  form {
    margin: auto;
  }
}

.el-header {
  padding: 20px;
}

.el-form-item {
  margin-bottom: unset;
}

.tableBox {
  margin-top: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: #bfbfbf 0 0 2px;
}

.block {
  margin-top: 20px;
  float: right;
}

.demo-drawer__content {
  padding: 20px 5%;
  line-height: 32px;

  .el-form-item {
    margin-top: 20px;
  }

  .demo-drawer__footer {
    position: fixed;
    bottom: 30px;
    width: 27%;
    margin-top: 20px;
    display: flex;

    button {
      flex: 1;
    }
  }

  .el-select {
    display: block;
  }

  .el-dialog {
    min-width: 630px;
  }
}
</style>
