<template>
  <el-drawer v-model="drawer" title="媒体库" direction="ltr" :size="props.size">
    <template #header>
      <div class="flex justify-between items-center">
        <span class="text-lg">媒体库</span>
      </div>
    </template>

    <div class="gva-btn-list">
      <upload-common :image-common="imageCommon" class="upload-btn-media-library" :category="props.category"
        @on-success="getTableData" />
      <el-tooltip effect="dark" content="图片超过 512K 或者 长宽 > 1080 会自动压缩后再上传" placement="top-start">
        <upload-image :image-url="imageUrl" :file-size="512" :max-w-h="1080" :category="props.category"
          @on-success="getTableData" />
      </el-tooltip>
      <cropper-img btn-type="primary" :img-width="1080" :img-height="1080" category="media" crop-type="max"
        @on-success="getTableData" />
      <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" plain icon="search" @click="getTableData">查询</el-button>
    </div>

    <warning-bar title="点击“文件名/备注”可以编辑文件名或者备注内容。" />
    <div class="gva-media-card">
      <div v-for="(item, key) in picList" :key="key" class="media-box">
        <el-image v-if="isImageTag(item.tag)" :key="key" fit="contain" :src="getUrl(item.url)"
          style="width: 138px; height: 138px;" @click="chooseImg(item)">
          <template #error>
            <div>
              <el-icon>
                <picture />
              </el-icon>
            </div>
          </template>
        </el-image>
        <video-viewer v-else-if="isVideoTag(item.tag)" width="138px" height="138px" :url="item.url" />
        <div v-else class="gva-media-box" style="width: 138px; height: 138px;">
          <el-icon :size="25">
            <Document />
          </el-icon>
        </div>
        <div class="img-title" @click="editFileNameFunc(item)">{{ item.name }}</div>
      </div>
    </div>
    <el-pagination :current-page="page" :page-size="pageSize" :total="total" :style="{ 'justify-content': 'center' }"
      layout="total, prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
  </el-drawer>
</template>

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

const imageUrl = ref('')
const imageCommon = ref('')

const search = ref({})
const page = ref(1)
const total = ref(0)
const pageSize = ref(20)

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

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

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

const emit = defineEmits(['on-select', 'on-before-upload', 'on-upload-success', 'on-upload-failure'])
const props = defineProps({
  category: { type: String, required: true },
  size: { type: String, default: '800px' },
})

const drawer = ref(false)
const picList = ref([])

const chooseImg = (item) => {
  emit('on-select', item)
  drawer.value = false
}

const getTableData = async () => {
  const res = await getFileList({ page: page.value, pageSize: pageSize.value, ...search.value })
  if (res.code === 0) {
    picList.value = res.data.list
    total.value = res.data.total
    page.value = res.data.page
    pageSize.value = res.data.pageSize
  }
}

const open = async () => {
  search.value.category = props.category
  drawer.value = true
  getTableData()
}

/**
 * 编辑文件名或者备注
 * @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: '取消修改'
    })
  })
}

defineExpose({ open })
</script>
