<template>
  <div class="user-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <el-form-item label="手机号：" label-width="75px">
          <el-input
            style="width: 142px"
            v-model.trim="filter.loginName"
            placeholder="手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" label-width="75px">
          <el-input
            style="width: 142px"
            v-model.trim="filter.realName"
            placeholder="姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="启用/禁用：" label-width="90px">
          <el-select
            v-model="filter.enable"
            style="width: 120px"
            placeholder="启用/禁用"
            clearable
          >
            <el-option
              v-for="(val, key) in ABLE_TYPE"
              :key="key"
              :value="key * 1"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label-width="0px">
          <el-button type="primary" @click="toPage(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="toAdd"
          >新增用户</el-button
        >
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="users">
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="mobileNumber" label="手机号"></el-table-column>
        <el-table-column prop="realName" label="姓名"></el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column prop="orgName" label="学院"></el-table-column>
        <el-table-column prop="enable" label="状态" width="100">
          <template slot-scope="scope">
            {{ scope.row.enable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.updateTime | timestampFilter }}
          </template>
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              class="btn-danger"
              type="text"
              @click="toResetPwd(scope.row)"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          :page-sizes="[20, 50, 100]"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>

    <!-- ModifyUser -->
    <modify-user
      ref="ModifyUser"
      :instance="curUser"
      :roles="roles"
      :orgs="colleges"
      @modified="getList"
    ></modify-user>
  </div>
</template>

<script>
import ModifyUser from "../components/ModifyUser";
import { ABLE_TYPE } from "@/constants/enumerate";
import {
  userListPage,
  ableUser,
  resetPwd,
  userRoleListPage,
  collegeQuery,
} from "../api";
// import { logout } from "@/modules/login/api";

export default {
  name: "user-manage",
  components: { ModifyUser },
  data() {
    return {
      filter: {
        loginName: "",
        realName: "",
        enable: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      visible: false,
      ABLE_TYPE,
      roles: [],
      roleMap: {},
      colleges: [],
      collegeMap: {},
      users: [],
      curUser: {},
      loading: false,
    };
  },
  async mounted() {
    await this.getRoleList();
    await this.getCollegeList();
    this.getList();
  },
  methods: {
    async getRoleList() {
      const data = await userRoleListPage();
      this.roles = data || [];
      // this.roles = this.roles.filter(item => item.type !== "ADMIN");
      let roleMap = {};
      this.roles.forEach((item) => {
        roleMap[item.id] = item.name;
      });
      this.roleMap = roleMap;
    },
    async getCollegeList() {
      const res = await collegeQuery();
      this.colleges = res || [];

      let collegeMap = {};
      this.colleges.forEach((item) => {
        collegeMap[item.id] = item.name;
      });
      this.collegeMap = collegeMap;
    },
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (datas.enable !== null && datas.enable !== "")
        datas.enable = !!datas.enable;
      const data = await userListPage(datas);
      this.users = data.records.map((item) => {
        item.roleName = this.roleMap[item.roleId];
        item.orgName = this.collegeMap[item.orgId];
        return item;
      });
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toEnable(row) {
      // 自己不可以启用/禁用自己
      const userId = this.$ls.get("user", { id: "" }).id;
      if (row.id === userId) {
        this.$message.error("不可以启用/禁用自己！");
        return;
      }

      const action = row.enable ? "禁用" : "启用";
      this.$confirm(`确定要${action}用户【${row.realName}】吗?`, "提示", {
        type: "warning",
      })
        .then(async () => {
          const enable = !row.enable;
          await ableUser({
            id: row.id,
            enable,
          });
          row.enable = enable;
          this.$message.success("操作成功！");
        })
        .catch(() => {});
    },
    toEdit(row) {
      this.curUser = row;
      this.$refs.ModifyUser.open();
    },
    toAdd() {
      this.curUser = {};
      this.$refs.ModifyUser.open();
    },
    async toResetPwd(row) {
      const result = await this.$confirm(
        `确定要重置用户【${row.realName}】密码吗?`,
        "提示",
        {
          type: "warning",
        }
      );
      if (result !== "confirm") return;

      await resetPwd(row.id);
      this.$message.success("密码重置成功！");

      // 修改自己时，会强制重新登录
      // const userId = this.$ls.get("user", { id: "" }).id;
      // if (row.id !== userId) return;
      // this.toLogout();
    },
    // async toLogout() {
    //   await logout();
    //   this.$ls.clear();
    //   this.$router.push({ name: "Login" });
    //   this.$message.info("您的密码已经变更，请重新登录系统！");
    // },
  },
};
</script>
