<template>
<div>
  <el-form inline :model="search" @submit.prevent>
    <el-form-item label="内容：">
      <el-input size="small" v-model="search.content" />
    </el-form-item>
    <el-form-item label="类型：">
      <el-select size="small" v-model="search.type" multiple collapse-tags>
        <el-option v-for="item in typeList" :key="item.value" :value="item.value" :label="item.label" />
      </el-select>
    </el-form-item>
    <el-form-item label="创建时间：">
      <el-date-picker
        v-model="search.createdAt"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期" />
    </el-form-item>
  </el-form>
  <div class="btn-container">
    <el-button size="small" type="primary" @click="addModal = true">添加</el-button>
    <el-button size="small" type="danger" @click="deleteAll">删除</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="hitokotoData" v-loading="loading" stripe height="520" @selection-change="dataSelect">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="type" label="类型" width="180">
        <template #default="scope">
          {{ findTypeText(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="hitokoto" label="内容" />
      <el-table-column prop="from" label="来自" width="180"/>
      <el-table-column prop="creator" label="作者" width="180"/>
      <el-table-column prop="number" label="编号" width="70"/>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ datetimeFormat(scope.row.created_at) }}
        </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="新增一言" >
    <hitokoto-add ref="addForm" :typeList="typeList" :formData="formData" />
    <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 HitokotoAdd from './HitokotoAdd.vue'
import { Options } from 'vue-class-component'
import BaseList from '../../model/baselist'
import { Page } from '../../model/common.dto'
import HitokotoModel from '../../model/api/hitokoto'
import { AxiosResponse } from 'axios'
import { ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElPagination, ElDialog, ElSelect, ElOption, ElDatePicker, ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'

let selectedData: string[] = []
@Options({
  name: 'Hitokoto',
  components: { ElButton, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElPagination, ElDialog, ElSelect, ElOption, ElDatePicker, HitokotoAdd }
})
export default class Hitokoto extends BaseList<HitokotoPage> {
  private readonly addForm: any = ref('addForm')
  search = new HitokotoPage()
  typeList: {label: string, value: string}[] = []
  hitokotoData: HitokotoModel[] = []
  formData: {[propName:string]: string | null} = {}
  addModal: boolean = false

  async loadData() {
    this.loading = true
    const { data } = await this.$http.get<HitokotoPage, AxiosResponse<any>>('/api/hitokoto/list', {params:this.search})
    selectedData = []
    this.loading = false
    this.total = data.total
    this.hitokotoData = data.data
  }
  async save() {
    this.addForm.$refs.hitokotoForm.validate(async (valid: boolean) => {
      if(!valid) return
      this.modalLoading = true
      const { data } = await this.$http.post<any, AxiosResponse<any>>('/api/hitokoto/save', this.formData)
      this.modalLoading = false
      this.addModal = false
      ElMessage.success(data.message)
      this.loadData()
      // 清空表单
      this.formData = {}
    })
  }
  deleteAll() {
    if(!selectedData.length) {
      ElMessage.warning('请选择要删除的数据')
      return
    }
    ElMessageBox.confirm(`是否确认删除选中的${selectedData.length}条数据？`, '确认删除', {type: 'warning'}).then(async () => {
      const { data } = await this.$http.delete<any, AxiosResponse<any>>('/api/hitokoto/delete', {params:{_ids: selectedData}})
      ElMessage.success(data.message)
      this.loadData()
    }).catch(() => {})
  }
  dataSelect(selection: HitokotoModel[]) {
    selectedData = selection.map(item => item._id)
  }
  created() {
    this.loadData()
    this.$http.get('/api/common/config/hitokoto_type').then(({data}) => {
      this.typeList = data
    })
  }
  findTypeText(value: string): string | null {
    const type = this.typeList.find(item => item.value === value)
    return type ? type.label : null
  }
}

class HitokotoPage extends Page {
  content?: string
  type?: string
  createdAt?: [Date, Date]
  reset() {
    super.reset()
    this.content = undefined
    this.type = undefined
    this.createdAt = undefined
  }
}
</script>
