<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="this.searchInfo" class="demo-form-inline">
        <el-form-item>
          <el-button size="mini" type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="openDialog">新增</el-button>
          <el-popover v-model:visible="deleteVisible" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="deleteVisible = false">取消</el-button>
              <el-button size="mini" type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
              <el-button icon="el-icon-delete" size="mini" type="danger" style="margin-left: 10px;">批量删除</el-button>
            </template>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <el-table
        ref="multipleTable"
        border
        stripe
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="日期" width="180">
        <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
      </el-table-column>
      <el-table-column label="操作人" prop="oper" width="120"/>
      <el-table-column label="标题" prop="title" width="280"/>
      <el-table-column label="副标题" prop="subtitle" width="220"/>
      <!--      <el-table-column label="内容" prop="text" width="120" />-->
      <el-table-column label="图片" prop="imgs" width="165">
        <template #default="scope">
          <img :src="scope.row.imgs.split('|')[0] " width="140"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="primary" icon="el-icon-edit" class="table-button"
                     @click="updateContent(scope.row)">变更
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 30, 50, 100]"
        :style="{float:'right',padding:'20px'}"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
    />
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="弹窗操作">
      <el-form :model="formData" label-position="right" label-width="80px">
        <el-form-item label="操作人:">
          <el-input v-model="formData.oper" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="标题:">
          <el-input v-model="formData.title" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="副标题:">
          <el-input v-model="formData.subtitle" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="内容:">
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" v-model="formData.text" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="图片:">
          <el-upload
              class="upload-demo"
              :action="`${path}/fileUploadAndDownload/upload`"
              :before-upload="checkFile"
              :headers="{ 'x-token': token }"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :on-remove="delFile"
              :file-list="formData.imgsList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  createContent,
  deleteContent,
  deleteContentByIds,
  updateContent,
  findContent,
  getContentList
} from '@/api/content' //  此处请自行替换地址
import infoList from '@/mixins/infoList'
import { mapGetters } from 'vuex'

const path = import.meta.env.VITE_BASE_API
export default {
  name: 'Content',
  mixins: [infoList],
  data() {
    return {
      path: path,
      listApi: getContentList,
      dialogFormVisible: false,
      type: '',
      deleteVisible: false,
      multipleSelection: [],
      searchInfo: {
        type: 'bulletin',
      },
      formData: {
        oper: '',
        title: '',
        text: '',
        subtitle: '',
        imgs: '',
        imgsList: [],
        type: 'bulletin',
      }
    }
  },
  computed: {
    ...mapGetters('user', ['userInfo', 'token'])
  },
  async created() {
    await this.getTableData()
  },
  methods: {
    // 条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteRow(row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteContent(row)
      })
    },
    async onDelete() {
      const ids = []
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      this.multipleSelection &&
      this.multipleSelection.map(item => {
        ids.push(item.ID)
      })
      const res = await deleteContentByIds({ids})
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        if (this.tableData.length === ids.length && this.page > 1) {
          this.page--
        }
        this.deleteVisible = false
        this.getTableData()
      }
    },
    async updateContent(row) {
      const res = await findContent({ID: row.ID})
      this.type = 'update'
      if (res.code === 0) {
        this.formData = res.data.recontent
        if (this.formData.imgs.length != 0) {
          var imgs = this.formData.imgs.split('|')
          var imgList = new Set();
          for (let img of imgs) {
            imgList.add({name: '图片', url: img})
          }
          this.formData.imgsList = Array.from(imgList)
        }
        this.dialogFormVisible = true
      }
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.formData = {
        oper: '',
        title: '',
        text: '',
        imgs: '',
        type: '',
      }
    },
    async deleteContent(row) {
      const res = await deleteContent({ID: row.ID})
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getTableData()
      }
    },
    async enterDialog() {
      let res
      switch (this.type) {
        case 'create':
          res = await createContent(this.formData)
          break
        case 'update':
          res = await updateContent(this.formData)
          break
        default:
          res = await createContent(this.formData)
          break
      }
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '创建/更改成功'
        })
        this.closeDialog()
        this.getTableData()
      }
    },
    openDialog() {
      this.type = 'create'
      this.dialogFormVisible = true
    },
    checkFile(file) {
      this.fullscreenLoading = true
      const isJPG = file.type === 'image/jpeg'
      const isPng = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG或png 格式!')
        this.fullscreenLoading = false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        this.fullscreenLoading = false
      }
      return (isPng || isJPG) && isLt2M
    },
    uploadSuccess(res) {
      this.fullscreenLoading = false
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '上传成功'
        })
        if (this.formData.imgs.length > 0) {
          this.formData.imgs = this.formData.imgs + '|' + res.data.file.url
        } else {
          this.formData.imgs = res.data.file.url
        }
      } else {
        this.$message({
          type: 'warning',
          message: res.msg
        })
      }
    },
    uploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      })
      this.fullscreenLoading = false
    },
    delFile(file, fileList) {
      if (fileList.length != 0) {
        var fileArr = new Set()
        for (let file of fileList) {
          fileArr.add(file.url)
        }
        this.formData.imgs = Array.from(fileArr).join('|')
      } else {
        this.formData.imgs = '';
      }
    }
  },
}
</script>

<style>
</style>
