<template>
    <el-drawer v-model="drawerVisible" title="订单详情" direction="rtl" size="60%" class="order-detail-drawer">
        <div class="detail-container" v-if="order">
            <!-- 1. Header Status -->
            <div class="detail-header">
                <div class="left-head">
                    <span class="order-no">{{ order.orderNo }}</span>
                    <el-tag :type="getStatusTag(order.status)" effect="dark" class="status-tag">{{
                        getStatusName(order.status) }}</el-tag>
                    <el-tag effect="plain" class="type-tag"
                        :type="order.type === 'transport' ? '' : (order.type === 'feeding' ? 'warning' : 'danger')">
                        {{ getTypeName(order.type) }}
                    </el-tag>
                </div>
                <div class="right-head">
                    <!-- Action Buttons Group -->
                    <div class="detail-actions">
                        <template v-if="![4, 7].includes(order.status)">
                            <el-button v-hasPermi="['order:orderList:dispatch']" v-if="order.status === 0"
                                type="success" icon="Bicycle" @click="emit('dispatch', order)">
                                立即派单
                            </el-button>
                            <el-button v-hasPermi="['order:orderList:redispatch']"
                                v-if="![0, 4, 7].includes(order.status)" type="warning" icon="Bicycle"
                                @click="emit('dispatch', order)">
                                重新派单
                            </el-button>
                        </template>

                        <template v-if="[0, 1].includes(order.status)">
                            <el-button v-hasPermi="['order:orderList:cancel']" type="danger" plain icon="CircleClose"
                                @click="emit('cancel', order)">取消订单</el-button>
                        </template>

                        <template v-if="order.status === 3">
                            <el-button type="primary" icon="CircleCheck"
                                @click="emit('command', 'complete', order)">确认完成</el-button>
                        </template>

                        <template v-if="[3, 4].includes(order.status) && order.mode == 0">
                            <el-button v-hasPermi="['order:orderList:nursingSummary']" icon="Notebook"
                                @click="emit('care-summary', order)">护理小结</el-button>
                        </template>

                        <el-dropdown v-if="![7].includes(order.status)" trigger="click"
                            @command="(cmd) => emit('command', cmd, order)" style="margin-left: 12px;">
                            <el-button icon="More">更多操作</el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-if="[3, 4].includes(order.status)" command="reward"
                                        icon="Trophy">奖惩操作</el-dropdown-item>
                                    <el-dropdown-item v-if="![7].includes(order.status)" command="remark"
                                        icon="EditPen">订单备注</el-dropdown-item>
                                    <el-dropdown-item command="delete" v-if="[4, 5, 6].includes(order.status)" divided
                                        icon="Delete" style="color: #f56c6c;">删除订单</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
            </div>

            <div class="detail-scroll-area">
                <!-- 2. Progress Section -->
                <div class="progress-section">
                    <el-steps :active="currentOrderSteps.active" finish-status="success" align-center
                        class="custom-steps">
                        <el-step v-for="(step, index) in currentOrderSteps.steps" :key="index" :title="step.title"
                            :description="step.time" />
                    </el-steps>
                </div>

                <!-- 3. Top Info: Pet & User -->
                <div class="top-info-row">
                    <!-- Left: Pet Info -->
                    <div class="info-section pet-section">
                        <div class="sec-header">
                            <span class="label">宠物档案</span>
                            <el-tag size="small" effect="plain">{{ order.petBreed }}</el-tag>
                        </div>
                        <div class="pet-basic-row">
                            <el-avatar :size="50" :src="order.petAvatar" shape="square" class="pet-avatar-lg">{{
                                (order.petName || '').charAt(0) }}</el-avatar>
                            <div class="pet-names">
                                <div class="b-name">{{ order.petName }}
                                    <el-icon v-if="order.petGender === 'male'" color="#409eff">
                                        <Male />
                                    </el-icon>
                                    <el-icon v-else color="#f56c6c">
                                        <Female />
                                    </el-icon>
                                </div>
                                <div class="b-tags">
                                    <el-tag size="small" type="info">{{ order.petAge || '-' }}</el-tag>
                                    <el-tag size="small" type="info">{{ order.petWeight || '-' }}</el-tag>
                                </div>
                            </div>
                        </div>
                        <el-descriptions :column="2" size="small" class="pet-desc" border>
                            <el-descriptions-item label="宠物品种">{{ order.petBreed || '-'
                            }}</el-descriptions-item>
                            <el-descriptions-item label="疫苗状态"><span style="color:#67c23a">{{ order.petVaccine || '-'
                            }}</span></el-descriptions-item>
                            <el-descriptions-item label="性格特点">{{ order.petPersonality || order.petCharacter || '-'
                            }}</el-descriptions-item>
                            <el-descriptions-item label="健康状况">{{ order.petHealth || '-' }}</el-descriptions-item>
                        </el-descriptions>
                    </div>

                    <!-- Right: User Info -->
                    <div class="info-section user-section">
                        <div class="sec-header">
                            <span class="label">用户信息</span>
                        </div>
                        <div class="user-content">
                            <div class="u-row">
                                <el-avatar :size="40" :src="order.userAvatar">{{ (order.userName || '').charAt(0)
                                }}</el-avatar>
                                <div class="u-info">
                                    <div class="nm">{{ order.userName }}</div>
                                    <div class="ph">{{ order.contactPhone }}</div>
                                </div>
                            </div>
                            <div class="addr-box">
                                <div class="addr-label">服务地址</div>
                                <div class="addr-txt">{{ order.city }}{{ order.district }} {{ order.address || '' }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 4. Bottom Tabs -->
                <el-tabs v-model="activeDetailTab" class="detail-tabs type-card">
                    <!-- Tab 1: Basic Info -->
                    <el-tab-pane label="订单基础信息" name="basic">
                        <div class="tab-pane-content">
                            <div class="section-block">
                                <div class="sec-title-bar">基础业务信息</div>
                                <el-descriptions :column="3" border size="default" class="custom-desc">
                                    <el-descriptions-item label="系统单号">{{ order.orderNo }}</el-descriptions-item>
                                    <el-descriptions-item label="服务类型">
                                        {{ getTypeName(order.type) }}
                                        <el-tag size="small" v-if="order.type === 'transport'" style="margin-left:5px"
                                            effect="light">{{ getTransportModeName(order.transportType) }}</el-tag>
                                    </el-descriptions-item>

                                    <el-descriptions-item label="归属门店">{{ order.merchantName }}
                                        ({{ Number(order.platformId) === 1 ? '门店下单' : '平台代下单' }})</el-descriptions-item>
                                    <el-descriptions-item label="宠主信息">{{ order.userName }} / {{ order.contactPhone
                                    }}</el-descriptions-item>
                                    <el-descriptions-item label="履约佣金" label-class-name="money-label">
                                        <span style="color:#f56c6c; font-weight:bold;">¥ {{ order.fulfillerFee }}</span>
                                    </el-descriptions-item>

                                    <el-descriptions-item label="预约时间">{{ getServiceTimeRange(order.serviceTime)
                                    }}</el-descriptions-item>
                                    <el-descriptions-item label="团购套餐">{{ order.groupBuyPackage || '-'
                                    }}</el-descriptions-item>
                                    <el-descriptions-item label="创建时间">{{ order.createTime }}</el-descriptions-item>
                                    <el-descriptions-item label="订单佣金" label-class-name="money-label">
                                        <span style="color:#f56c6c; font-weight:bold;">¥ {{ order.orderCommission || 0
                                        }}</span>
                                    </el-descriptions-item>

                                    <el-descriptions-item label="订单备注" :span="3">
                                        {{ order.remark || '-' }}
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>

                            <div v-if="order.type === 'transport'" class="section-block transport-split-block">
                                <div class="sec-title-bar">接送任务详情</div>
                                <div class="transport-one">
                                    <div class="t-row">
                                        <el-tag size="small" effect="plain" class="sub-badge">{{
                                            getTransportLabel(order.subOrderType) }}</el-tag>
                                        <span class="time">{{ order.serviceTime }}</span>
                                    </div>
                                    <div class="t-row">
                                        <span class="t-k">起点</span>
                                        <span class="t-v">{{ order.detail?.fromAddress || order.detail?.pickAddr || '-'
                                            }}</span>
                                    </div>
                                    <div class="t-row">
                                        <span class="t-k">终点</span>
                                        <span class="t-v">{{ order.detail?.toAddress || order.detail?.dropAddr ||
                                            order.toAddress ||
                                            '-' }}</span>
                                    </div>
                                    <div class="t-row sub">
                                        <span class="t-v">{{ order.contact || order.userName || '-' }} {{
                                            order.contactPhoneNumber
                                            || order.contactPhone || '-' }}</span>
                                    </div>
                                </div>
                            </div>

                            <div v-if="['feeding', 'washing'].includes(order.type)" class="section-block">
                                <div class="sec-title-bar">服务执行要求</div>
                                <el-descriptions :column="2" border size="default" class="custom-desc">
                                    <el-descriptions-item label="服务地址" :span="2">{{ order.detail.area || order.address
                                    }}</el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- Tab 2: Fulfiller Info -->
                    <el-tab-pane label="指派履约者" name="fulfiller">
                        <div class="tab-pane-content">
                            <div v-if="order.fulfillerName" class="fulfiller-card">
                                <div class="f-left">
                                    <el-avatar :size="60" :src="order.fulfillerAvatar">{{ order.fulfillerName.charAt(0)
                                    }}</el-avatar>
                                </div>
                                <div class="f-right">
                                    <div class="f-row1">
                                        <span class="f-name">{{ order.fulfillerName }}</span>
                                        <el-tag size="small" type="primary" effect="plain" round>{{
                                            order.fulfillerLevelName ||
                                            '普通履约者' }}</el-tag>
                                    </div>
                                    <div class="f-row2">
                                        <span>联系电话：{{ order.fulfillerPhone || '-' }}</span>
                                        <span class="sep">|</span>
                                        <span>归属区域：{{ order.fulfillerStation || '-' }}</span>
                                    </div>
                                    <div class="f-row3"
                                        style="margin-top: 8px; font-size: 13px; color: #606266; background: #f9fafe; padding: 8px; border-radius: 4px; display: flex; gap: 20px;">
                                        <span><span style="color:#909399;">指派时间：</span>{{ dispatchTime }}</span>
                                        <span><span style="color:#909399;">接单时间：</span>{{ acceptTime }}</span>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="empty-state">
                                <el-result icon="info" title="暂无履约者" sub-title="该订单尚未指派履约人员"></el-result>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- Tab 3: Service Progress -->
                    <el-tab-pane label="服务进度" name="service">
                        <div class="tab-pane-content">
                            <!-- 导出流程图按钮：与订单日志导出Excel位置一致 -->
                            <div style="display: flex; justify-content: flex-end; margin-bottom: 15px; gap: 10px;">
                                <el-button type="primary" size="small" icon="Picture"
                                    v-hasPermi="['order:orderList:queryExportExcel']"
                                    @click="handleExportProgressImage">导出流程图</el-button>
                                <el-button type="success" size="small" icon="Link"
                                    v-hasPermi="['order:orderList:queyGenerateFulfillPath']"
                                    @click="handleGenerateFulfillPath">生成履约路径</el-button>
                            </div>

                            <div v-if="serviceProgressSteps.length === 0" class="empty-progress"
                                style="padding:40px; text-align:center; color:#909399;">
                                <el-result icon="info" title="待接单" sub-title="履约者接单后将在此记录服务进度"></el-result>
                            </div>

                            <el-timeline style="padding: 10px 20px;" v-else>
                                <el-timeline-item v-for="(step, index) in serviceProgressSteps" :key="index"
                                    :timestamp="step.time" placement="top" :color="step.color" :icon="step.icon"
                                    size="large">
                                    <div class="progress-card">
                                        <h4 class="p-title">{{ step.title }}</h4>
                                        <p class="p-desc">{{ step.desc }}</p>
                                        <div class="p-media" v-if="step.media && step.media.length">
                                            <div v-for="(item, i) in step.media" :key="i" class="media-item">
                                                <!-- 图片类型 -->
                                                <el-image v-if="item.type === 'image'" :src="item.url"
                                                    :preview-src-list="step.media.filter(m => m.type === 'image').map(m => m.url)"
                                                    fit="cover" class="p-img" :preview-teleported="true" />

                                                <!-- 视频类型：由于后端没给第一帧，这里采用 video 标签 preload 方式尝试展示 -->
                                                <div v-else-if="item.type === 'video'" class="p-video-box"
                                                    @click="openVideoPreview(item.url)">
                                                    <video :src="item.url" preload="metadata"
                                                        class="p-img p-video"></video>
                                                    <div class="play-icon-overlay">
                                                        <el-icon>
                                                            <VideoPlay />
                                                        </el-icon>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </el-timeline-item>
                            </el-timeline>
                        </div>
                    </el-tab-pane>

                    <!-- Tab 4: Logs -->
                    <el-tab-pane label="订单日志" name="logs">
                        <div class="tab-pane-content">
                            <div style="display: flex; justify-content: flex-end; margin-bottom: 15px;">
                                <el-button type="primary" size="small" icon="Download"
                                    v-hasPermi="['order:orderList:queryExportExcel']"
                                    @click="handleExportLogs">导出日志Excel</el-button>
                            </div>
                            <el-timeline>
                                <el-timeline-item v-for="(log, index) in (orderLogs || [])" :key="index"
                                    :timestamp="log.createTime || log.time || ''" :type="'primary'" :icon="undefined"
                                    placement="top">
                                    <div class="log-card">
                                        <div class="l-tit">{{ log.title }}</div>
                                        <div class="l-txt">{{ log.content }}</div>
                                    </div>
                                </el-timeline-item>
                            </el-timeline>
                        </div>
                    </el-tab-pane>

                    <!-- Tab 5: Complaint Records -->
                    <el-tab-pane label="投诉记录" name="complaints">
                        <div class="tab-pane-content">
                            <div v-if="complaintList.length === 0" class="empty-state">
                                <el-result icon="success" title="暂无投诉" sub-title="该订单暂无投诉记录"></el-result>
                            </div>
                            <el-timeline v-else>
                                <el-timeline-item v-for="(complaint, index) in complaintList" :key="index"
                                    :timestamp="complaint.createTime" placement="top" color="#f56c6c">
                                    <div class="log-card">
                                        <div class="l-tit">履约者：{{ complaint.fulfiller }}</div>
                                        <div class="l-txt">{{ complaint.reason }}</div>
                                        <div class="l-txt" v-if="complaint.photoUrls">
                                            <span>图片：</span>
                                            <div style="display: flex; gap: 5px; flex-wrap: wrap; margin-top: 5px;">
                                                <ImagePreview v-for="(url, imgIndex) in complaint.photoUrls.split(',')"
                                                    :key="imgIndex" :src="url" :width="40" :height="40" />
                                            </div>
                                        </div>
                                    </div>
                                </el-timeline-item>
                            </el-timeline>
                        </div>
                    </el-tab-pane>

                    <!-- Tab 6: Service Change Records -->
                    <el-tab-pane label="服务变更记录" name="serviceChanges">
                        <div class="tab-pane-content">
                            <div v-if="serviceChangeList.length === 0" class="empty-state">
                                <el-result icon="success" title="暂无服务变更" sub-title="该订单暂无服务变更记录"></el-result>
                            </div>
                            <el-timeline v-else>
                                <el-timeline-item v-for="(change, index) in serviceChangeList" :key="index"
                                    :timestamp="change.createTime" placement="top" color="#409eff">
                                    <div class="log-card">
                                        <div class="l-tit">服务变更 - {{ change.service }}</div>
                                        <div class="l-txt">申诉理由：{{ change.reason }}</div>
                                        <div class="l-txt" v-if="change.auditStatus === 1" style="color:#67c23a;">
                                            审核状态：已通过</div>
                                        <div class="l-txt" v-else-if="change.auditStatus === 2" style="color:#f56c6c;">
                                            审核状态：已驳回
                                        </div>
                                        <div class="l-txt" v-else style="color:#e6a23c;">审核状态：待审核</div>
                                        <div class="l-txt" v-if="change.photoUrls">
                                            <span>图片：</span>
                                            <div style="display: flex; gap: 5px; flex-wrap: wrap; margin-top: 5px;">
                                                <ImagePreview v-for="(url, imgIndex) in change.photoUrls.split(',')"
                                                    :key="imgIndex" :src="url" :width="40" :height="40" />
                                            </div>
                                        </div>
                                    </div>
                                </el-timeline-item>
                            </el-timeline>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </el-drawer>

    <!-- 流程图预览弹窗 -->
    <el-dialog v-model="processImageVisible" title="服务流程图预览" width="620px" destroy-on-close append-to-body>
        <div v-loading="isProcessing" element-loading-text="正在绘制流程图...">
            <div v-if="processImageUrl" style="text-align: center;">
                <el-image :src="processImageUrl"
                    style="max-width: 100%; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);"
                    :preview-src-list="[processImageUrl]" :preview-teleported="true" />
                <div style="margin-top: 20px;">
                    <el-button type="primary" icon="Download" @click="downloadProcessImage">下载并保存图片</el-button>
                </div>
            </div>
            <div v-else-if="!isProcessing" style="text-align: center; color: #909399; padding: 40px;">
                生成图片失败，请稍后重试
            </div>
        </div>
    </el-dialog>

    <!-- 视频播放弹窗 -->
    <el-dialog v-model="videoPreview.visible" title="视频播放" width="800px" append-to-body @closed="videoPreview.url = ''">
        <div
            style="width: 100%; display: flex; justify-content: center; background: #000; border-radius: 4px; overflow: hidden;">
            <video v-if="videoPreview.url" :src="videoPreview.url" controls autoplay
                style="max-width: 100%; max-height: 70vh;"></video>
        </div>
    </el-dialog>

    <!-- 隐藏截图区域（离屏渲染模式） @Author: Antigravity -->
    <div style="position: fixed; left: -9999px; top: 0; pointer-events: none; background: #fff;">
        <div id="order-process-capture-area"
            style="width: 650px; padding: 40px; background: #fff; border-radius: 8px; box-sizing: border-box; font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;">
            <!-- 报告头部 -->
            <div style="margin-bottom: 30px; border-bottom: 2px solid #f0f2f5; padding-bottom: 20px;">
                <div
                    style="font-size: 20px; font-weight: bold; color: #303133; display: flex; align-items: center; gap: 12px;">
                    <span
                        style="font-size: 14px; padding: 4px 10px; border-radius: 4px; background: #409eff; color: #fff;">{{
                            getStatusName(order?.status) }}</span>
                    <span>服务流程：{{ order?.orderNo || order?.code }}</span>
                </div>
                <div style="margin-top: 10px; font-size: 13px; color: #909399;">
                    报告生成时间：{{ captureTime }}
                </div>
            </div>

            <!-- 进度步骤列表 -->
            <div style="padding-left: 10px;">
                <div v-if="serviceProgressSteps.length === 0"
                    style="padding: 40px; text-align: center; color: #909399;">
                    暂无服务进度记录
                </div>
                <div v-else>
                    <div v-for="(step, index) in serviceProgressSteps" :key="index"
                        style="position: relative; padding-bottom: 35px; padding-left: 40px;">
                        <!-- 垂线 -->
                        <div v-if="index < serviceProgressSteps.length - 1"
                            style="position: absolute; left: 13px; top: 13px; bottom: 0; width: 2px; background-color: #e4e7ed;">
                        </div>
                        <!-- 圆点 -->
                        <div :style="{
                            position: 'absolute', left: '0', top: '0',
                            width: '28px', height: '28px', borderRadius: '50%',
                            backgroundColor: '#fff',
                            border: '3px solid ' + (step.color || '#ff9900'),
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            zIndex: '1', color: step.color || '#ff9900', fontSize: '12px', fontWeight: 'bold'
                        }">●</div>
                        <!-- 时间 -->
                        <div style="font-size: 14px; color: #909399; margin-bottom: 10px; font-weight: 500;">{{
                            step.time
                        }}</div>
                        <!-- 进度卡片 -->
                        <div
                            style="background: #f8fcfb; border-radius: 8px; padding: 20px; border: 1px solid #ebeef5; width: calc(100% - 10px); box-sizing: border-box;">
                            <h4 style="margin: 0 0 12px; font-size: 17px; font-weight: bold; color: #303133;">{{
                                step.title
                            }}</h4>
                            <p
                                style="margin: 0 0 18px; color: #606266; font-size: 14px; line-height: 1.7; text-align: justify;">
                                {{ step.desc }}</p>
                            <!-- 图片展示（截图区域内用 base64 DataURL，避免 html2canvas 跨域问题） -->
                            <div v-if="step.media && step.media.length"
                                style="display: flex; gap: 12px; flex-wrap: wrap;">
                                <div v-for="(item, i) in step.media" :key="i">
                                    <!-- 图片：用预加载的 base64 -->
                                    <img v-if="item.type === 'image' && captureBase64Cache[item.url]"
                                        :src="captureBase64Cache[item.url]" decoding="sync" loading="eager"
                                        style="width: 140px; height: 140px; border-radius: 6px; border: 1px solid #e4e7ed; object-fit: cover; display: block;" />
                                    <!-- 占位白块（当加载失败或还未加载完时） -->
                                    <div v-else-if="item.type === 'image'"
                                        style="width: 140px; height: 140px; border-radius: 6px; background: #f5f7fa; border: 1px solid #e4e7ed;">
                                    </div>
                                    <!-- 视频： html2canvas 无法渲染 video，展示占位标识 -->
                                    <div v-else-if="item.type === 'video'"
                                        style="width: 140px; height: 140px; border-radius: 6px; border: 1px solid #e4e7ed; background: #1a1a2e; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; flex-direction: column; gap: 6px;">
                                        <span style="font-size: 28px;">▶</span>
                                        <span>视频</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 页脚 -->
            <div style="margin-top: 50px; text-align: center; border-top: 1px solid #f0f2f5; padding-top: 25px;">
                <div style="font-size: 13px; color: #c0c4cc; font-style: italic; letter-spacing: 1px;">Powered by
                    宠宝管理系统 · 官方服务证书</div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import html2canvas from 'html2canvas'
