<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,
  Cell as VanCell,
  CellGroup as VanCellGroup,
  Empty as VanEmpty,
  Icon as VanIcon,
  Popup as VanPopup,
} from 'vant'
import { computed, nextTick, 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 previewUrl = ref('')
const previewName = ref('')
const filePreviewRef = ref<InstanceType<typeof FilePreview> | null>(null)

// 按步骤分组的附件
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 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 = ''
}

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">
                  <AttachmentListItem
                    v-for="file in getStepAllFiles(step)"
                    :key="file.id"
                    :file="file"
                    :thumb-size="40"
                    @preview="handlePreview"
                  />
                </template>
              </div>
            </div>
          </template>
          <VanEmpty v-else description="暂无附件" />
        </div>
      </div>
    </VanPopup>

    <!-- 附件预览 -->
    <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 scoped lang="less">
.history-form-data {
  margin-bottom: 16px;
}

.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;
}

.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-type-badge {
  width: 40px;
  height: 40px;
  min-width: 40px;
  border-radius: 6px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 10px;
  font-weight: 700;
  flex-shrink: 0;
}

.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>
