<template>
<div>
  <el-form inline :model="search" @submit.prevent>
    <el-form-item label="用户名/昵称：">
      <el-input size="small" v-model="search.username" />
    </el-form-item>
  </el-form>
  <div class="btn-container">
    <el-button size="small" type="primary" @click="add">添加</el-button>
    <div class="search-btn">
      <el-button type="primary" @click="loadDataBase(true)" size="small" icon="el-icon-search">搜索</el-button>
      <el-button @click="reset" size="small" icon="el-icon-refresh-right">重置</el-button>
    </div>
  </div>
  <div class="table-container">
    <el-table :data="systemUserData" v-loading="loading" stripe height="520">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="realname" label="昵称" />
      <el-table-column prop="created_at" label="创建时间" >
        <template #default="scope">
          {{ datetimeFormat(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" label="更新时间" >
        <template #default="scope">
          {{ datetimeFormat(scope.row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button size="mini" plain @click="update(scope.row)">修改</el-button>
          <el-button type="danger" size="mini" plain @click="remove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page-container">
    <el-pagination background 
      :page-sizes="$store.state.pageSizeOpts"
      :layout="$store.state.pageLayout"
      :total="total"
      @size-change="pageSizeChange"
      @current-change="pageChange">
    </el-pagination>
  </div>
  <el-dialog v-model="addModal" :title="modalTitle" >
    <el-form ref="userForm" :model="formData" :rules="ruleValidate" :label-width="120">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" />
      </el-form-item>
      <el-form-item label="昵称" prop="realname">
        <el-input v-model="formData.realname" />
      </el-form-item>
      <el-form-item label="角色" prop="realname">
        <el-select v-model="formData.role_ids" multiple >
          <el-option v-for="role in roles" :key="role._id" :value="role._id" :label="role.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addModal = false">取消</el-button>
        <el-button type="primary" @click="save" :loading="modalLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</div>
</template>
<script lang="ts">
import { Options } from 'vue-class-component'
import BaseList from '../../model/baselist'
import { Page } from '../../model/common.dto'
import { SystemUserModel } from '../../model/system/system-user'
import { SystemRoleModel } from '../../model/system/system-role'
import { AxiosResponse } from 'axios'
import { ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElPagination, ElDialog, ElSelect, ElOption, ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'

@Options({
  name: 'SystemUser',
  components: { ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElPagination, ElDialog, ElSelect, ElOption }
})
export default class SystemUser extends BaseList<SystemUserPage> {
  private readonly userForm: any = ref('userForm')
  get ruleValidate() {
    return {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { validator: async (rule: object, value: string, callback: Function) => {
            const { data } = await this.$http.get<any, AxiosResponse<any>>('/api/system/user/exists', {params: {username: value, id: this.formData._id}})
            if(data.data.exists) {
              callback(new Error('用户名已存在'))
            } else {
              callback()
            }
          }, trigger: 'blur'
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 8, max: 16, message: '密码长度8~16位', trigger: 'blur' },
        { pattern: /^(?![\d]+$)(?![a-zA-Z]+$)(?![-=+_.,]+$)[\da-zA-Z-=+_.,]{8,16}$/, message: '密码由字母、数字、特殊字符中的任意两种组成', trigger: 'blur' }
      ],
    }
  }
  search = new SystemUserPage()
  systemUserData: SystemUserModel[] = []
  roles: SystemRoleModel[] = []
  addModal: boolean = false
  modalTitle: string | null = null
  formData: SystemUserModel = {
    _id: null,
    username: null,
    password: null,
    realname: null,
    role_ids: []
  }
  async loadData() {
    this.loading = true
    const { data } = await this.$http.get<{params: SystemUserPage}, AxiosResponse<any>>('/api/system/user/list', {params:this.search})
    this.loading = false
    this.total = data.total
    this.systemUserData = data.data
  }
  add() {
    // 清空表单
    this.formData = {
      _id: null,
      username: null,
      password: null,
      realname: null,
      role_ids: []
    }
    this.modalTitle = '新增用户'
    this.addModal = true
    this.clearValidate()
  }
  update(row: SystemUserModel) {
    this.formData._id = row._id
    this.formData.username = row.username
    this.formData.realname = row.realname
    this.formData.role_ids = row.role_ids
    this.modalTitle = '修改用户'
    this.addModal = true
    this.clearValidate()
  }
  async save() {
    console.log(this.userForm)
    this.userForm.validate(async (valid: boolean) => {
      if(!valid) return
      this.modalLoading = true
      const { data } = await this.$http.post<SystemUserModel, AxiosResponse<any>>('/api/system/user/save', this.formData)
      this.modalLoading = false
      this.addModal = false
      ElMessage.success(data.message)
      this.loadData()
    })
  }
  remove(row: SystemUserModel) {
    ElMessageBox.confirm(`是否确认删除 ${row.username} 用户？`, '确认删除', {type: 'warning'}).then(async () => {
      const { data } = await this.$http.delete<{params: {id: string}}, AxiosResponse<any>>('/api/system/user/delete', {params: {id: row._id}})
      if(data.status) {
        ElMessage.success(data.message)
        this.loadData()
      } else {
        ElMessage.warning(data.message)
      }
    }).catch(() => {})
  }
  created() {
    this.loadData()
    this.$http.get('/api/system/role/listAll').then(({data}) => {
      this.roles = data
    })
  }
  clearValidate() {
    this.$nextTick(() => {
      this.userForm.clearValidate()
    })
  }
}

class SystemUserPage extends Page {
  username?: string
  reset() {
    super.reset()
    this.username = undefined
  }
}
</script>