import { getPet } from '@/api/archieves/pet'
import { getCustomer } from '@/api/archieves/customer'
import { getSubOrderInfo } from '@/api/order/subOrder/index'
import { getFulfiller } from '@/api/fulfiller/fulfiller/index'
import { listSubOrderLog, exportSubOrderLogUrl } from '@/api/order/subOrderLog/index'
import { listComplaintByOrder } from '@/api/fulfiller/complaint'
import { listSubOrderAppealByOrderId } from '@/api/order/subOrderAppeal'
import ImagePreview from '@/components/ImagePreview/index.vue'

const { proxy } = getCurrentInstance()

// 视频判定辅助函数
const isVideo = (url) => {
    if (!url) return false;
    const videoExts = ['.mp4', '.mov', '.avi', '.wmv', '.webm', '.ogg'];
    return videoExts.some(ext => String(url).toLowerCase().endsWith(ext));
}

// 视频预览状态
const videoPreview = reactive({
    visible: false,
    url: ''
})

const openVideoPreview = (url) => {
    videoPreview.url = url;
    videoPreview.visible = true;
}

const props = defineProps({
    visible: Boolean,
    order: Object
})

const emit = defineEmits(['update:visible', 'dispatch', 'cancel', 'command', 'care-summary'])

const drawerVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
})

