<template>
  <div v-loading.fullscreen.lock="fullscreenLoading">
    <div class="gva-table-box">
      <warning-bar title="点击“文件名/备注”可以编辑文件名或者备注内容。" />
      <div class="gva-btn-list">
        <upload-common category="media" label="直接上传" @on-success="uploadSuccess" @on-failure="uploadFailure"
          @on-before-upload="beforeUpload" />
        <upload-image category="media" label="图片压缩上传" :file-size="512" :max-w-h="1080" @on-success="uploadSuccess"
          @on-failure="uploadFailure" @on-before-upload="beforeUpload" />
        <cropper-img btn-type="primary" :img-width="1080" :img-height="800" category="media" crop-type="max"
          @on-success="uploadSuccess" />
        <el-select v-model="search.category" clearable placeholder="请选择分类" style="width: 350px;"
          @clear="() => { search.category = undefined }">
          <el-option v-for="(item, key) in mediaFileCategoryOpts" :key="key" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="search.keyword" class="keyword" placeholder="请输入文件名或备注" clearable />
        <el-button type="primary" icon="search" @click="getTableData">查询</el-button>
      </div>

      <el-table :data="tableData">
        <el-table-column align="left" fixed label="预览" width="150">
          <template #default="scope">
            <el-image v-if="isImageTag(scope.row.tag)" :src="getUrl(scope.row.url)" class="gva-image" fit="contain"
              :preview-src-list="[getUrl(scope.row.url)]" :preview-teleported="true"
              style="width: 120px; height: 100px;" />
            <video-viewer v-else-if="isVideoTag(scope.row.tag)" width="120px" height="100px" :url="scope.row.url" />
            <div v-else class="gva-media-box" style="width: 120px; height: 100px;">
              <el-icon :size="25">
                <Document />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="文件名/备注" prop="name" min-width="280" class-name="gva-text-truncate">
          <template #default="scope">
            <div class="name" @click="editFileNameFunc(scope.row)">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="链接" prop="url" min-width="300" class-name="gva-text-truncate">
          <template #default="scope">
            <div>{{ scope.row.url }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="分类" prop="kind" min-width="140">
          <template #default="scope">
            {{ filterDict(scope.row.category, mediaFileCategoryOpts) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="标签" prop="tag" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.tag === 'jpg' ? 'info' : 'success'" disable-transitions>
              {{ scope.row.tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="日期" prop="UpdatedAt" width="180">
          <template #default="scope">
            <div>{{ formatDate(scope.row.UpdatedAt) }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="80">
          <template #default="scope">
            <!-- <el-button icon="download" type="primary" link @click="downloadFile(scope.row)">下载</el-button> -->
            <el-button icon="delete" type="danger" link @click="deleteFileFunc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[10, 30, 50, 100]"
          :style="{ float: 'right', padding: '20px' }" :total="total" layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { getUrl, isImageTag, isVideoTag } from '@/utils/image'
import { getFileList, deleteFile, editFileName } from '@/api/mediaFile'
import { downloadImage } from '@/utils/downloadImg'
import UploadImage from '@/components/upload/image.vue'
import UploadCommon from '@/components/upload/common.vue'
import VideoViewer from '@/components/video/videoViewer.vue'
import CropperImg from '@/components/upload/cropperImg.vue'
import { getDictFunc, formatDate, filterDict } from '@/utils/format'
import WarningBar from '@/components/warningBar/warningBar.vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'MediaFile',
})

const mediaFileCategoryOpts = ref([])
// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
  mediaFileCategoryOpts.value = await getDictFunc('mediaFileCategory')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

const path = ref(import.meta.env.VITE_BASE_API)
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const search = ref({})
const tableData = ref([])
const fullscreenLoading = ref(false)

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const beforeUpload = () => {
  fullscreenLoading.value = true
}

const uploadSuccess = () => {
  fullscreenLoading.value = false
  getTableData()
}

const uploadFailure = () => {
  fullscreenLoading.value = false
}

// 查询
const getTableData = async () => {
  const table = await getFileList({ page: page.value, pageSize: pageSize.value, ...search.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}
getTableData()

const deleteFileFunc = async (row) => {
  ElMessageBox.confirm('此操作将永久删除文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await deleteFile({ ID: row.ID })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
        if (tableData.value.length === 1 && page.value > 1) {
          page.value--
        }
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const downloadFile = (row) => {
  if (row.url.indexOf('http://') > -1 || row.url.indexOf('https://') > -1) {
    downloadImage(row.url, row.name)
  } else {
    downloadImage(path.value + '/' + row.url, row.name)
  }
}

/**
 * 编辑文件名或者备注
 * @param row
 * @returns {Promise<void>}
 */
const editFileNameFunc = async (row) => {
  ElMessageBox.prompt('请输入文件名或者备注', '编辑', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '不能为空',
    inputValue: row.name
  }).then(async ({ value }) => {
    row.name = value
    const res = await editFileName(row)
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '编辑成功!',
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消修改'
    })
  })
}
</script>

<style scoped>
.name {
  cursor: pointer;
}
</style>
