<template>
    <div class="note-timeline-wrap">
        <div v-if="!readonly && diagnosisId" class="timeline-actions">
            <material-picker
                v-model="tongueModel"
                :limit="99"
                type="image"
                :exclude-domain="true"
                @change="handleTongueChange"
            >
                <template #upload>
                    <div class="upload-trigger">
                        <icon :size="20" name="el-icon-Plus" />
                        <span>舌苔照片</span>
                    </div>
                </template>
            </material-picker>
            <material-picker
                v-model="reportModel"
                :limit="99"
                type="file"
                :exclude-domain="true"
                @change="handleReportChange"
            >
                <template #upload>
                    <div class="upload-trigger">
                        <icon :size="20" name="el-icon-Plus" />
                        <span>检查报告</span>
                    </div>
                </template>
            </material-picker>
        </div>
        <div v-if="notes.length" class="note-timeline">
            <div v-for="note in notes" :key="note.id" class="timeline-node">
                <div class="timeline-dot"></div>
                <div class="timeline-date">{{ note.note_date }}</div>
                <div class="timeline-body">
                    <div v-if="note.content" class="timeline-content">
                        <div v-for="(line, idx) in splitLines(note.content)" :key="idx" class="content-line">
                            {{ line }}
                        </div>
                    </div>
                    <div v-if="note.tongue_images?.length" class="timeline-images">
                        <span class="images-label">舌苔照片</span>
                        <div v-for="(url, idx) in note.tongue_images" :key="idx" class="thumb-wrap">
                            <el-image
                                :src="getImageUrl(url)"
                                :preview-src-list="note.tongue_images.map(getImageUrl)"
                                :initial-index="idx"
                                :z-index="IMAGE_PREVIEW_Z_INDEX"
                                fit="cover"
                                class="timeline-thumb"
                                preview-teleported
                            />
                            <el-icon
                                v-if="!readonly"
                                class="thumb-delete"
                                @click.stop="handleDeleteImage(note.id, 'tongue_images', url)"
                            ><CircleClose /></el-icon>
                        </div>
                    </div>
                    <div v-if="note.report_files?.length" class="timeline-images">
                        <span class="images-label">检查报告</span>
                        <template v-for="(url, idx) in note.report_files" :key="idx">
                            <div v-if="isImageFile(url)" class="thumb-wrap">
                                <el-image
                                    :src="getImageUrl(url)"
                                    :preview-src-list="getImagePreviewList(note.report_files)"
                                    :initial-index="getImagePreviewIndex(note.report_files, idx)"
                                    :z-index="IMAGE_PREVIEW_Z_INDEX"
                                    fit="cover"
                                    class="timeline-thumb"
                                    preview-teleported
                                />
                                <el-icon
                                    v-if="!readonly"
                                    class="thumb-delete"
                                    @click.stop="handleDeleteImage(note.id, 'report_files', url)"
                                ><CircleClose /></el-icon>
                            </div>
                            <div v-else class="file-wrap">
                                <a :href="getImageUrl(url)" target="_blank" class="file-link" :title="getFileName(url)">
                                    <el-icon :size="20"><Document /></el-icon>
                                    <span class="file-name">{{ getFileName(url) }}</span>
                                </a>
                                <el-icon
                                    v-if="!readonly"
                                    class="file-delete"
                                    @click.stop="handleDeleteImage(note.id, 'report_files', url)"
                                ><CircleClose /></el-icon>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
        <el-empty v-if="!notes.length && readonly" description="暂无备注" :image-size="48" />
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { CircleClose, Document } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import useAppStore from '@/stores/modules/app'
import { addDoctorNote, deleteDoctorNoteImage } from '@/api/patient'
import feedback from '@/utils/feedback'

export interface DoctorNoteItem {
    id: number
    note_date: string
    content: string | null
    tongue_images: string[]
    report_files: string[]
}

const props = defineProps<{
    notes: DoctorNoteItem[]
    diagnosisId?: number
    readonly?: boolean
}>()

const emit = defineEmits<{ refresh: [] }>()

const appStore = useAppStore()
const getImageUrl = (url: string) => appStore.getImageUrl(url)

const tongueModel = ref<string[]>([])
const reportModel = ref<string[]>([])
const prevTongueCount = ref(0)
const prevReportCount = ref(0)

/** 高于诊单抽屉（最高 4000）与多层弹窗叠加后的遮罩，避免预览被挡住 */
const IMAGE_PREVIEW_Z_INDEX = 8000

const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']

const isImageFile = (url: string): boolean => {
    const ext = url.split('.').pop()?.toLowerCase().split('?')[0] || ''
    return IMAGE_EXTENSIONS.includes(ext)
}

const getFileName = (url: string): string => {
    const parts = url.split('/')
    return decodeURIComponent(parts[parts.length - 1]?.split('?')[0] || '文件')
}