const orderDetail = ref(null)
const order = computed(() => orderDetail.value || props.order)

const loadSeq = ref(0)

const orderLogs = ref([])
const fulfillerLogs = ref([])
const complaintList = ref([])
const serviceChangeList = ref([])

const loadOrderLogs = async (order) => {
    const id = order?.id
    if (!id) {
        orderLogs.value = []
        fulfillerLogs.value = []
        complaintList.value = []
        serviceChangeList.value = []
        return
    }
    try {
        const res = await listSubOrderLog({ orderId: id })
        const list = res?.data?.data || res?.data || []
        const arr = Array.isArray(list) ? list : []
        orderLogs.value = arr.filter(i => Number(i?.logType) === 0)
        fulfillerLogs.value = arr.filter(i => Number(i?.logType) === 1)
    } catch {
        orderLogs.value = []
        fulfillerLogs.value = []
    }

    try {
        const complaintRes = await listComplaintByOrder(id)
        complaintList.value = complaintRes?.data || []
    } catch {
        complaintList.value = []
    }

    try {
        const serviceChangeRes = await listSubOrderAppealByOrderId(id)
        serviceChangeList.value = serviceChangeRes?.data || []
    } catch {
        serviceChangeList.value = []
    }
}

const loadPetAndCustomer = async (order) => {
    const seq = ++loadSeq.value
    const next = { ...(order || {}) }

    if (next.id) {
        try {
            const orderRes = await getSubOrderInfo(next.id)
            if (orderRes.data) {
                if (orderRes.data.type == null) {
                    delete orderRes.data.type;
                } else {
                    const typeMap = { 0: 'transport', 1: 'feeding', 2: 'washing' };
                    if (typeMap[orderRes.data.type] !== undefined) {
                        orderRes.data.type = typeMap[orderRes.data.type];
                    }
                }
                Object.assign(next, orderRes.data)
                if (orderRes.data.price != null) {
                    next.fulfillerFee = (orderRes.data.price / 100).toFixed(2)
                }
                if (orderRes.data.orderCommission != null) {
                    next.orderCommission = (orderRes.data.orderCommission / 100).toFixed(2)
                }
            }
        } catch (e) {
            console.error('获取订单详细信息失败', e)
        }
    }

    const petId = next?.usrPet || next?.pet || next?.petId
    if (petId) {
        try {
            const res = await getPet(petId)
            const pet = res?.data
            console.log('Web管理端 - 宠物详情:', pet)
            if (pet) {
                next.petName = pet.name ?? next.petName
                next.petAvatar = pet.avatarUrl || pet.avatar || next.petAvatar
                next.petGender = pet.gender ?? next.petGender
                next.petAge = (pet.age !== undefined && pet.age !== null) ? `${pet.age}岁` : next.petAge
                next.petWeight = (pet.weight !== undefined && pet.weight !== null) ? `${pet.weight}kg` : next.petWeight
                next.petBreed = pet.breed ?? next.petBreed
                next.petSterilized = (pet.isSterilized !== undefined && pet.isSterilized !== null)
                    ? (Number(pet.isSterilized) === 1)
                    : next.petSterilized
                next.petVaccine = pet.vaccineStatus ?? next.petVaccine
                next.petPersonality = (pet.cutePersonality || pet.personality) ?? next.petPersonality
                next.petHealth = pet.healthStatus ?? next.petHealth
            }
        } catch {
        }
    }

    const customerId = next?.usrCustomer || next?.customer || next?.customerId
    if (customerId) {
        try {
            const res = await getCustomer(customerId)
            const customer = res?.data
            console.log('Web管理端 - 客户详情:', customer)
            if (customer) {
                next.userName = customer.name ?? next.userName
                next.userAvatar = customer.avatarUrl || customer.avatar || next.userAvatar
                next.contactPhone = customer.phone ?? next.contactPhone
                next.city = customer.areaName ?? next.city
                next.address = customer.address ?? next.address
            }
        } catch {
        }
    }

    const fulfillerId = next?.fulfiller
    if (fulfillerId) {
        try {
            const fRes = await getFulfiller(fulfillerId)
            const fulfiller = fRes?.data
            console.log('Web管理端 - 履约者详情:', fulfiller)
            if (fulfiller) {
                next.fulfillerAvatar = fulfiller.avatarUrl || fulfiller.avatar || next.fulfillerAvatar
                next.fulfillerPhone = fulfiller.phone ?? next.fulfillerPhone
                next.fulfillerStation = fulfiller.stationName ?? next.fulfillerStation
                next.fulfillerLevelName = fulfiller.levelName ?? next.fulfillerLevelName
            }
        } catch {
        }
    }

    if (seq !== loadSeq.value) return
    orderDetail.value = next
}

