<template>
    <div class="patient-order-list">
        <div v-if="!patientIdAvailable" class="po-empty-tip">
            <el-empty description="当前诊单未携带患者ID，无法列出业务订单" />
        </div>
        <template v-else>
            <el-table
                v-loading="pager.loading"
                :data="pager.lists"
                border
                stripe
                empty-text="暂无业务订单"
            >
                <el-table-column label="订单编号" prop="order_no" min-width="200" show-overflow-tooltip />
                <el-table-column label="金额" width="120" align="right">
                    <template #default="{ row }">
                        <span class="text-red-500 font-semibold">¥{{ formatAmount(row.amount) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="医生" prop="doctor_name" width="110" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.doctor_name || '—' }}
                    </template>
                </el-table-column>
                <el-table-column label="医助" prop="assistant_name" width="110" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.assistant_name || '—' }}
                    </template>
                </el-table-column>
                <el-table-column label="履约状态" width="110">
                    <template #default="{ row }">
                        <el-tag :type="fulfillmentTagType(row.fulfillment_status)" size="small" effect="light">
                            {{ fulfillmentText(row.fulfillment_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" min-width="170">
                    <template #default="{ row }">
                        {{ formatTime(row.create_time) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-perms="['tcm.prescriptionOrder/detail']"
                            type="primary"
                            link
                            @click="openDetail(row.id)"
                        >查看详情</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="flex justify-end mt-3">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </template>

        <!-- 业务订单详情抽屉（只读，与 order_list.vue 详情保持一致） -->
        <el-drawer
            v-model="detailVisible"
            size="80%"
            destroy-on-close
            :close-on-click-modal="false"
            append-to-body
        >
            <template #header>
                <div class="flex items-center">
                    <span class="font-semibold text-lg">业务订单详情</span>
                    <el-tag v-if="detailData?.order_no" type="primary" effect="plain" round class="ml-3">{{ detailData.order_no }}</el-tag>
                    <el-tag v-if="detailData?.gancao_reciperl_order_no" type="success" effect="plain" round class="ml-2">甘草 {{ detailData.gancao_reciperl_order_no }}</el-tag>
                </div>
            </template>
            <el-skeleton v-if="detailLoading" :rows="12" animated class="px-6 py-4" />
            <div v-else-if="detailData" class="px-6 pb-6 overflow-y-auto">

                <!-- 顶部数据概览 -->
                <el-row :gutter="16" class="mb-5">
                    <el-col :xs="12" :sm="6">
                        <el-card shadow="never" class="border border-gray-100 bg-gray-50/50">
                            <div class="text-gray-500 text-xs mb-1">总金额</div>
                            <div class="text-red-500 font-bold text-xl">¥{{ detailData.amount }}</div>
                        </el-card>
                    </el-col>
                    <el-col :xs="12" :sm="6">
                        <el-card shadow="never" class="border border-gray-100 bg-gray-50/50">
                            <div class="text-gray-500 text-xs mb-1">已付总额</div>
                            <div class="text-green-600 font-bold text-xl">¥{{ detailData.linked_pay_paid_total || 0 }}</div>
                        </el-card>
                    </el-col>
                    <el-col :xs="12" :sm="6">
                        <el-card shadow="never" class="border border-gray-100 bg-gray-50/50">
                            <div class="text-gray-500 text-xs mb-1">需代收</div>
                            <div class="font-bold text-xl" :class="detailAgencyToCollect > 0 ? 'text-amber-600' : 'text-gray-500'">¥{{ formatMoney(detailAgencyToCollect) }}</div>
                        </el-card>
                    </el-col>
                    <el-col :xs="12" :sm="6">
                        <el-card shadow="never" class="border border-gray-100 bg-gray-50/50">
                            <div class="text-gray-500 text-xs mb-1">已付笔数</div>
                            <div class="text-primary font-bold text-xl">{{ detailLinkedPayOrders.length }} 笔</div>
                        </el-card>
                    </el-col>
                </el-row>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <!-- 左侧：处方单（不含测试价格、改患者信息、药材明细） -->
                    <el-card shadow="never" class="border-gray-100 h-full relative overflow-hidden">
                        <div v-if="detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass"><div class="stamp-inner">审核通过</div></div>
                        <div v-if="detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject"><div class="stamp-inner">已驳回</div></div>
                        <template #header>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-3">
                                    <span class="font-medium text-[15px]">处方详情</span>
                                    <span v-if="detailData.doctor_name" class="text-xs text-gray-500">
                                        开方人：<span class="text-primary font-medium">{{ detailData.doctor_name }}</span>
                                    </span>
                                </div>
                                <span class="text-xs text-gray-400">ID: {{ detailData.prescription_id || '—' }}</span>
                            </div>
                        </template>
                        <template v-if="detailPrescription">
                            <el-descriptions :column="2" border size="small" class="bg-white">
                                <el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
                                <el-descriptions-item label="患者">{{ detailPrescription.patient_name || '—' }}</el-descriptions-item>
                                <el-descriptions-item label="性别 / 年龄">{{ detailPrescription.gender_desc || '—' }} · {{ detailPrescription.age ?? '—' }}岁</el-descriptions-item>
                                <el-descriptions-item label="手机">
                                    <span :class="detailRecipientRxPhoneMismatch ? 'text-red-600 font-bold' : ''">{{ detailPrescription.phone || '—' }}</span>
                                    <el-tag v-if="detailRecipientRxPhoneMismatch" type="danger" size="small" effect="dark" class="ml-2">与订单手机不一致</el-tag>
                                </el-descriptions-item>
                                <el-descriptions-item label="处方日期">{{ detailPrescription.prescription_date || '—' }}</el-descriptions-item>
                                <el-descriptions-item label="医师">{{ detailPrescription.doctor_name || '—' }}</el-descriptions-item>
                                <el-descriptions-item label="类型">{{ detailPrescription.prescription_type || '—' }}</el-descriptions-item>
                                <el-descriptions-item label="临床诊断" :span="2">{{ detailPrescription.clinical_diagnosis || '—' }}</el-descriptions-item>
                                <el-descriptions-item label="剂数 / 用法" :span="2">
                                    {{ detailData.dose_count ?? detailPrescription.dose_count ?? '—' }} {{ detailData.dose_unit || '剂' }} ·
                                    {{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
                                </el-descriptions-item>
                                <el-descriptions-item label="处方金额">
                                    <span class="text-red-500 font-medium">¥{{ detailPrescription.amount ?? '—' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="消费者审核">
                                    <el-tag :type="consumerRxAuditTag(detailPrescription.audit_status)" size="small">{{ consumerRxAuditText(detailPrescription.audit_status) }}</el-tag>
                                </el-descriptions-item>
                                <el-descriptions-item label="用量">
                                    <template v-if="detailPrescription.dosage_amount">
                                        {{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
                                        <template v-if="detailPrescription.prescription_type === '浓缩水丸'">
                                            · {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
                                        </template>
                                        <span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
                                            ({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
                                        </span>
                                    </template>
                                    <template v-else>—</template>
                                </el-descriptions-item>
                                <el-descriptions-item label="服用方式">
                                    <div class="flex flex-col gap-1.5 text-sm leading-relaxed">
                                        <div>
                                            <span class="text-gray-500">每天次数：</span>
                                            {{ detailPrescription.times_per_day ? detailPrescription.times_per_day + ' 次' : '—' }}
                                        </div>
                                        <div>
                                            <span class="text-gray-500">处方开立：</span>
                                            {{ detailPrescription.usage_days != null && detailPrescription.usage_days !== '' ? detailPrescription.usage_days + ' 天' : '—' }}
                                        </div>
                                        <div>
                                            <span class="text-gray-500">订单设置：</span>
                                            {{ detailData.medication_days != null && String(detailData.medication_days).trim() !== '' ? detailData.medication_days + ' 天' : '—' }}
                                        </div>
                                    </div>
                                </el-descriptions-item>
                                <el-descriptions-item label="状态" :span="2">
                                    <el-tag :type="Number(detailPrescription.void_status) === 1 ? 'danger' : 'success'" size="small">{{ Number(detailPrescription.void_status) === 1 ? '已作废' : '正常' }}</el-tag>
                                </el-descriptions-item>
                            </el-descriptions>
                        </template>
                        <el-empty v-else description="无处方数据" :image-size="72" />
                    </el-card>

                    <!-- 右侧：未关联 + 已关联支付单 -->
                    <div class="flex flex-col gap-4 h-full">
                        <el-card shadow="never" class="border-gray-100">
                            <template #header>
                                <div class="flex items-center justify-between">
                                    <span class="font-medium text-[15px]">未关联的收款记录</span>
                                    <span class="text-xs text-gray-400">本诊单下未被占用的支付单</span>
                                </div>
                            </template>
                            <el-table v-if="detailUnlinkedPayOrders.length" :data="detailUnlinkedPayOrders" size="small" border stripe max-height="280">
                                <el-table-column prop="id" label="ID" width="70" />
                                <el-table-column prop="order_no" label="单号" min-width="135" show-overflow-tooltip />
                                <el-table-column label="类型" width="90">
                                    <template #default="{ row }">{{ row.order_type_desc || feeTypeText(row.order_type) }}</template>
                                </el-table-column>
                                <el-table-column label="金额" width="86" align="right">
                                    <template #default="{ row }"><span class="text-red-500">¥{{ row.amount }}</span></template>
                                </el-table-column>
                                <el-table-column label="状态" width="82" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="payOrderStatusTag(row.status)" size="small">{{ row.status_desc || orderStatusText(row.status) }}</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="creator_name" label="创建人" width="80" show-overflow-tooltip />
                                <el-table-column label="创建时间" min-width="136">
                                    <template #default="{ row }">{{ formatOrderTime(row.create_time) }}</template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-else description="无未关联的收款单" :image-size="60" />
                        </el-card>

                        <el-card shadow="never" class="border-gray-100 relative overflow-hidden">
                            <div v-if="detailData.payment_slip_audit_status === 1" class="audit-stamp stamp-pass"><div class="stamp-inner">审核通过</div></div>
                            <div v-if="detailData.payment_slip_audit_status === 2" class="audit-stamp stamp-reject"><div class="stamp-inner">已驳回</div></div>
                            <template #header>
                                <div class="flex items-center gap-3">
                                    <span class="font-medium text-[15px]">关联收款记录</span>
                                    <span v-if="detailData.creator_name" class="text-xs text-gray-500">创建人：<span class="text-primary font-medium">{{ detailData.creator_name }}</span></span>
                                </div>
                            </template>
                            <el-table v-if="detailLinkedPayOrders.length" :data="detailLinkedPayOrders" size="small" border stripe max-height="280">
                                <el-table-column prop="id" label="ID" width="70" />
                                <el-table-column prop="order_no" label="单号" min-width="135" show-overflow-tooltip />
                                <el-table-column label="类型" width="90">
                                    <template #default="{ row }">{{ row.order_type_desc || feeTypeText(row.order_type) }}</template>
                                </el-table-column>
                                <el-table-column label="金额" width="86" align="right">
                                    <template #default="{ row }"><span class="text-red-500">¥{{ row.amount }}</span></template>
                                </el-table-column>
                                <el-table-column label="状态" width="82" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="payOrderStatusTag(row.status)" size="small">{{ row.status_desc || orderStatusText(row.status) }}</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="creator_name" label="创建人" width="80" show-overflow-tooltip />
                                <el-table-column label="创建时间" min-width="136">
                                    <template #default="{ row }">{{ formatOrderTime(row.create_time) }}</template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-else description="未关联收款单" :image-size="60" />
                        </el-card>
                    </div>
                </div>

                <!-- 履约与收货信息 -->
                <el-card shadow="never" class="border-gray-100 mb-4">
                    <template #header><span class="font-medium text-[15px]">履约与收货信息</span></template>
                    <el-descriptions :column="3" border size="small">
                        <el-descriptions-item label="诊单ID" :span="3"><span class="font-mono">{{ detailData.diagnosis_id }}</span></el-descriptions-item>
                        <el-descriptions-item label="创建时间">{{ formatTime(detailData.create_time) }}</el-descriptions-item>
                        <el-descriptions-item label="业务订单创建人" :span="2">
                            <div v-if="detailData.creator_name" class="text-[13px] space-y-1">
                                <div><span class="font-medium text-gray-900">{{ detailData.creator_name || '—' }}</span></div>
                                <div v-if="detailOrderCreatorMetaLine" class="text-gray-600 text-xs">{{ detailOrderCreatorMetaLine }}</div>
                            </div>
                            <span v-else class="text-gray-400">—</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="创建人所属部门" :span="3">
                            <div v-if="detailOrderCreatorDeptBreadcrumbs.length" class="space-y-1.5">
                                <div v-for="(segments, idx) in detailOrderCreatorDeptBreadcrumbs" :key="idx">
                                    <el-breadcrumb v-if="segments.length" class="text-[13px]" separator="/">
                                        <el-breadcrumb-item v-for="(name, j) in segments" :key="j"><span class="text-gray-800">{{ name }}</span></el-breadcrumb-item>
                                    </el-breadcrumb>
                                </div>
                            </div>
                            <span v-else class="text-gray-400">—</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="收货人">{{ detailData.recipient_name }}</el-descriptions-item>
                        <el-descriptions-item label="收货手机">
                            <span :class="detailRecipientRxPhoneMismatch ? 'text-red-600 font-bold font-mono' : 'font-mono'">{{ detailData.recipient_phone || '—' }}</span>
                            <el-tag v-if="detailRecipientRxPhoneMismatch" type="danger" size="small" effect="dark" class="ml-2">与处方手机不一致</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="收货地址">{{ detailFullAddress }}</el-descriptions-item>
                        <el-descriptions-item label="复诊">{{ detailData.is_follow_up ? '是' : '否' }}</el-descriptions-item>
                        <el-descriptions-item label="用药疗程">{{ detailData.medication_days ? detailData.medication_days + ' 天' : '—' }}</el-descriptions-item>
                        <el-descriptions-item label="上次医护">{{ detailData.prev_staff || '—' }}</el-descriptions-item>
                        <el-descriptions-item label="服务渠道">{{ detailData.service_channel || '—' }}</el-descriptions-item>
                        <el-descriptions-item label="费用类别">{{ feeTypeText(detailData.fee_type) }}</el-descriptions-item>
                        <el-descriptions-item label="快递单号">{{ detailData.tracking_number || '—' }}</el-descriptions-item>
                        <el-descriptions-item label="快递公司">{{ expressCompanyLabel(detailData.express_company) }}</el-descriptions-item>
                        <el-descriptions-item v-perms="['tcm.prescriptionOrder/editRemarkExtra']" label="药房备注" :span="3">{{ detailData.remark_extra || '—' }}</el-descriptions-item>
                        <el-descriptions-item label="医助备注" :span="3">{{ detailData.remark_assistant || '—' }}</el-descriptions-item>
                        <el-descriptions-item label="处方审核意见" :span="3">{{ detailData.prescription_audit_remark || '—' }}</el-descriptions-item>
                        <el-descriptions-item label="支付审核意见" :span="3">{{ detailData.payment_slip_audit_remark || '—' }}</el-descriptions-item>
                    </el-descriptions>
                </el-card>

                <!-- 物流轨迹（只读） -->
                <el-card v-if="String(detailData.tracking_number || '').trim()" shadow="never" class="border-gray-100 mb-4">
                    <template #header><span class="font-medium text-[15px]">物流轨迹</span></template>
                    <div class="flex flex-wrap items-center gap-3 mb-4">
                        <el-input v-model="logisticsTracePhoneTail" clearable maxlength="20" placeholder="收件手机" class="w-[180px]" @keyup.enter="fetchLogisticsTrace" />
                        <el-select v-model="detailLogisticsExpress" placeholder="承运商" style="width: 140px">
                            <el-option label="自动识别" value="auto" />
                            <el-option label="顺丰速运" value="sf" />
                            <el-option label="京东快递" value="jd" />
                            <el-option label="极兔速递" value="jt" />
                        </el-select>
                        <el-button v-perms="['tcm.prescriptionOrder/logisticsTrace']" type="primary" plain size="default" :loading="logisticsTraceLoading" @click="fetchLogisticsTrace">刷新轨迹</el-button>
                    </div>
                    <div v-if="logisticsTraceLoading && !logisticsTracePayload" class="py-6 text-center text-sm text-gray-500">正在加载物流轨迹...</div>
                    <div v-else-if="logisticsTracePayload" class="bg-gray-50/50 p-4 rounded-md">
                        <div v-if="logisticsTracePayload.state_text" class="text-sm mb-4 font-medium flex items-center gap-2">
                            <span class="text-gray-800">状态：{{ logisticsTracePayload.state_text }}</span>
                            <el-tag v-if="logisticsTracePayload.carrier_label" size="small" type="info">{{ logisticsTracePayload.carrier_label }}</el-tag>
                        </div>
                        <el-timeline v-if="logisticsTraceList.length" class="mt-2 pl-2">
                            <el-timeline-item v-for="(t, idx) in logisticsTraceList" :key="idx" :type="idx === 0 ? 'primary' : 'info'" :hollow="idx !== 0" :timestamp="t.time" placement="top">
                                <span :class="idx === 0 ? 'text-gray-800 font-medium' : 'text-gray-500'">{{ t.context }}</span>
                            </el-timeline-item>
                        </el-timeline>
                        <el-empty v-else description="暂无轨迹节点记录" :image-size="64" />
                    </div>
                </el-card>

                <!-- 操作日志 -->
                <el-card v-perms="['tcm.prescriptionOrder/logs']" shadow="never" class="border-gray-100">
                    <template #header><span class="font-medium text-[15px]">操作日志</span></template>
                    <el-timeline v-if="detailLogs.length" class="mt-2 pl-2">
                        <el-timeline-item v-for="(log, idx) in detailLogs" :key="log.id" :type="idx === 0 ? 'primary' : 'info'" :hollow="idx !== 0" :timestamp="formatTime(log.create_time)" placement="top">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="font-medium text-[13px]">{{ log.admin_name }}</span>
                                <el-tag size="small" type="info">{{ logActionText(log.action) }}</el-tag>
                            </div>
                            <span :class="idx === 0 ? 'text-gray-800 font-medium' : 'text-gray-500'">{{ log.summary }}</span>
                        </el-timeline-item>
                    </el-timeline>
                    <el-empty v-else description="暂无操作日志" :image-size="64" />
                </el-card>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import { usePaging } from '@/hooks/usePaging'
import {
    prescriptionOrderLists,
    prescriptionOrderDetail,
    prescriptionOrderLogs,
    prescriptionOrderLogisticsTrace,
    prescriptionOrderPaidPayOrders
} from '@/api/tcm'
import { hasPermission } from '@/utils/perm'
import feedback from '@/utils/feedback'
import useUserStore from '@/stores/modules/user'

const userStore = useUserStore()

const props = defineProps<{
    diagnosisId: number
    patientId?: number | string
}>()

const patientIdNum = computed(() => {
    const n = Number(props.patientId)
    return Number.isFinite(n) && n > 0 ? n : 0
})
const patientIdAvailable = computed(() => patientIdNum.value > 0)

const queryParams = reactive<Record<string, number | string>>({})

const { pager, getLists, resetPage } = usePaging({
    fetchFun: prescriptionOrderLists,
    params: queryParams,
    size: 10
})

const buildParams = () => {
    Object.keys(queryParams).forEach((k) => delete queryParams[k])
    if (props.diagnosisId > 0) {
        queryParams.context_diagnosis_id = props.diagnosisId
    }
    if (patientIdAvailable.value) {
        queryParams.patient_id = patientIdNum.value
    }
    queryParams.scene = 'diagnosis_edit'
}

// ─── 详情抽屉 ───
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<any>(null)
const detailLogs = ref<any[]>([])
const detailUnlinkedPayOrders = ref<any[]>([])

const detailPrescription = computed(() => {
    const p = detailData.value?.prescription
    return p && typeof p === 'object' ? p : null
})

const detailLinkedPayOrders = computed(() => {
    const arr = detailData.value?.linked_pay_orders
    return Array.isArray(arr) ? arr : []
})

const detailAgencyToCollect = computed(() => {
    const d = detailData.value
    if (!d) return 0
    const total = Number(d.amount) || 0
    const paid = Number(d.linked_pay_paid_total) || 0
    return Math.round((total - paid) * 100) / 100
})

const detailRecipientRxPhoneMismatch = computed(() => {
    const rx = normalizeBizPhone(detailPrescription.value?.phone)
    const biz = normalizeBizPhone(detailData.value?.recipient_phone)
    if (!rx || !biz) return false
    return rx !== biz
})

const detailFullAddress = computed(() => {
    const d = detailData.value
    if (!d) return '—'
    const parts = []
    if (d.shipping_province) parts.push(d.shipping_province)
    if (d.shipping_city) parts.push(d.shipping_city)
    if (d.shipping_district) parts.push(d.shipping_district)
    if (d.shipping_address) parts.push(d.shipping_address)
    return parts.length > 0 ? parts.join(' ') : '—'
})

const detailOrderCreatorMetaLine = computed(() => {
    const d = detailData.value
    if (!d) return ''
    const account = String(d.creator_account ?? '').trim()
    const mobile = String(d.creator_mobile ?? '').trim()
    const parts: string[] = []
    if (account) parts.push(`登录账号：${account}`)
    if (mobile) parts.push(`手机：${mobile}`)
    return parts.join(' · ')
})

const detailOrderCreatorDeptBreadcrumbs = computed(() => {
    const raw = String(detailData.value?.order_creator_dept_path ?? detailData.value?.diagnosis_creator_dept_path ?? '').trim()
    if (!raw) return [] as string[][]
    return raw.split('；').map((s) => s.trim()).filter(Boolean)
        .map((p) => p.includes(' / ') ? p.split(' / ').map((x) => x.trim()).filter(Boolean) : p.split('/').map((x) => x.trim()).filter(Boolean))
        .filter((segs) => segs.length > 0)
})

// ─── 物流轨迹 ───
const detailLogisticsExpress = ref<string>('auto')
const logisticsTraceLoading = ref(false)
const logisticsTracePayload = ref<Record<string, any> | null>(null)
const logisticsTracePhoneTail = ref('')

const logisticsTraceList = computed(() => {
    const p = logisticsTracePayload.value
    if (!p || !Array.isArray(p.traces)) return []
    return p.traces as Array<{ time: string; context: string }>
})

async function fetchLogisticsTrace() {
    const id = Number(detailData.value?.id)
    if (!id) return
    logisticsTraceLoading.value = true
    try {
        const digits = String(logisticsTracePhoneTail.value || '').replace(/\D/g, '')
        const params: { id: number; express_company?: string; phone_tail?: string } = {
            id,
            express_company: detailLogisticsExpress.value
        }
        if (digits.length >= 4) params.phone_tail = digits
        const res: any = await prescriptionOrderLogisticsTrace(params)
        logisticsTracePayload.value = (res?.data ?? res) as Record<string, any>
    } catch {
        logisticsTracePayload.value = null
    } finally {
        logisticsTraceLoading.value = false
    }
}

// ─── 打开详情 ───
async function openDetail(id: number) {
    detailData.value = null
    detailUnlinkedPayOrders.value = []
    logisticsTracePayload.value = null
    detailLogisticsExpress.value = 'auto'
    logisticsTracePhoneTail.value = ''
    detailLogs.value = []

    detailVisible.value = true
    detailLoading.value = true
    try {
        const res: any = await prescriptionOrderDetail({ id })
        const d = res?.data ?? res ?? null
        detailData.value = d
        if (d) {
            detailLogisticsExpress.value = String(d.express_company || 'auto') || 'auto'
            const dig = String(d.recipient_phone || '').replace(/\D/g, '')
            logisticsTracePhoneTail.value = dig.length >= 4 ? dig : ''
            if (String(d.tracking_number || '').trim()) fetchLogisticsTrace()
            fetchLogs(id)
            if (d.diagnosis_id) {
                loadDetailUnlinkedPayOrders(d.diagnosis_id, id, d.pay_order_ids || [])
            }
        }
    } catch (e: any) {
        feedback.msgError(e?.message || '加载详情失败')
        detailVisible.value = false
    } finally {
        detailLoading.value = false
    }
}

async function loadDetailUnlinkedPayOrders(diagnosisId: number, prescriptionOrderId: number, linkedIds: number[]) {
    if (!diagnosisId) { detailUnlinkedPayOrders.value = []; return }
    try {
        const res: any = await prescriptionOrderPaidPayOrders({ diagnosis_id: diagnosisId, prescription_order_id: prescriptionOrderId })
        const lists = res?.lists ?? res?.data?.lists ?? []
        detailUnlinkedPayOrders.value = Array.isArray(lists) ? lists.filter((item: any) => !linkedIds.includes(item.id)) : []
    } catch { detailUnlinkedPayOrders.value = [] }
}

function canViewPrescriptionOrderLogs() {
    const p = userStore.perms || []
    return p.includes('*') || p.includes('tcm.prescriptionOrder/logs')
}

async function fetchLogs(id: number) {
    if (!canViewPrescriptionOrderLogs()) { detailLogs.value = []; return }
    try {
        const res: any = await prescriptionOrderLogs({ id })
        detailLogs.value = res?.data ?? res ?? []
    } catch { detailLogs.value = [] }
}

// ─── 工具函数 ───
function normalizeBizPhone(v: unknown): string {
    if (v === null || v === undefined) return ''
    return String(v).replace(/\s/g, '').trim()
}

const formatAmount = (value: unknown) => {
    const n = Number(value)
    return Number.isFinite(n) ? n.toFixed(2) : '0.00'
}

function formatMoney(v: unknown) {
    const n = Number(v)
    return Number.isFinite(n) ? n.toFixed(2) : '0.00'
}

const formatTime = (value: unknown) => {
    if (value === null || value === undefined || value === '') return '—'
    if (typeof value === 'number' && value > 1e9 && value < 1e11) {
        const d = new Date(value * 1000)
        const pad = (n: number) => String(n).padStart(2, '0')
        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
    }
    return String(value)
}

function formatOrderTime(v: unknown) {
    if (v === null || v === undefined || v === '') return '—'
    if (typeof v === 'string' && String(v).includes('-')) return String(v)
    return formatTime(v)
}

function feeTypeText(t: number | undefined) {
    const m: Record<number, string> = { 1: '药费', 2: '诊费', 3: '药费+诊费', 4: '其他' }
    return m[Number(t)] ?? '—'
}

function expressCompanyLabel(v: unknown) {
    const s = String(v || '').toLowerCase()
    if (s === 'sf') return '顺丰速运'
    if (s === 'jd') return '京东快递'
    if (s === 'jt' || s === 'jtexpress') return '极兔速递'
    return '自动识别'
}

function consumerRxAuditText(s: number | undefined) {
    const n = Number(s)
    if (n === 1) return '已通过'
    if (n === 2) return '已驳回'
    return '待审核'
}

function consumerRxAuditTag(s: number | undefined): 'success' | 'warning' | 'danger' | 'info' {
    const n = Number(s)
    if (n === 1) return 'success'
    if (n === 2) return 'danger'
    return 'warning'
}

function payOrderStatusTag(s: number | undefined): 'success' | 'warning' | 'danger' | 'info' {
    const n = Number(s)
    if (n === 2) return 'success'
    if (n === 1) return 'warning'
    return 'info'
}

function orderStatusText(s: number | undefined) {
    const m: Record<number, string> = { 0: '待支付', 1: '待支付', 2: '已支付', 3: '已取消' }
    return m[Number(s)] ?? '—'
}

const fulfillmentText = (s: number | undefined) => {
    const m: Record<number, string> = { 1: '待双审通过', 2: '待发货', 3: '已完成', 4: '已取消', 5: '已发货', 6: '已签收', 7: '进行中', 8: '暂不制药', 9: '拒收', 10: '退款', 11: '保留药方', 12: '制药缓发' }
    return m[Number(s)] ?? '—'
}

const fulfillmentTagType = (s: number | undefined): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
    const n = Number(s)
    if (n === 3 || n === 6) return 'success'
    if (n === 5) return 'primary'
    if (n === 4 || n === 9 || n === 10) return 'danger'
    if (n === 2 || n === 7) return 'warning'
    if (n === 8 || n === 11 || n === 12) return 'info'
    return 'info'
}

function logActionText(act: string) {
    const m: Record<string, string> = {
        create: '创建', edit: '编辑', audit_rx_approve: '处方审核', audit_rx_reject: '处方审核',
        audit_pay_approve: '支付审核', audit_pay_reject: '支付审核', fill_tracking: '填快递单',
        ship: '确认发货', withdraw: '撤销', link_pay_order: '关联支付单',
        revoke_rx_audit: '撤回处方审核', revoke_pay_audit: '撤回支付审核',
        gancao_submit: '甘草下单', patch_rx_patient: '处方患者信息',
        update_amount: '修改订单金额', complete: '完成订单'
    }
    return m[act] || act
}

watch(
    () => [props.diagnosisId, patientIdNum.value] as const,
    () => {
        if (!patientIdAvailable.value) { pager.lists = []; pager.count = 0; return }
        buildParams()
        resetPage()
    },
    { immediate: true }
)

defineExpose({ refresh: () => getLists() })
</script>

<style scoped lang="scss">
.patient-order-list {
    padding: 4px 0;
}
.po-empty-tip {
    padding: 24px 0;
}
.audit-stamp {
    position: absolute;
    top: 12px;
    right: 16px;
    transform: rotate(15deg);
    opacity: 0.15;
    pointer-events: none;
    z-index: 1;
}
.stamp-inner {
    border: 3px solid currentColor;
    border-radius: 8px;
    padding: 4px 12px;
    font-size: 18px;
    font-weight: bold;
}
.stamp-pass { color: #22c55e; }
.stamp-reject { color: #ef4444; }
</style>
