<template>
  <div class="user-manage">
    <div class="part-box part-box-filter">
      <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="55px">
          <el-select
            v-model="filter.roleCode"
            style="width: 142px;"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in roles"
              :key="item.roleCode"
              :value="item.roleCode"
              :label="item.roleName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态：" label-width="55px">
          <el-select
            v-model="filter.enable"
            style="width: 142px;"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(val, key) in ABLE_TYPE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label-width="0px">
          <el-button type="primary" icon="icon icon-search" @click="toPage(1)"
            >查询</el-button
          >
          <upload-button
            btn-icon="icon icon-share"
            btn-type="warning"
            btn-content="导入"
            :upload-url="uploadUrl"
            :format="['xls', 'xlsx']"
            :upload-data="uploadData"
            @upload-error="uplaodError"
            @upload-success="uploadSuccess"
          >
          </upload-button>
          <el-button icon="icon icon-download-act">
            <a :href="downloadUrl" download="用户导入模板.xlsx"
              >用户导入模板下载</a
            >
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="part-box">
      <el-table ref="TableList" :data="users" border stripe>
        <el-table-column
          type="index"
          label="序号"
          width="70"
          align="center"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="loginName" label="用户名"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column
          prop="courseNameCode"
          label="科目名称(编码)"
        ></el-table-column>
        <el-table-column prop="enable" label="状态">
          <template slot-scope="scope">
            {{ ABLE_TYPE[scope.row.enable + ""] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px">
          <template slot-scope="scope">
            <el-button
              class="btn-table-icon"
              type="text"
              :icon="
                scope.row.enable
                  ? 'icon icon-circle-stop'
                  : 'icon icon-circle-caret-right'
              "
              @click="toEnable(scope.row)"
              :title="scope.row.enable ? '禁用' : '启用'"
            ></el-button>
            <el-button
              class="btn-table-icon"
              type="text"
              icon="icon icon-edit"
              @click="toEdit(scope.row)"
              title="编辑"
            ></el-button>
            <el-button
              class="btn-table-icon"
              type="text"
              icon="icon icon-circle-lock"
              @click="toResetPwd(scope.row)"
              title="重置密码"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { ABLE_TYPE } from "@/constants/enumerate";
import { userListPage, ableUser, updatePwd, roleList } from "../api";
import UploadButton from "@/components/UploadButton";
import { AES } from "@/plugins/crypto";
import { logout } from "@/modules/login/api";

export default {
  name: "user-manage",
  components: { UploadButton },
  data() {
    return {
      filter: {
        loginName: "",
        roleCode: "",
        enable: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      visible: false,
      ABLE_TYPE,
      roles: [],
      users: [],
      downloadUrl: "/temps/用户导入模版.xlsx",
      // import
      uploadUrl: "/api/print/basic/user/add",
      uploadData: {
        schoolId: this.$ls.get("schoolId"),
        userId: this.$ls.get("user", { id: "" }).id
      }
    };
  },
  created() {
    this.getRoleList();
    this.getList();
  },
  methods: {
    indexMethod(index) {
      return (this.current - 1) * this.size + index + 1;
    },
    async getRoleList() {
      const data = await roleList();
      this.roles = data.records;
    },
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      const data = await userListPage(datas);
      this.users = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    async toEnable(row) {
      const enable = Number(!row.enable);
      await ableUser({
        id: row.id,
        enable
      });
      row.enable = enable;
    },
    toEdit(row) {
      this.$router.push({
        name: "UserEdit",
        params: {
          userId: row.id
        }
      });
    },
    async toResetPwd(row) {
      await updatePwd({
        id: row.id,
        newPassword: AES("123456")
      });
      this.$message.success("密码重置成功！");

      // 修改自己时，会强制重新登录
      const userId = this.$ls.get("user", { id: "" }).id;
      if (row.id !== userId) return;
      this.toLogout(userId);
    },
    async toLogout(userId) {
      await logout(userId);
      this.$ls.clear();
      this.$router.push({ name: "Login" });
      this.$message.info("您的密码已经变更，请重新登录系统！");
    },
    uplaodError(errorData) {
      this.$notify.error({ title: "错误提示", message: errorData.message });
    },
    uploadSuccess(res) {
      this.$message.success("上传成功！");
      this.getList();
    }
  }
};
</script>