watch(() => props.order, (val) => {
    if (!val) {
        orderDetail.value = null
        orderLogs.value = []
        fulfillerLogs.value = []
        return
    }
    loadPetAndCustomer(val)
    loadOrderLogs(val)
}, { immediate: true, deep: true })

const activeDetailTab = ref('basic')

const getStatusName = (status) => {
    const map = { 0: '待派单', 1: '待接单', 2: '待服务', 3: '服务中', 4: '已完成', 5: '已取消', 6: '已拒绝', 7: '已关闭' }
    return map[status] || '未知'
}
const getStatusTag = (status) => {
    const map = { 0: 'danger', 1: 'warning', 2: 'primary', 3: 'primary', 4: 'success', 5: 'info', 6: 'danger', 7: 'info' }
    return map[status] || 'info'
}
const getTypeName = (type) => {
    const map = { transport: '宠物接送', feeding: '上门喂遛', washing: '上门洗护' }
    return map[type] || '-'
}
const getTransportModeName = (type) => {
    const map = { round: '往返接送', pick: '单程接(到店)', drop: '单程送(回家)' }
    return map[type] || '接送服务'
}

const previewImage = (url, urls) => {
    // 直接在新窗口打开图片
    window.open(url, '_blank')
}

const getTransportLabel = (t) => {
    if (t === 0 || t === '0') return '接'
    if (t === 1 || t === '1') return '送'
    if (t === 2 || t === '2') return '单程接'
    if (t === 3 || t === '3') return '单程送'
    return '接送'
}
const getServiceTimeRange = (timeStr) => {
    if (!timeStr) return '-'
    try {
        if (timeStr.length < 16) return timeStr
        let timePart = timeStr.substring(11, 16)
        let [hh, mm] = timePart.split(':').map(Number)
        let endH = hh + 2
        if (endH >= 24) endH -= 24
        let endHStr = endH.toString().padStart(2, '0')
        return `${timeStr}-${endHStr}:${mm.toString().padStart(2, '0')}`
    } catch (e) {
        return timeStr
    }
}

