<script setup lang="ts">
import AttachmentListItem from '@af-mobile-client-vue3/components/data/AttachmentListItem/index.vue'
import FilePreview from '@af-mobile-client-vue3/components/data/FilePreview/index.vue'
import { getAttachmentDisplayName } from '@af-mobile-client-vue3/utils/fileType'
import { getPreviewPath } from '@af-mobile-client-vue3/utils/resourceUrl'
import {
  showToast,
  Popup as VanPopup,
} from 'vant'
import { nextTick, ref } from 'vue'

const props = defineProps({
  files: {
    type: Array<any>,
    required: true,
  },
})

const previewShow = ref(false)
const previewUrl = ref('')
const previewName = ref('')
const filePreviewRef = ref<InstanceType<typeof FilePreview> | null>(null)

function handlePreview(file: any) {
  const fileUrl = getPreviewPath(file?.url || file?.f_downloadpath || '')
  if (!fileUrl) {
    showToast('附件地址无效')
    return
  }
  previewUrl.value = fileUrl
  previewName.value = getAttachmentDisplayName(file)
  previewShow.value = true
  nextTick(() => {
    filePreviewRef.value?.init({
      path: fileUrl,
      name: previewName.value,
    })
  })
}

function closePreview() {
  previewShow.value = false
  previewUrl.value = ''
  previewName.value = ''
}
</script>

<template>
  <div class="file-list">
    <div class="file-grid">
      <AttachmentListItem
        v-for="file in props.files"
        :key="file.id"
        :file="file"
        :thumb-size="48"
        @preview="handlePreview"
      />
    </div>

    <VanPopup
      v-model:show="previewShow"
      position="bottom"
      :style="{ height: '85vh', width: '100vw' }"
      closeable
      close-icon-position="top-right"
      @close="closePreview"
    >
      <div class="doc-preview-panel">
        <div class="doc-preview-title">
          {{ previewName }}
        </div>
        <FilePreview
          v-if="previewUrl"
          ref="filePreviewRef"
          :key="previewUrl"
          class="doc-preview-frame"
        />
      </div>
    </VanPopup>
  </div>
</template>

<style lang="less" scoped>
.doc-preview-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 12px;
  box-sizing: border-box;
}

.doc-preview-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 12px;
  padding-right: 32px;
  word-break: break-all;
}

.doc-preview-frame {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.file-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>
