<!--
 * @Author: Billy
 * @Date: 2021-06-19 00:51:47
 * @LastEditors: Billy
 * @LastEditTime: 2022-01-04 17:41:04
 * @Description: 用户列表
-->

<template>
  <div class="user">
    <el-table :data="userInfo.rows" style="width: 100%">
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column
        prop="name"
        label="用户名"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="Organization.name"
        label="部门"
        width="100"
        :formatter="departmentNameFormatter"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="softDelete"
        label="禁用"
        width="80"
        :formatter="booleanFormatter"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        :formatter="timeFormatter"
      ></el-table-column>
      <!-- <el-table-column
        prop="modifyTime"
        label="修改时间"
        width="180"
        :formatter="timeFormatter"
      ></el-table-column> -->
      <el-table-column label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            class="btn-icon"
            icon="el-icon-edit"
            type="text"
            @click="onEditBtnClick(scope.$index, scope.row)"
          ></el-button>

          <el-button
            class="btn-icon"
            icon="el-icon-delete"
            type="text"
            @click="onDelBtnClick(scope.$index, scope.row)"
          ></el-button>

          <el-button
            class="btn-icon"
            icon="el-icon-rank"
            type="text"
            @click="onMoveBtnClick(scope.$index, scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="userInfo.totalCount"
        :page-size="userInfo.pageSize"
        :current-page.sync="userInfo.pageNum"
      ></el-pagination>
    </div>

    <el-dialog
      v-if="editingUser"
      title="修改用户"
      :visible.sync="isDialEditUserVisible"
      width="30%"
      :before-close="onDialEditUserClose"
    >
      <el-form
        :model="editingUser"
        :rules="userRules"
        ref="edit-user-form"
        label-width="70px"
        class="edit-user-form"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editingUser.name"></el-input>
        </el-form-item>
        <el-form-item label="是否禁用">
          <el-radio-group v-model="editingUser.softDelete">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialEditUserVisible = false">退 出</el-button>
        <el-button type="primary" @click="onEditUserConfirmClick"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="移动用户"
      width="50%"
      :visible.sync="isDialMoveUserVisible"
      :before-close="onDialMoveUserClose"
      @open="onDialMoveUserOpen"
    >
      <UserMove
        ref="user-move-form"
        :user="editingUser"
        :treeData="orgTreeData"
        @cancel="isDialMoveUserVisible = false"
        @success="onUserMoveSuccess"
      />
    </el-dialog>
  </div>
</template>
<script>
import UserMove from "../../../components/Rbac/User/UserMove.vue";
import UserBiz from "../../../biz/Rbac/User.js";
import OrgAndUserBiz from "../../../biz/Rbac/OrgAndUser.js";
import DateHelper from "../../../util/DateHelper.js";