const currentOrderSteps = computed(() => {
    if (!props.order) return { active: 0, steps: [] }
    const status = props.order.status
    const logs = orderLogs.value || []
    const findTime = (keyword) => {
        const log = logs.find(l => l.title.includes(keyword) || l.content.includes(keyword))
        return log ? log.time : ''
    }

    // 已取消 — 特殊两步流程
    if (status === 5) {
        const createTime = props.order.createTime || findTime('下单') || findTime('创建')
        return {
            active: 1,
            steps: [
                { title: '商户下单', time: createTime },
                { title: '已取消', time: findTime('取消') || '订单已取消' }
            ]
        }
    }

    // 已拒绝 — 特殊两步流程
    if (status === 6) {
        const createTime = props.order.createTime || findTime('下单') || findTime('创建')
        return {
            active: 1,
            steps: [
                { title: '商户下单', time: createTime },
                { title: '已拒绝', time: findTime('拒绝') || '订单已拒绝' }
            ]
        }
    }

    // 已关闭 — 特殊两步流程
    if (status === 7) {
        const createTime = props.order.createTime || findTime('下单') || findTime('创建')
        return {
            active: 1,
            steps: [
                { title: '商户下单', time: createTime },
                { title: '已关闭', time: findTime('关闭') || '订单已关闭' }
            ]
        }
    }

    // 六步流程：商户下单 → 运营派单 → 履约接单 → 等待服务 → 服务进行 → 订单完成
    const steps = [
        { title: '商户下单', time: props.order.createTime || findTime('下单') || findTime('创建') },
        { title: '运营派单', time: findTime('派单') || '' },
        { title: '履约接单', time: findTime('接单') || '' },
        { title: '等待服务', time: findTime('到达') || '' },
        { title: '服务进行', time: findTime('完成') || '' },
        { title: '订单完成', time: findTime('完成') || '' }
    ]

    let active = 1 // 默认停在「运营派单」

    switch (status) {
        case 0:
            active = 1
            break
        case 1:
            active = 2
            steps[2].title = '等待接单'
            break
        case 2:
            active = 3
            steps[2].title = '已确认接'
            break
        case 3:
            active = 4
            steps[2].title = '已确认接'
            steps[3].title = '已到达点'
            break
        case 4:
            active = 6
            steps[2].title = '已确认接'
            steps[3].title = '已到达点'
            break
    }

    return { active, steps }
})