const getImagePreviewList = (files: string[]): string[] => {
    return files.filter(isImageFile).map(getImageUrl)
}

const getImagePreviewIndex = (files: string[], currentIdx: number): number => {
    const imageFiles = files.filter(isImageFile)
    const currentUrl = files[currentIdx]
    return imageFiles.indexOf(currentUrl)
}

const splitLines = (content: string | null): string[] => {
    if (!content) return []
    return content.split('\n').filter(Boolean)
}

const handleTongueChange = (val: string[]) => {
    if (!props.diagnosisId) return
    const newItems = Array.isArray(val) ? val : [val]
    if (newItems.length <= prevTongueCount.value) {
        prevTongueCount.value = newItems.length
        return
    }
    const added = newItems.slice(prevTongueCount.value)
    prevTongueCount.value = newItems.length
    if (added.length > 0) {
        addDoctorNote({ diagnosis_id: props.diagnosisId, tongue_images: added }).then(() => {
            feedback.msgSuccess('舌苔照片已添加')
            emit('refresh')
        })
    }
}

const handleReportChange = (val: string[]) => {
    if (!props.diagnosisId) return
    const newItems = Array.isArray(val) ? val : [val]
    if (newItems.length <= prevReportCount.value) {
        prevReportCount.value = newItems.length
        return
    }
    const added = newItems.slice(prevReportCount.value)
    prevReportCount.value = newItems.length
    if (added.length > 0) {
        addDoctorNote({ diagnosis_id: props.diagnosisId, report_files: added }).then(() => {
            feedback.msgSuccess('检查报告已添加')
            emit('refresh')
        })
    }
}

watch(() => props.notes, () => {
    tongueModel.value = []
    reportModel.value = []
    prevTongueCount.value = 0
    prevReportCount.value = 0
})

const handleDeleteImage = async (noteId: number, imageType: 'tongue_images' | 'report_files', imagePath: string) => {
    try {
        await ElMessageBox.confirm('确认删除？', '提示', { type: 'warning' })
    } catch {
        return
    }
    await deleteDoctorNoteImage({ note_id: noteId, image_type: imageType, image_path: imagePath })
    feedback.msgSuccess('已删除')
    emit('refresh')
}
</script>

<style scoped lang="scss">
.timeline-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px dashed #ebeef5;
}
.upload-trigger {
    width: 90px;
    height: 90px;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 4px;
    cursor: pointer;
    color: #909399;
    font-size: 12px;
    transition: border-color 0.2s;
    &:hover {
        border-color: #409eff;
        color: #409eff;
    }
}
.note-timeline {
    position: relative;
    padding-left: 22px;
}
.note-timeline::before {
    content: '';
    position: absolute;
    left: 6px;
    top: 4px;
    bottom: 4px;
    width: 2px;
    background: #ebeef5;
    border-radius: 1px;
}
.timeline-node {
    position: relative;
    padding-bottom: 16px;
}
.timeline-node:last-child {
    padding-bottom: 0;
}
.timeline-dot {
    position: absolute;
    left: -19px;
    top: 5px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #409eff;
    border: 2px solid #ecf5ff;
}
.timeline-date {
    font-size: 13px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 6px;
    font-family: 'IBM Plex Mono', Consolas, monospace;
}
.timeline-body {
    display: flex;
    flex-direction: column;
    gap: 6px;
}
.timeline-content {
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.content-line {
    font-size: 12.5px;
    color: #606266;
    line-height: 1.6;
    word-break: break-word;
}
.timeline-images {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 6px;
}
.images-label {
    font-size: 12px;
    color: #909399;
    flex-shrink: 0;
}
.thumb-wrap {
    position: relative;
    display: inline-block;
}
.timeline-thumb {
    width: 64px;
    height: 64px;
    border-radius: 6px;
    border: 1px solid #ebeef5;
    cursor: pointer;
    transition: transform 0.15s ease;
}
.timeline-thumb:hover {
    transform: scale(1.05);
}
.thumb-delete {
    position: absolute;
    top: -6px;
    right: -6px;
    font-size: 16px;
    color: #f56c6c;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    display: none;
}
.thumb-wrap:hover .thumb-delete {
    display: block;
}
.file-wrap {
    position: relative;
    display: inline-flex;
    align-items: center;
}
.file-link {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 6px 10px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    text-decoration: none;
    color: #409eff;
    font-size: 12px;
    max-width: 180px;
    transition: border-color 0.2s;
    &:hover {
        border-color: #409eff;
    }
}
.file-name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 120px;
}
.file-delete {
    position: absolute;
    top: -6px;
    right: -6px;
    font-size: 16px;
    color: #f56c6c;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    display: none;
}
.file-wrap:hover .file-delete {
    display: block;
}
</style>