export default {
  components: { UserMove },
  props: {
    orgId: { type: Number }, // orgId是-1的时候代表根节点
    orgTreeData: { type: Array }, // 组织架构树结构，主要用于移动用户
  },
  data() {
    return {
      isDialEditUserVisible: false,
      userRules: {
        name: [{ required: true, message: "请填写用户名", trigger: "none" }],
        password: [{ required: true, message: "请填写密码", trigger: "none" }],
      },
      editingUser: null,
      editingUserPrototype: null,
      userInfo: {
        rows: [],
        totalCount: 0,
        pageSize: 10,
        pageNum: 1,
      },
      isDialMoveUserVisible: false, // 移动用户对话框是否显示
    };
  },
  computed: {
    // 共几页
    pageCount: function () {
      return Math.ceil(this.userInfo.totalCount / this.userInfo.pageSize);
    },
    myOrgId: function () {
      return this.orgId < 0 ? null : this.orgId;
    },
  },
  watch: {
    "userInfo.pageNum": function (newVal, oldVal) {
      this.getCurrPageUsers();
    },
    orgId: function (newVal, oldVal) {
      this.getCurrPageUsers();
    },
  },
  mounted() {
    this.getCurrPageUsers();
    // this.getAllRoles();
  },
  methods: {
    // 获取当前页面的用户信息列表
    async getCurrPageUsers() {
      // if (this.myOrgId === null) {
      //   // 查询所有用户
      //   UserBiz.findByPage(this.userInfo.pageSize, this.userInfo.pageNum).then(
      //     (result) => {
      //       this.userInfo.rows = result.rows;
      //       this.userInfo.totalCount = result.count;
      //     }
      //   );
      // } else {
      //   OrgAndUserBiz.findUsersByOrgIdAndByPage(
      //     this.myOrgId,
      //     this.userInfo.pageSize,
      //     this.userInfo.pageNum
      //   ).then((result) => {
      //     this.userInfo.rows = result.rows;
      //     this.userInfo.totalCount = result.count;
      //   });
      // }

      await OrgAndUserBiz.findUsersByOrgIdAndByPage(
        this.myOrgId,
        this.userInfo.pageSize,
        this.userInfo.pageNum
      ).then((result) => {
        this.userInfo.rows = result.rows;
        this.userInfo.totalCount = result.count;
      });
    },

    // table里每一row的“编辑”按钮被点击时
    onEditBtnClick(index, row) {
      this.editingUserPrototype = row;
      this.editingUser = JSON.parse(JSON.stringify(row));
      this.isDialEditUserVisible = true;
    },

    // “修改用户”的对话框的确定按钮被点击时
    onEditUserConfirmClick() {
      this.$refs["edit-user-form"].validate((valid) => {
        if (valid) {
          let user = {};
          for (const key in this.editingUser) {
            if (Object.hasOwnProperty.call(this.editingUser, key)) {
              if (this.editingUser[key] !== this.editingUserPrototype[key]) {
                user[key] = this.editingUser[key];
              }
            }
          }

          if (JSON.stringify(user) !== "{}") {
            user.id = this.editingUser.id;
            UserBiz.update(user)
              .then((count) => {
                if (count === 1) {
                  this.$message({
                    message: "用户修改成功",
                    type: "success",
                  });
                  this.isDialEditUserVisible = false;
                  this.getCurrPageUsers();
                }
              })
              .catch((err) => {
                this.$message({
                  message: err.message,
                  type: "error",
                });
              });
          } else {
            this.$message({
              message: "用户信息没有任何修改",
              type: "warning",
            });
          }
        }
      });
    },

    // “修改用户”的对话框的❌被点击时
    onDialEditUserClose(done) {
      done();
    },

    // table里每一row的“删除”按钮被点击时
    onDelBtnClick(index, row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          UserBiz.delById(row.id)
            .then((count) => {
              this.$message({
                type: "success",
                message: "用户删除成功",
              });
              this.getCurrPageUsers();
            })
            .catch((err) => {
              this.$message({
                message: err.message,
                type: "error",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    onMoveBtnClick(index, row) {
      this.editingUser = JSON.parse(JSON.stringify(row));
      // this.editingUser = row;
      this.isDialMoveUserVisible = true;
    },

    // 去到表格的最后一页(外部调用)
    async goToLastPage() {
      let userCount = await UserBiz.countAll();
      this.userInfo.totalCount = userCount;

      if (this.userInfo.pageNum === this.pageCount) {
        // 已在最后一页
        this.getCurrPageUsers();
      } else {
        // 未在最后一页
        this.userInfo.pageNum = this.pageCount;
        this.getCurrPageUsers();
      }
    },

    // “移动用户”的对话框的❌被点击时
    onDialMoveUserClose(done) {
      done();
    },

    // 当移动用户的对话框的open事件被触发时
    onDialMoveUserOpen() {
      let $refForm = this.$refs["user-move-form"];
      // 第一次打开dialog时，表单会不存在
      if ($refForm) {
        $refForm.updateForm();
      }
    },

    // 当移动用户的对话框里移动用户成功时
    async onUserMoveSuccess(currNodeData, targetParentData) {
      // TODO: 非常神奇，马上获取本页用户，被移动的用户还在；但是如果隔1秒获取，则被移动的用户已不在本页；而后端明明是等(await)用户保存成功后才返回的
      setTimeout(() => {
        this.getCurrPageUsers();
      }, 1000);
    },

    departmentNameFormatter(row, column, cellValue, index) {
      return cellValue ? cellValue : "-";
    },

    // 表格的布尔值格式器
    booleanFormatter(row, column, cellValue, index) {
      return cellValue ? "是" : "否";
    },

    // 表格的时间格式器
    timeFormatter(row, column, cellValue, index) {
      let date = new Date(cellValue);
      let dateStr = DateHelper.format(date, "yyyy-MM-dd hh:mm");
      return dateStr;
    },
  },
};
</script>
<style lang="scss" scoped>
.user {
  width: 100%;
  box-sizing: border-box;
  // padding: 10px;
  .el-table {
    .el-button {
      padding: 0px;
      &.btn-icon {
        color: #000;
        &:hover {
          color: #409eff;
        }
      }
    }
  }
  .pagination {
    margin-top: 8px;
    overflow: hidden;
    .el-pagination {
      float: right;
    }
  }
}
</style>