// 从订单日志中取派单/接单时间 @Author: Antigravity
const dispatchTime = computed(() => orderLogs.value.find(l => l.title === '系统派单')?.createTime || '-')
const acceptTime = computed(() => orderLogs.value.find(l => l.title === '接单成功')?.createTime || '-')

const serviceProgressSteps = computed(() => {
    const list = fulfillerLogs.value || []
    return list.map((i) => {
        const urls = i?.photoUrls || []
        const media = Array.isArray(urls)
            ? urls.map(url => ({ type: isVideo(url) ? 'video' : 'image', url }))
            : []

        return {
            title: i?.title || '--',
            time: i?.createTime || i?.time || '',
            icon: i.step === 4 || i.step === 99 ? 'CircleCheck' : undefined,
            color: i.step === 4 || i.step === 99 ? '#67c23a' : '#ff9900',
            desc: i?.content || '',
            media: media
        }
    })
})

const handleExportLogs = () => {
    const id = props.order?.id;
    if (!id) {
        ElMessage.warning('订单信息不完整，无法导出');
        return;
    }
    proxy?.download(
        exportSubOrderLogUrl(id),
        {},
        `OrderLogs_${props.order.orderNo}_${new Date().getTime()}.xlsx`
    );
}

// =================== 服务流程图导出（仿 platform-admin/OrderList.vue handleProcessImage 实现） ===================

/** 流程图预览弹窗状态 */
const processImageVisible = ref(false)
/** 生成的流程图 base64 DataURL */
const processImageUrl = ref('')
/** 是否正在截图中 */
const isProcessing = ref(false)
/** 截图报告时间戳（用于隐藏 DOM 渲染） */
const captureTime = ref('')
/**
 * 截图区域的图片 base64 缓存表
 * key: ossId（如果有）或图片 url（如果无 ossId）
 * value: base64 DataURL
 */
