<template>
  <div class="user-manage">
    <div class="part-box part-box-filter">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="所属机构：">
            <org-select
              v-model="filter.orgId"
              placeholder="所属机构"
            ></org-select>
          </el-form-item>
          <el-form-item label="关键词：" label-width="75px">
            <el-input
              style="width: 180px"
              v-model.trim="filter.userInfo"
              placeholder="用户名/姓名/手机号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="角色：" label-width="55px">
            <el-select
              v-model="filter.roleId"
              style="width: 142px"
              placeholder="角色"
              filterable
              clearable
            >
              <el-option
                v-for="item in roles"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </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>
        </template>

        <el-form-item label-width="0px">
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="box-justify">
        <div>
          <el-button
            v-if="checkPrivilege('button', 'SyncUser')"
            type="primary"
            icon="el-icon-refresh"
            :loading="loading"
            @click="toSyncUser"
            >同步用户</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'export')"
            type="primary"
            icon="el-icon-download"
            :loading="loading"
            @click="toExportUser"
            >导出</el-button
          >
        </div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'import')"
            type="success"
            icon="el-icon-upload2"
            @click="toImport"
            >导入</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'import')"
            type="primary"
            icon="el-icon-s-order"
            @click="toDataTask"
            >导入结果查询</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'add')"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="toAdd"
            >新增</el-button
          >
        </div>
      </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="loginName" label="用户名/工号"></el-table-column>
        <el-table-column
          prop="realName"
          label="姓名"
          width="120"
        ></el-table-column>
        <el-table-column prop="mobileNumber" label="手机号"></el-table-column>
        <el-table-column prop="orgName" label="所属机构"></el-table-column>
        <el-table-column prop="roles" label="角色">
          <template slot-scope="scope">
            {{ scope.row.roles | rolesFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="状态" width="80">
          <template slot-scope="scope">
            {{ scope.row.enable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="200px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'edit')"
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'enable')"
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'reset')"
              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, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <!-- ModifyUser -->
    <modify-user
      ref="ModifyUser"
      :instance="curUser"
      :roles="roles"
      @modified="getList"
    ></modify-user>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'import')"
      ref="ImportFile"
      title="导入用户"
      :upload-url="uploadUrl"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('user')"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="checkPrivilege('button', 'import')"
      ref="DataTaskDialog"
      task-type="USER_IMPORT"
    ></data-task-dialog>
  </div>
</template>

<script>
import ModifyUser from "../components/ModifyUser";
import ImportFile from "../../../components/ImportFile.vue";
import { ABLE_TYPE } from "@/constants/enumerate";
import {
  userListPage,
  ableUser,
  deleteUser,
  resetPwd,
  userRoleListPage,
  syncUserToEcs,
  exportUser,
} from "../api";
import { downloadByApi } from "@/plugins/download";
import templateDownload from "@/mixins/templateDownload";

// import { logout } from "@/modules/login/api";

export default {
  name: "user-manage",
  components: { ModifyUser, ImportFile },
  mixins: [templateDownload],
  data() {
    return {
      filter: {
        orgId: "",
        userInfo: "",
        roleId: "",
        enable: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      visible: false,
      ABLE_TYPE,
      roles: [],
      users: [],
      curUser: {},
      loading: false,
      // import
      uploadUrl: "/api/admin/sys/user/import",
      dfilename: "用户导入模板.xlsx",
    };
  },
  mounted() {
    this.getRoleList();
    this.getList();
  },
  methods: {
    async getRoleList() {
      if (
        !this.checkPrivilege("button", "add") &&
        !this.checkPrivilege("link", "edit")
      )
        return;

      const data = await userRoleListPage();
      this.roles = data || [];
      this.roles = this.roles.filter((item) => item.type !== "ADMIN");
    },
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;
      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;
      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 toDelete(row) {
      // 自己不可以删除自己
      const userId = this.$ls.get("user", { id: "" }).id;
      if (row.id === userId) {
        this.$message.error("不可以删除自己");
        return;
      }

      this.$confirm(`确定要删除用户【${row.realName}】吗?`, "提示", {
        type: "warning",
      })
        .then(async () => {
          await deleteUser(row.id);
          this.$message.success("操作成功！");
          this.getList();
        })
        .catch(() => {});
    },
    async toResetPwd(row) {
      await resetPwd(row.id);
      this.$message.success("密码重置成功！");

      // 修改自己时，会强制重新登录
      // const userId = this.$ls.get("user", { id: "" }).id;
      // if (row.id !== userId) return;
      // this.toLogout();
    },
    async toSyncUser() {
      if (this.loading) return;
      this.loading = true;
      const res = await syncUserToEcs().catch(() => {});
      this.loading = false;

      if (!res) return;
      this.$message.success("同步任务已经提交！");
    },
    async toExportUser() {
      if (this.loading) return;

      this.loading = true;
      const res = await downloadByApi(() => {
        return exportUser(this.filter);
      }, "").catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.loading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // async toLogout() {
    //   await logout();
    //   this.$ls.clear();
    //   this.$router.push({ name: "Login" });
    //   this.$message.info("您的密码已经变更，请重新登录系统！");
    // },
    // import
    toImport() {
      this.$refs.ImportFile.open();
    },
    toDataTask() {
      this.$refs.DataTaskDialog.open();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.getList();
    },
  },
};
</script>
