<script setup lang="ts">
import {
  showToast,
  Cell as VanCell,
  CellGroup as VanCellGroup,
  Empty as VanEmpty,
  Icon as VanIcon,
  Image as VanImage,
  ImagePreview as VanImagePreview,
  Popup as VanPopup,
} from 'vant'
import { computed, ref } from 'vue'

interface HistoryFormDataItem {
  label: string
  value: any
}

interface StepAttachment {
  stepId: number
  stepName: string
  data: any[]
  images: any[]
  files: any[]
}

interface Props {
  data?: HistoryFormDataItem[]
  stepAttachments?: StepAttachment[]
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  stepAttachments: () => [],
})

const drawerVisible = ref(false)
const previewShow = ref(false)
const previewIndex = ref(0)

// 合并所有步骤的附件
const allFiles = computed(() => {
  const files: any[] = []
  props.stepAttachments?.forEach((step) => {
    if (step.images && step.images.length > 0) {
      files.push(...step.images.map(img => ({ ...img, stepName: step.stepName })))
    }
    if (step.files && step.files.length > 0) {
      files.push(...step.files.map(file => ({ ...file, stepName: step.stepName })))
    }
  })
  return files
})

// 按步骤分组的附件
const groupedAttachments = computed(() => {
  return props.stepAttachments?.filter((step) => {
    const hasImages = step.images && step.images.length > 0
    const hasFiles = step.files && step.files.length > 0
    return hasImages || hasFiles
  }) || []
})

function isImage(file: any) {
  return /\.(?:png|jpe?g|gif|webp|bmp|svg)$/i.test(file.url || file.name || '')
}

function handlePreview(file: any) {
  if (isImage(file)) {
    const imageFiles = allFiles.value.filter(isImage)
    previewIndex.value = imageFiles.map(f => f.url).indexOf(file.url)
    previewShow.value = true
  }
  else {
    showToast('不支持在线查看')
  }
}

function getFileType(filename: string) {
  if (!filename)
    return '文件'
  const ext = filename.split('.').pop()?.toLowerCase() || ''
  const typeMap: Record<string, string> = {
    pdf: 'PDF文档',
    doc: 'Word文档',
    docx: 'Word文档',
    xls: 'Excel表格',
    xlsx: 'Excel表格',
    ppt: 'PPT演示',
    pptx: 'PPT演示',
    jpg: '图片',
    jpeg: '图片',
    png: '图片',
    gif: '图片',
    txt: '文本文件',
    zip: '压缩文件',
    rar: '压缩文件',
  }
  return typeMap[ext] || '文件'
}

function formatFileSize(size: number) {
  if (!size)
    return ''
  // 如果小于1M，转换为KB显示
  if (size < 1) {
    const kbSize = size * 1024
    return `${kbSize.toFixed(1)} KB`
  }
  // 大于等于1M，保持M为单位
  return `${size.toFixed(1)} MB`
}

function openDrawer() {
  drawerVisible.value = true
}

// 获取步骤的所有文件（合并 images 和 files）
function getStepAllFiles(step: StepAttachment) {
  const allFiles: any[] = []
  if (step.images && step.images.length > 0) {
    allFiles.push(...step.images)
  }
  if (step.files && step.files.length > 0) {
    allFiles.push(...step.files)
  }
  return allFiles
}
</script>