const captureBase64Cache = ref({})

/**
 * 将图片URL转换为 base64 DataURL @Author: Antigravity
 */
const loadImageAsBase64 = async (url) => {
    try {
        const response = await fetch(url);
        const blob = await response.blob();

        if (!blob || blob.size === 0) {
            console.warn('[FlowChart] 下载到的 Blob 为空:', url);
            return '';
        }

        console.log(`[FlowChart] 成功获取 Blob: 尺寸=${blob.size}, 类型=${blob.type}`);

        if (blob.type === 'application/json') {
            const text = await blob.text();
            console.error('[FlowChart] 图片下载返回了错误 JSON:', text);
            return '';
        }

        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.onloadend = () => {
                const result = reader.result;
                if (typeof result === 'string' && result.length > 100) {
                    resolve(result);
                } else {
                    console.warn('[FlowChart] 生成的 Base64 长度不足或无效:', url);
                    resolve('');
                }
            };
            reader.onerror = () => {
                console.error('[FlowChart] FileReader 读取失败');
                resolve('');
            };
            reader.readAsDataURL(blob);
        });
    } catch (err) {
        console.error('[FlowChart] 图片加载异常:', url, err);
        return '';
    }
}

/**
 * 点击「导出流程图」：
 * 1. 预加载所有图片为 base64（以解决 html2canvas 跨域无法捕获问题）
 * 2. 更新 captureTime，等 DOM 刷新
 * 3. 用 html2canvas 截取隐藏区域
 * 4. 弹窗展示预览图
 */
const handleExportProgressImage = async () => {
    if (serviceProgressSteps.value.length === 0) {
        ElMessage.warning('暂无服务进度记录，无法导出流程图');
        return;
    }
    processImageUrl.value = ''
    isProcessing.value = true
    processImageVisible.value = true
    captureTime.value = new Date().toLocaleString()
    captureBase64Cache.value = {}

    // 收集所有需要预加载的图片URL @Author: Antigravity
    const itemsToLoad = []
    for (const step of serviceProgressSteps.value) {
        if (!step.media || !step.media.length) continue
        for (const mediaItem of step.media) {
            if (mediaItem.type === 'image' && mediaItem.url) {
                if (!captureBase64Cache.value[mediaItem.url]) {
                    itemsToLoad.push(mediaItem.url)
                }
            }
        }
    }

    // 并行下载所有图片为 base64 @Author: Antigravity
    if (itemsToLoad.length > 0) {
        console.log(`[FlowChart] 开始预加载 ${itemsToLoad.length} 张图片...`);
        const results = await Promise.all(
            itemsToLoad.map(async (url) => {
                const b64 = await loadImageAsBase64(url);
                return { url, b64 };
            })
        );

        // 批量更新缓存，确保触发响应式
        const newCache = { ...captureBase64Cache.value };
        results.forEach(({ url, b64 }) => {
            if (b64) newCache[url] = b64;
        });
        captureBase64Cache.value = newCache;
        console.log('[FlowChart] 图片预加载完成，当前有效缓存数:', Object.keys(newCache).length);
    }

    // 等待 Vue DOM 更新
    await nextTick()

    // 获取截图区域并等待内部所有图片 load 完成
    const el = document.getElementById('order-process-capture-area')
    if (!el) {
        ElMessage.error('截图区域未找到')
        isProcessing.value = false
        return
    }

    // 显式等待所有图片加载完毕
    const imgs = el.querySelectorAll('img');
    if (imgs.length > 0) {
        console.log(`[FlowChart] 发现区域内有 ${imgs.length} 张图片，等待浏览器解码...`);
        await Promise.all(Array.from(imgs).map(img => {
            if (img.complete && img.naturalWidth > 0) return Promise.resolve();
            return new Promise(resolve => {
                img.onload = () => {
                    console.log('[FlowChart] 图片加载成功:', img.src.substring(0, 50) + '...');
                    resolve();
                };
                img.onerror = () => {
                    console.error('[FlowChart] 图片加载失败:', img.src.substring(0, 50) + '...');
                    resolve();
                };
                // 如果超过 3 秒还没加载完，强制继续，避免卡死
                setTimeout(resolve, 3000);
            });
        }));
    }

    // 再给 300ms 缓冲时间
    await new Promise(resolve => setTimeout(resolve, 300))

    try {
        const canvas = await html2canvas(el, {
            scale: 2,
            useCORS: true,
            allowTaint: true,
            backgroundColor: '#ffffff',
            logging: true,
            // 明确指定宽高，防止在某些浏览器下因离屏导致尺寸计算为 0
            width: el.offsetWidth,
            height: el.offsetHeight
        })
        processImageUrl.value = canvas.toDataURL('image/png')
        console.log('[FlowChart] Canvas 绘制完成');
    } catch (e) {
        console.error('[FlowChart] 生成失败:', e)
        ElMessage.error('流程图生成失败')
    } finally {
        isProcessing.value = false
    }
}

/**
 * 下载流程图到本地
 */
const downloadProcessImage = () => {
    if (!processImageUrl.value) return
    const orderNo = order.value?.orderNo || order.value?.code || 'order'
    const link = document.createElement('a')
    link.href = processImageUrl.value
    link.download = `服务流程图_${orderNo}_${new Date().getTime()}.png`
    link.click()
}

/**
 * 生成履约路径链接并复制到剪贴板
 */
