<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入账号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="queryParams.role" placeholder="请选择角色" clearable style="width: 160px">
          <el-option label="超级管理员" value="1" />
          <el-option label="普通用户" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>
    <br>

    <el-table v-loading="loading" :data="userList">
      <el-table-column label="账号" align="center" prop="username" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template #default="scope">
          <el-image
            v-if="scope.row.avatar"
            :src="getFilePrefix + scope.row.avatar"
            :preview-src-list="[getFilePrefix + scope.row.avatar]"
            preview-teleported
            fit="cover"
            style="width: 40px; height: 40px; border-radius: 50%; cursor: zoom-in"
          />
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" prop="role">
        <template #default="scope">
          <el-tag v-if="scope.row.role === '1'" type="danger">超级管理员</el-tag>
          <el-tag v-else type="info">普通用户</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">停用</el-tag>
          <el-tag v-else type="info">待审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-if="scope.row.status === 0"
            @click="toggleStatus(scope.row, 1)"
            icon="CloseBold"
          >停用</el-button>
          <el-button
            link
            type="primary"
            v-if="scope.row.status !== 0"
            @click="toggleStatus(scope.row, 0)"
            icon="CircleCheck"
          >启用</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog :title="title" v-model="open" width="650px" append-to-body :close-on-click-modal="false">
      <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username" placeholder="请输入账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="isAdd">
              <el-input v-model="form.password" placeholder="请输入密码" type="password" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
                <el-option label="超级管理员" value="1" />
                <el-option label="普通用户" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" :value="0" />
                <el-option label="停用" :value="1" />
                <el-option label="待审核" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar">
              <el-upload
                action="/api/files/upload"
                :headers="headers"
                name="file"
                :data="{filePath: 'avatar'}"
                list-type="picture-card"
                :file-list="avatarFileList"
                :limit="1"
                :on-success="handleAvatarSuccess"
                :on-remove="handleAvatarRemove"
                :on-exceed="handleAvatarExceed"
                :before-upload="beforeAvatarUpload"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdminUser">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listSysUser, getSysUser, addSysUser, updateSysUser, delSysUser } from "@/api/sysUser";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const headers = {};

const isAdd = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    nickname: null,
    role: null,
  },
  rules: {
    username: [
      { required: true, message: "账号不能为空", trigger: "blur" }
    ],
    nickname: [
      { required: true, message: "昵称不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    role: [
      { required: true, message: "角色不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const avatarFileList = ref([]);
const getFilePrefix = proxy.getFilePrefix;

function getList() {
  loading.value = true;
  listSysUser(queryParams.value).then(response => {
    userList.value = response.list;
    total.value = response.total;
    loading.value = false;
  });
}

function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    id: null,
    username: null,
    nickname: null,
    avatar: null,
    password: null,
    status: 0,
    role: '2',
    remark: null
  };
  const userRef = proxy.$refs["userRef"]
  if (userRef) {
    userRef.resetFields();
  }
  avatarFileList.value = [];
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  const queryRef = proxy.$refs["queryRef"]
  if (queryRef) {
    queryRef.resetFields();
  }
  handleQuery();
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
  isAdd.value = true;
}

function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSysUser(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户";
    isAdd.value = false;
    avatarFileList.value = form.value.avatar ? [{ name: '头像', url: getFilePrefix + form.value.avatar }] : [];
  });
}

function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {  // 添加
        addSysUser(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      } else {  // 更新
        const payload = { ...form.value };
        payload.password = undefined;
        updateSysUser(payload).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  proxy.$confirm('是否确认删除用户编号为"' + row.id + '"的数据项？').then(function() {
    return delSysUser(row.id);
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

function toggleStatus(row, nextVal) {
  const text = nextVal === 1 ? '是否要停用该用户？' : '是否要启用该用户？';
  proxy.$confirm(text).then(function() {
    return updateSysUser({ id: row.id, status: nextVal });
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

function handleAvatarSuccess(res, file, fileList) {
  form.value.avatar = res;
  avatarFileList.value = [{ name: file.name, url: getFilePrefix + form.value.avatar }];
  const userRef = proxy.$refs["userRef"];
  if (userRef) {
    userRef.validateField('avatar');
  }
}

function handleAvatarRemove() {
  form.value.avatar = null;
  avatarFileList.value = [];
}

function handleAvatarExceed(files, fileList) {
  proxy.$message({
    message: '只允许上传一张头像',
    type: 'warning'
  });
}

function beforeAvatarUpload(file) {
  const ok = file.size / 1024 / 1024 <= 5;
  if (!ok) {
    proxy.$message({
      message: '图片大小不能超过5MB',
      type: 'error'
    });
  }
  return ok;
}

getList();
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
.el-upload--picture-card {
  width: 100px;
  height: 100px;
}
.el-upload-list__item {
  width: 100px !important;
  height: 100px !important;
}
</style>
