<template>
<div class="page-wrapper">
  <el-alert type="info" show-icon :closable="false" style="margin-bottom: 10px" >
    <template #title>上传要求</template>
    图片格式为{{allowUploadExt.join('、')}}，文件大小不超过10MB。
  </el-alert>
  <el-form inline :model="search">
    <el-form-item label="文件名">
      <el-input v-model="search.name" />
    </el-form-item>
    <el-form-item label="宽度" >
      <el-input v-model="search.widthMin" type="number" style="vertical-align: middle;" >
        <template #prepend>≥</template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-input v-model="search.widthMax" type="number" style="vertical-align: middle;" >
        <template #prepend>≤</template>
      </el-input>
    </el-form-item>
    <el-form-item label="高度" >
      <el-input v-model="search.heightMin" type="number" style="vertical-align: middle;" >
        <template #prepend>≥</template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-input v-model="search.heightMax" type="number" style="vertical-align: middle;" >
        <template #prepend>≤</template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="btn-container">
    <el-upload
      action="/api/v2/photoWall/upload"
      accept="image/jpeg,image/png"
      name="image"
      :headers="{token: store.state.loginInfo.token}"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :on-error="uploadError" 
      auto-upload
      :show-file-list="false"
      style="display: inline-block;margin-right: 10px;">
      <el-button type="primary" icon="Upload" :loading="isUploading">上传图片</el-button>
    </el-upload>
    <el-button type="danger" @click="deleteAll" style="vertical-align: bottom">批量删除</el-button>
    <div class="search-btn">
      <el-button type="primary" @click="loadDataBase(true)" icon="Search">搜索</el-button>
      <el-button @click="reset" icon="RefreshLeft">重置</el-button>
    </div>
  </div>
   
  <div class="table-container">
    <el-table :data="photowallData" v-loading="loading" stripe @selection-change="dataSelect">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="md5" label="md5" width="300" />
      <el-table-column prop="thumbnail" label="缩略图" />
      <el-table-column prop="width" label="宽度" width="70" />
      <el-table-column prop="height" label="高度" width="70" />
      <el-table-column label="操作" width="100" >
        <template #default="scope">
          <el-button link icon="View" plain @click="preview(scope.row)" title="预览"></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"
      :current-page="search.pageNum"
      :total="total"
      @size-change="pageSizeChange"
      @current-change="pageChange">
    </el-pagination>
  </div>
</div>
</template>
<script setup lang="ts">
import { ref, h } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MsgResult, Page } from '@/model/common.dto'
import { useBaseList } from '@/model/baselist'
import PhotoWallModel from '@/model/api/photowall'
import http from '@/utils/http'

class PhotoWallPage extends Page {
  name?: string
  widthMin?: number = 0
  widthMax?: number = 0
  heightMin?: number = 0
  heightMax?: number = 0
  reset() {
    super.reset()
    this.name = undefined
    this.widthMin = 0
    this.widthMax = 0
    this.heightMin = 0
    this.heightMax = 0
  }
}

const store = useStore()
const { loading, total, search, setLoadData, loadDataBase, reset, pageChange, pageSizeChange } = useBaseList(new PhotoWallPage())

const allowUploadExt = ['jpg', 'jpeg', 'png']
const photowallData = ref([])
const isUploading = ref(false)

let selectedData: string[] = []

async function loadData() {
  loading.value = true
  const data = await http.get<PhotoWallPage, any>('/api/v2/photoWall/list', {params: search})
  selectedData = []
  loading.value = false
  total.value = data.total
  photowallData.value = data.data
}
setLoadData(loadData)

function deleteAll() {
  if (!selectedData || !selectedData.length) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(`是否确认删除选中的${selectedData.length}条数据？`, '确认删除', {type: 'warning'}).then(async () => {
    await http.delete('/api/v2/photoWall/delete', {params: {_ids: selectedData}})
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}
function dataSelect(selection: PhotoWallModel[]) {
  selectedData = selection.map(item => item._id)
}
function beforeUpload(file: File): boolean {
  if (file.size > 10 << 20) {
    ElMessage.warning('文件大小超过10MB')
    return false
  }
  isUploading.value = true
  return true
}
function uploadSuccess(response: MsgResult) {
  if (response.code === 0) {
    ElMessage.success(response.message)
    loadData()
  } else {
    ElMessage.warning(response.message)
  }
  isUploading.value = false
}
function uploadError(error: Error) {
  isUploading.value = false
  ElMessage.error(error.message)
}
async function preview(row: PhotoWallModel) {
  const previewHeight = Math.floor(row.height * (500 / row.width))
  const pictureCdn = await http.get('/api/v2/common/config/picture_cdn')
  ElMessageBox({
    title: '图片预览',
    message: h('img', { style: `width:500px;height:${previewHeight}px;`, src: `${pictureCdn}/${row.name}` }, ''),
    showCancelButton: false,
    confirmButtonText: '关闭',
    customStyle: {width: '530px', maxWidth: 'unset'}
  }).catch(() => {})
}

// created
loadData()
</script>