<template>
  <div v-if="data && data.length > 0" class="history-form-data">
    <VanCellGroup title="历史表单数据">
      <VanCell
        v-for="(item, index) in data"
        :key="index"
        :title="item.label"
        :value="item.value"
      />
      <VanCell
        v-if="groupedAttachments && groupedAttachments.length > 0"
        title="查看附件"
        is-link
        @click="openDrawer"
      >
        <template #right-icon>
          <VanIcon name="arrow" />
        </template>
      </VanCell>
    </VanCellGroup>

    <!-- 附件抽屉 -->
    <VanPopup
      v-model:show="drawerVisible"
      position="bottom"
      :style="{ height: '80vh', width: '100vw' }"
      closeable
      close-icon-position="top-right"
      @close="drawerVisible = false"
    >
      <div class="attachment-drawer">
        <div class="drawer-header">
          <h3>附件</h3>
        </div>
        <div class="drawer-content">
          <template v-if="groupedAttachments && groupedAttachments.length > 0">
            <div
              v-for="step in groupedAttachments"
              :key="step.stepId"
              class="step-attachment-group"
            >
              <div class="step-title">
                <VanIcon name="location-o" />
                <span>{{ step.stepName }}</span>
              </div>
              <div class="records-container attachment-list">
                <template v-if="getStepAllFiles(step) && getStepAllFiles(step).length > 0">
                  <div
                    v-for="file in getStepAllFiles(step)"
                    :key="file.id"
                    class="attachment-item"
                    @click="handlePreview(file)"
                  >
                    <template v-if="isImage(file)">
                      <VanImage
                        :src="file.url"
                        width="40"
                        height="40"
                        fit="cover"
                        class="attachment-thumb"
                        :alt="file.real_name || file.name"
                      />
                      <div class="file-content">
                        <div class="file-header">
                          <span class="file-name">{{ file.real_name || file.name }}</span>
                          <span class="file-type">{{ getFileType(file.name) }}</span>
                        </div>
                        <div class="file-footer">
                          <span v-if="file.size" class="file-size">{{ formatFileSize(file.size) }}</span>
                          <span v-if="file.upload_time" class="file-time">{{ file.upload_time }}</span>
                        </div>
                      </div>
                    </template>
                    <template v-else>
                      <i class="attachment-file-icon i-fa6-solid-file-lines" />
                      <div class="file-content">
                        <div class="file-header">
                          <span class="file-name">{{ file.real_name || file.name }}</span>
                          <span class="file-type">{{ getFileType(file.name) }}</span>
                        </div>
                        <div class="file-footer">
                          <span v-if="file.size" class="file-size">{{ formatFileSize(file.size) }}</span>
                          <span v-if="file.upload_time" class="file-time">{{ file.upload_time }}</span>
                        </div>
                      </div>
                    </template>
                  </div>
                </template>
              </div>
            </div>
          </template>
          <VanEmpty v-else description="暂无附件" />
        </div>
      </div>
    </VanPopup>

    <!-- 图片预览 -->
    <VanImagePreview
      v-model:show="previewShow"
      :images="allFiles.filter(isImage).map(f => f.url)"
      :start-position="previewIndex"
      @close="previewShow = false"
    />
  </div>
</template>

<style scoped lang="less">
.history-form-data {
  margin-bottom: 16px;
}

.attachment-drawer {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;

  .drawer-header {
    padding: 12px 16px;
    background: #fff;
    border-bottom: 1px solid rgba(229, 230, 235, 0.4);
    flex-shrink: 0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .drawer-content {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
    background: #fff;
  }
}

.step-attachment-group {
  margin-bottom: 12px;
  background: #fff;
  border: 1px solid rgba(229, 230, 235, 0.4);
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  &:last-child {
    margin-bottom: 0;
  }

  .step-title {
    display: flex;
    align-items: center;
    padding: 0;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;

    .van-icon {
      margin-right: 6px;
      color: #1890ff;
      font-size: 16px;
    }
  }
}

.records-container,
.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0;
  min-height: auto;
  background: transparent;
  border-radius: 0;
  align-items: stretch;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  min-height: auto;
  background: transparent;
  border-radius: 0;
  align-items: stretch;
  position: relative;
  padding: 0;
}

.attachment-item {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.07);
  padding: 10px 12px;
  cursor: pointer;
  transition: box-shadow 0.2s;
  min-height: 56px;
}

.attachment-thumb,
.attachment-file-icon {
  width: 40px;
  height: 40px;
  min-width: 40px;
  min-height: 40px;
  max-width: 40px;
  max-height: 40px;
  border-radius: 6px;
  margin-right: 12px;
  object-fit: cover;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e6f7ff;
  font-size: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
  flex-shrink: 0;
}

.attachment-file-icon {
  font-size: 22px;
  color: #8fa4b6;
}

.file-content {
  display: flex;
  flex-direction: column;
  min-width: 0;
  flex: 1;

  .file-header {
    display: flex;
    align-items: center;
    margin-bottom: 3px;

    .file-name {
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 8px;
      width: 0;
      flex: 1;
    }

    .file-type {
      color: rgba(0, 0, 0, 0.45);
      font-size: 11px;
      padding: 2px 6px;
      background: rgba(0, 0, 0, 0.04);
      border-radius: 4px;
      flex-shrink: 0;
    }
  }

  .file-footer {
    display: flex;
    align-items: center;
    color: rgba(0, 0, 0, 0.45);
    font-size: 11px;

    .file-size {
      margin-right: 10px;
    }

    .file-time {
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 4px;
        background: rgba(0, 0, 0, 0.25);
        border-radius: 50%;
      }
    }
  }
}
</style>
