<template>
  <div class="app-container">
    <div class="portal-header">
      <h2 class="portal-title">图片�?/h2>
      <el-button type="primary" icon="Upload" @click="handleUpload" v-hasPermi="['efinder:file:upload']">上传图片</el-button>
    </div>

    <el-row :gutter="12">
      <el-col v-for="item in imageList" :key="item.id" :xs="12" :sm="8" :md="6" :lg="4" :xl="4" class="mb12">
        <el-card shadow="hover" :body-style="{ padding: '0' }" class="image-card">
          <el-image
            :src="getImageUrl(item.id)"
            :preview-src-list="previewList"
            fit="cover"
            class="gallery-image"
            lazy
            @click="handleImageClick(item)"
          >
            <template #error>
              <div class="image-error">
                <el-icon :size="32"><picture-filled /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="image-info">
            <div class="image-name" :title="item.name">{{ item.name }}</div>
            <div class="image-time">{{ parseTime(item.date, '{y}-{m}-{d}') }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty v-if="!loading && imageList.length === 0" description="暂无图片" />

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getImageList" />

    <el-dialog :title="title" v-model="uploadVisible" width="500px" append-to-body>
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :auto-upload="false"
        drag
        multiple
        accept="image/*"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将图片拖到此处，�?em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">支持 JPG、PNG、GIF 等图片格式，单张不超�?20MB</div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">开始上�?/el-button>
          <el-button @click="uploadVisible = false">�?�?/el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tpz">
import { getFileList, folderList } from "@/api/efinder/finder"
import { getToken } from "@/utils/auth"
import { parseTime } from "@/utils/goldenwater"

const { proxy } = getCurrentInstance()

const imageList = ref([])
const total = ref(0)
const loading = ref(true)
const uploadVisible = ref(false)
const title = ref("上传图片")
const currentPreviewIndex = ref(0)

const uploadRef = ref(null)
const uploadUrl = ref(import.meta.env.VITE_SERVICE_BASE_TITLE + "/efinder/file/upload")
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() })
const uploadData = ref({})
const categoryFolderId = ref(null)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 30,
    pid: null
  }
})

const { queryParams } = toRefs(data)

const previewList = computed(() => {
  return imageList.value.map(item => getImageUrl(item.id))
})

function getImageUrl(fileId) {
  return import.meta.env.VITE_SERVICE_BASE_TITLE + "/efinder/file/preview/" + fileId
}

function getImageList() {
  loading.value = true
  queryParams.value.pid = categoryFolderId.value
  getFileList(queryParams.value).then(response => {
    imageList.value = response.rows || response.data || []
    total.value = response.total || imageList.value.length
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleImageClick(item) {
  const idx = imageList.value.findIndex(i => i.id === item.id)
  if (idx >= 0) {
    currentPreviewIndex.value = idx
  }
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getImageList()
}

function handleUpload() {
  uploadData.value = { pid: categoryFolderId.value }
  uploadVisible.value = true
  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
  })
}

function submitUpload() {
  proxy.$refs.uploadRef.submit()
}

function beforeUpload(file) {
  const isImage = file.type.startsWith("image/")
  if (!isImage) {
    proxy.$modal.msgError("请上传图片文�?)
    return false
  }
  const isLtSize = file.size / 1024 / 1024 < 20
  if (!isLtSize) {
    proxy.$modal.msgError("上传图片大小不能超过 20MB")
    return false
  }
  return true
}

function uploadSuccess(response) {
  if (response.code === 200) {
    proxy.$modal.msgSuccess("上传成功")
    uploadVisible.value = false
    getImageList()
  } else {
    proxy.$modal.msgError(response.msg)
  }
}

function uploadError() {
  proxy.$modal.msgError("上传失败")
}

onMounted(async () => {
  const res = await folderList({ fdCate: "tpz", pageSize: 1 })
  const folder = (res.rows && res.rows[0]) || (res.data && res.data[0])
  if (folder) {
    categoryFolderId.value = folder.id
  }
  getImageList()
})
</script>

<style lang="scss" scoped>
.portal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.portal-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.mb12 {
  margin-bottom: 12px;
}

.image-card {
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;

  &:hover {
    transform: translateY(-2px);
  }
}

.gallery-image {
  width: 100%;
  height: 160px;
  display: block;
}

.image-error {
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #bbb;
}

.image-info {
  padding: 8px 10px;
}

.image-name {
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 2px;
}

.image-time {
  font-size: 11px;
  color: #999;
}
</style>
