<template>
<div class="page-wrapper">
  <el-form inline :model="search">
    <el-form-item label="文件名">
      <el-input v-model="search.name" />
    </el-form-item>
    <el-form-item label="宽度" >
      <el-input-number v-model="search.widthMin" :min="0" controls-position="right" step-strictly>
        <template #prefix>≥</template>
        <template #suffix>px</template>
      </el-input-number>
      <el-input-number v-model="search.widthMax" :min="0" controls-position="right" step-strictly>
        <template #prefix>≤</template>
        <template #suffix>px</template>
      </el-input-number>
    </el-form-item>
    <el-form-item label="高度" >
      <el-input-number v-model="search.heightMin" :min="0" controls-position="right" step-strictly>
        <template #prefix>≥</template>
        <template #suffix>px</template>
      </el-input-number>
      <el-input-number v-model="search.heightMax" :min="0" controls-position="right" step-strictly>
        <template #prefix>≤</template>
        <template #suffix>px</template>
      </el-input-number>
    </el-form-item>
  </el-form>
  <div class="btn-container">
    <el-upload
      :action="`${apiBase}/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-tooltip :content="`图片格式为${allowUploadExt.join('、')}，文件大小不超过10MB。`">
        <el-button type="primary" icon="Upload" :loading="isUploading" v-permission="'photoWall:save'" plain>上传图片</el-button>
      </el-tooltip>
    </el-upload>
    <el-button type="danger" @click="deleteAll" style="vertical-align: bottom" v-permission="'photoWall:delete'" plain>批量删除</el-button>
    <div class="search-btn">
      <el-button type="primary" @click="loadDataBase(true)" icon="Search" plain>搜索</el-button>
      <el-button @click="reset" icon="RefreshLeft" plain>重置</el-button>
    </div>
  </div>
   
  <el-table class="table-container" :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" @click="preview(scope.row)" title="预览"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <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>
  <el-image-viewer
    v-if="previewVisible"
    :url-list="previewUrlList"
    :initial-index="previewIndex"
    @close="previewVisible = false"
  />
</div>
</template>
<script setup lang="ts">
import { ref } 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 | null
  widthMax!: number | null
  heightMin!: number | null
  heightMax!: number | null
  reset() {
    super.reset()
    this.name = undefined
    this.widthMin = null
    this.widthMax = null
    this.heightMin = null
    this.heightMax = null
  }
}

const store = useStore()
const apiBase = process.env.VUE_APP_API_BASE as string
const { loading, total, search, setLoadData, loadDataBase, reset, pageChange, pageSizeChange } = useBaseList(new PhotoWallPage())

const allowUploadExt = ['jpg', 'jpeg', 'png']
const photowallData = ref<PhotoWallModel[]>([])
const isUploading = ref(false)
const previewVisible = ref(false)
const previewUrlList = ref<string[]>([])
const previewIndex = ref(0)

let selectedData: string[] = []

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

function deleteAll() {
  if (!selectedData || !selectedData.length) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(`是否确认删除选中的${selectedData.length}条数据？`, '确认删除', {type: 'warning'}).then(async () => {
    await http.delete('/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 pictureCdn = await http.get('/common/config/picture_cdn')
  const index = photowallData.value.findIndex(item => item._id === row._id)
  previewUrlList.value = photowallData.value.map(item => `${pictureCdn}/${item.name}`)
  previewIndex.value = index >= 0 ? index : 0
  previewVisible.value = true
}

// created
loadData()
</script>