const handleGenerateFulfillPath = () => {
    const id = order.value?.id
    if (!id) {
        ElMessage.warning('订单信息不完整，无法生成链接')
        return
    }
    const hostname = window.location.hostname
    const isIp = /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname)
    const baseUrl = isIp ? `http://${hostname}` : 'http://hoomeng.pet'
    const url = `${baseUrl}/fulfillPath?orderId=${id}`
    navigator.clipboard.writeText(url).then(() => {
        ElMessage.success('履约路径已复制到剪贴板')
    }).catch(() => {
        ElMessage({ message: url, type: 'success', duration: 10000, showClose: true })
    })
}
</script>

<style scoped>
/* Detail Styles */
.order-detail-drawer :deep(.el-drawer__body) {
    padding: 0 !important;
}

.detail-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f5f7fa;
}

.detail-header {
    background: #fff;
    padding: 20px 24px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.left-head {
    display: flex;
    align-items: center;
    gap: 12px;
}

.order-no {
    font-size: 20px;
    font-weight: bold;
    color: #303133;
}

.type-tag {
    font-weight: normal;
}

.detail-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.detail-scroll-area {
    flex: 1;
    overflow-y: auto;
    padding: 20px 24px;
}

/* Progress */
.progress-section {
    background: #fff;
    padding: 30px 20px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.custom-steps :deep(.el-step__title) {
    font-size: 13px;
}

/* Top Info Row */
.top-info-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    align-items: stretch;
}

.info-section {
    flex: 1;
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.sec-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f2f2f2;
}

.sec-header .label {
    font-weight: bold;
    font-size: 15px;
    color: #303133;
    border-left: 3px solid #409eff;
    padding-left: 8px;
}

/* Pet Section */
.pet-basic-row {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    align-items: center;
}

.pet-avatar-lg {
    border-radius: 8px;
    background: #ecf5ff;
    color: #409eff;
    font-size: 20px;
    font-weight: bold;
}

.pet-names {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.b-name {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 6px;
}

.b-tags {
    display: flex;
    gap: 5px;
}

.pet-desc :deep(.el-descriptions__label) {
    width: 70px;
}

/* User Section */
.u-row {
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 12px;
}

.u-info .nm {
    font-weight: bold;
    font-size: 15px;
    color: #303133;
    display: flex;
    align-items: center;
    gap: 6px;
}

.u-info .ph {
    font-size: 13px;
    color: #909399;
    margin-top: 2px;
}

.addr-box {
    background: #fdf6ec;
    padding: 8px 10px;
    border-radius: 4px;
    margin-bottom: 10px;
}

.addr-label {
    font-size: 12px;
    color: #e6a23c;
    margin-bottom: 2px;
    font-weight: bold;
}

.addr-txt {
    font-size: 13px;
    color: #606266;
    line-height: 1.4;
}

/* Tabs */
.detail-tabs {
    background: #fff;
    padding: 10px 20px;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    min-height: 400px;
}

.tab-pane-content {
    padding: 15px 0;
}

/* Fulfiller Card inside Tab */
.fulfiller-card {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 20px;
    background: #fff;
    border: 1px solid #ebeef5;
    border-radius: 8px;
}

.f-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.f-row1 {
    display: flex;
    align-items: center;
    gap: 10px;
}

.f-name {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
}

.f-row2 {
    font-size: 13px;
    color: #606266;
    display: flex;
    gap: 10px;
}

.sep {
    color: #e4e7ed;
}

.empty-state {
    padding: 40px 0;
    text-align: center;
}

/* Progress Card Styles */
.progress-card {
    background: #f8fcfb;
    border-radius: 8px;
    padding: 12px;
    border: 1px solid #ebeef5;
}

.p-title {
    margin: 0 0 8px;
    font-size: 15px;
    font-weight: bold;
    color: #303133;
}

.p-desc {
    margin: 0 0 12px;
    color: #606266;
    font-size: 13px;
    line-height: 1.5;
}

.p-media {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.media-item {
    display: inline-block;
}

.p-img {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    cursor: pointer;
    background: #f5f7fa;
}

.p-video-box {
    position: relative;
    width: 80px;
    height: 80px;
    cursor: pointer;
}

.p-video {
    object-fit: cover;
}

.play-icon-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    transition: all 0.2s;
}

.p-video-box:hover .play-icon-overlay {
    background: rgba(0, 0, 0, 0.6);
    transform: translate(-50%, -50%) scale(1.1);
}

/* New Transport Split Styles */
.transport-split-block {
    margin-top: 20px;
}

.transport-grid {
    display: flex;
    gap: 20px;
}

.transport-card {
    flex: 1;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.transport-card .t-header {
    background: #f5f7fa;
    padding: 10px 15px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.transport-card .t-header .time {
    font-size: 13px;
    font-weight: bold;
    color: #f56c6c;
}

.transport-card .t-body {
    padding: 15px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.transport-card .row {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    font-size: 14px;
    color: #303133;
    line-height: 1.4;
}

.transport-card .row.sub {
    color: #909399;
    font-size: 13px;
    margin-top: 4px;
}

.transport-card .row .el-icon {
    margin-top: 3px;
}

.transport-one {
    border: 1px solid #ebeef5;
    border-radius: 6px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
    padding: 14px 16px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.transport-one .t-row {
    display: flex;
    align-items: baseline;
    gap: 10px;
}

.transport-one .t-row .time {
    font-size: 13px;
    font-weight: bold;
    color: #f56c6c;
}

.transport-one .t-k {
    width: 40px;
    color: #909399;
    font-size: 13px;
}

.transport-one .t-v {
    color: #303133;
    font-size: 14px;
    line-height: 1.4;
}

.transport-one .t-row.sub .t-v {
    color: #909399;
    font-size: 13px;
}

/* Logs */
.log-card {
    background: #f4f4f5;
    padding: 10px 15px;
    border-radius: 4px;
    position: relative;
    top: -5px;
    width: 100%;
}

.l-tit {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 4px;
    color: #303133;
}

.l-txt {
    font-size: 13px;
    color: #606266;
    line-height: 1.5;
}
</style>
