<template>
  <el-row class="row-bg" justify="center">
    <el-col :span="20">
      <el-button link type="primary" @click="dialogTableVisible = true"
      >添加公告</el-button>
      <el-dialog v-model="dialogTableVisible" title="新建标题">
        <el-form :model="formData" ref="vForm"  label-position="left" label-width="80px"
                 size="default" >
              <el-form-item label="公告标题" prop="title">
                <el-input v-model="formData.title" placeholder="请输入公告标题"></el-input>
              </el-form-item>

              <el-form-item label="公告内容" prop="content">
                <el-input :rows="4" type="textarea" v-model="formData.content" placeholder="请输入公告内容"></el-input>
              </el-form-item>
          <el-button type="primary" @click="submitNotice">提交</el-button>
        </el-form>
      </el-dialog>


      <el-table :data="data" style="width: 100%">
        <el-table-column label="标题" prop="title"/>
        <el-table-column label="内容" prop="content"/>
        <el-table-column label="时间" prop="created_at"/>
        <el-table-column fixed="right" label="Operations" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleClick(scope.row)"
          >删除</el-button>
        </template>
        </el-table-column>

      </el-table>
    </el-col>
  </el-row>
</template>


<script>
import axios from "axios";
import * as dayjs from 'dayjs';
import {ElNotification} from "element-plus";
import { reactive, ref } from 'vue'

export default {
  data(){
    return{
      formData:{
        title:'',
        content:'',
      },
      data:[],
      dialogTableVisible:false,
    }
  },

  mounted() {

    axios.get('/api/v1/notice').then(res => {
      if (res.data.code === 200) {
        console.log(res.data.data);
        this.data = res.data.data;
        this.data.forEach(function(item,index){
          item.created_at = dayjs(item.created_at).format('YYYY-MM-DD HH:mm:ss');
        })
        this.data.reverse();
      }
    })
  },
  methods:{
    submitNotice(){
      axios.post('/api/v1/admin/notice',this.formData).then(res => {
        if (res.data.code === 200) {
          this.dialogTableVisible = false;
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          window.location.reload()
        }
      })
    },
    handleClick(row){
      axios.delete('/api/v1/admin/notice/'+row.id).then(res => {
        if (res.data.code === 200) {
          this.data.splice(this.data.indexOf(row),1);
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        }
      })
    }
  }
}
</script>
