<template>
  <div>
    <div class="container">
      <el-button
        type="primary"
        style="margin-bottom: 10px"
        @click="dialogVisible = true"
        size="mini"
        >添加人员</el-button
      >
      <el-table :data="tableData" max-height="800" stripe style="width: 100%">
        <el-table-column prop="userName" label="用户名"> </el-table-column>
        <el-table-column prop="chineseName" label="昵称"> </el-table-column>
        <el-table-column prop="identity" label="身份"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="mini"
              @click="handleDel(scope.row)"
              type="danger"
              :disabled="scope.row.identity == 'admin'"
              >删除</el-button
            >
            <el-button size="mini" @click="handleDesc(scope.row)" type="primary"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="dialogVisible" width="400px" @close="dialogClose">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="refruleForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="userName">
          <el-input v-model="ruleForm.userName" :disabled="idEdit"></el-input>
        </el-form-item>
        <el-form-item label="中文名称" prop="chineseName">
          <el-input v-model="ruleForm.chineseName"></el-input>
        </el-form-item>
        <el-form-item label="身份" prop="identity">
          <el-select v-model="ruleForm.identity">
            <el-option key="1" value="user" label="普通用户" />
            <el-option key="2" value="superuser" label="超级用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="passWord" v-if="!idEdit">
          <el-input type="password" v-model="ruleForm.passWord"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassWord" v-if="idEdit">
          <el-input type="password" v-model="ruleForm.newPassWord"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(refruleForm)"
            >确认</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  registerRequest,
  getUserList,
  editRequest,
  deleteUser,
} from "/@/api/api.js";
import dayjs from "dayjs";
import { JSEncrypt } from "jsencrypt";
import BASE from "@tools/basicTool";
onMounted(() => {
  userList();
});
const refruleForm = ref(null);
const dialogVisible = ref(false);
const idEdit = ref(false);
const rules = reactive({
  userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
  chineseName: [{ required: true, message: "请输入中文名称", trigger: "blur" }],
  passWord: [
    { required: true, validator: BASE.elCkeck.validatePass, trigger: "blur" },
  ],
  newPassWord: [
    { required: true, validator: BASE.elCkeck.validatePass, trigger: "blur" },
  ],
});
const ruleForm = reactive({
  userName: "",
  chineseName: "",
  passWord: "",
  newPassWord: "",
  identity: "user",
  id: "",
});
let tableData = ref([]);
// 利用jsencrypt.js进行RSA加密
const encryptionByPublickey = (formData) => {
  let key = sessionStorage.getItem("publicKey");
  var encrypt = new JSEncrypt();
  encrypt.setPublicKey(key);
  var result = encrypt.encrypt(JSON.stringify(formData));
  return result;
};
const toUtf8 = (str) => {
  return new TextEncoder("utf8").encode(str);
};
//获取user列表
const userList = async () => {
  const data = await getUserList();
  console.warn(data);
  tableData.value = data.filter((e) => {
    return e.identity != "admin";
  });
};

//编辑
const handleDesc = (item) => {
  console.warn(item);
  idEdit.value = true;
  dialogVisible.value = true;
  ruleForm.id = item.id;
  ruleForm.userName = item.userName;
  ruleForm.chineseName = item.chineseName;
  ruleForm.passWord = item.passWord;
  ruleForm.identity = item.identity;
};
//删除
const handleDel = (item) => {
  ElMessageBox.confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteUser(item.id);
      if (!res.success) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success(res.msg);
      }
      userList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
//添加
const release = async () => {
  let requestWrapper = {
    publicKey: sessionStorage.getItem("publicKey"),
    token: sessionStorage.getItem("token"),
    data: encryptionByPublickey(ruleForm),
  };
  const res = await registerRequest(requestWrapper);
  dialogVisible.value = false;
  if (res.success) {
    ElMessage.success(res.msg);
    userList();
  } else {
    ElMessage.error(res.msg);
  }
};
// edit
const edit = async () => {
  let requestWrapper = {
    publicKey: sessionStorage.getItem("publicKey"),
    token: sessionStorage.getItem("token"),
    data: encryptionByPublickey(ruleForm),
  };
  const res = await editRequest(requestWrapper);
  dialogVisible.value = false;
  if (res.success) {
    ElMessage.success(res.msg);
  } else {
    ElMessage.error(res.msg);
  }
  userList();
};
//表单提交
const submitForm = (formEl) => {
  formEl.validate((valid) => {
    if (valid) {
      if (idEdit.value == true) {
        edit();
      } else {
        release();
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
//表单重置
const resetForm = () => {
  refruleForm.value.resetFields();
  // ruleForm.userName = "";
  ruleForm.chineseName = "";
  ruleForm.passWord = "";
  ruleForm.newPassWord = "";
};

const dialogClose = () => {
  resetForm();
  idEdit.value = false;
};
// 时间格式化
const createdtime = (val) => {
  return dayjs(val).format("YYYY-MM-DD:HH:mm:ss");
};
</script>
<style lang="less" scoped>
.container {
  padding: 20px;
  box-sizing: border-box;
}
</style>