<template>
  <div>
    <el-form inline :model="search" @submit.prevent>
      <el-form-item label="角色名称/描述：">
        <el-input size="small" v-model="search.name" />
      </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="systemRoleData" v-loading="loading" stripe height="520">
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="methods" label="允许的请求类型" >
          <template #default="scope">
            <el-tag type="info" size="small" v-for="method in scope.row.methods" :key="method">{{method}}</el-tag>
          </template>
        </el-table-column>
        <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="roleForm" :model="formData" :rules="ruleValidate" :label-width="120">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="允许的请求类型">
          <el-select v-model="formData.methods" multiple >
            <el-option value="GET">GET</el-option>
            <el-option value="POST">POST</el-option>
            <el-option value="PUT">PUT</el-option>
            <el-option value="DELETE">DELETE</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="允许的URI">
          <el-input v-model="uri.include">
            <template #append>
              <el-button icon="el-icon-plus" @click="addUri('include_uri', uri.include)"></el-button>
            </template>
          </el-input>
          <el-tag v-for="uri in formData.include_uri" :key="uri" closable @close="removeUri('include_uri', uri)">{{uri}}</el-tag>
        </el-form-item>
        <el-form-item label="禁止的URI">
          <el-input v-model="uri.exclude">
            <template #append>
              <el-button icon="el-icon-plus" @click="addUri('exclude_uri', uri.exclude)"></el-button>
            </template>
          </el-input>
          <el-tag v-for="uri in formData.exclude_uri" :key="uri" closable @close="removeUri('exclude_uri', uri)">{{uri}}</el-tag>
        </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 { SystemRoleModel } from '../../model/system/system-role'
import { AxiosResponse } from 'axios'
import { ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElTag, ElPagination, ElDialog, ElSelect, ElOption, ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'

@Options({
  name: 'SystemRole',
  components: { ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElTag, ElPagination, ElDialog, ElSelect, ElOption }
})
export default class SystemRole extends BaseList<SystemRolePage> {
  private readonly roleForm: any = ref('roleForm')
  ruleValidate = {
    name: [
      { required: true, message: '请输入角色名称', trigger: 'blur' }
    ],
  }
  systemRoleData: SystemRoleModel[] = []
  search = new SystemRolePage()
  addModal: boolean  = false
  modalTitle: string | null = null
  uri: {
    include: string | null,
    exclude: string | null
  } = {
    include: null,
    exclude: null
  }
  formData: SystemRoleModel = {
    _id: null,
    name: null,
    description: null,
    methods: [],
    include_uri: [],
    exclude_uri: []
  }
  async loadData() {
    this.loading = true
    const { data } = await this.$http.get<{params: SystemRolePage}, AxiosResponse<any>>('/api/system/role/list', {params:this.search})
    this.loading = false
    this.total = data.total
    this.systemRoleData = data.data
  }
  created() {
    this.loadData()
  }
  add() {
    // 清空表单
    this.uri.include = null
    this.uri.exclude = null
    this.formData = {
      _id: null,
      name: null,
      description: null,
      methods: [],
      include_uri: [],
      exclude_uri: []
    }
    this.modalTitle = '新增角色'
    this.addModal = true
    this.clearValidate()
  }
  addUri(fieldName: 'include_uri' | 'exclude_uri', uri: string | null) {
    if(!uri) return
    if(this.formData[fieldName].indexOf(uri) === -1) {
      this.formData[fieldName].push(uri)
    }
  }
  removeUri(fieldName: 'include_uri' | 'exclude_uri', uri: string) {
    let index = this.formData[fieldName].indexOf(uri)
    if(index !== -1) {
      this.formData[fieldName].splice(index, 1)
    }
  }
  update(row: SystemRoleModel) {
    this.uri.include = null
    this.uri.exclude = null
    this.formData._id = row._id
    this.formData.name = row.name
    this.formData.description = row.description
    this.formData.methods = row.methods
    this.formData.include_uri = row.include_uri
    this.formData.exclude_uri = row.exclude_uri
    this.modalTitle = '修改角色'
    this.addModal = true
    this.clearValidate()
  }
  remove(row: SystemRoleModel) {
    ElMessageBox.confirm(`是否确认删除 ${row.name} 角色？`, '确认删除', {type: 'warning'}).then(async () => {
      const { data } = await this.$http.delete<{params: {id: string}}, AxiosResponse<any>>('/api/system/role/delete', {params: {id: row._id}})
      if(data.status) {
        ElMessage.success(data.message)
        this.loadData()
      } else {
        ElMessage.warning(data.message)
      }
    }).catch(() => {})
  }
  async save() {
    this.roleForm.validate(async (valid: boolean) => {
      if(!valid) return
      this.modalLoading = true
      const { data } = await this.$http.post<SystemRoleModel, AxiosResponse<any>>('/api/system/role/save', this.formData)
      this.modalLoading = false
      this.addModal = false
      ElMessage.success(data.message)
      this.loadData()
    })
  }
  clearValidate() {
    this.$nextTick(() => {
      this.roleForm.clearValidate()
    })
  }
}

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