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

        <!-- 业务订单详情抽屉：共享组件的 readonly 受限版（展示范围由组件内 v-if="!readonly" 门控） -->
        <prescription-order-detail-drawer ref="detailDrawerRef" readonly append-to-body />
    </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { usePaging } from '@/hooks/usePaging'
import { prescriptionOrderLists } from '@/api/tcm'
import PrescriptionOrderDetailDrawer from '@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue'
import {
    formatTime,
    fulfillmentText,
    fulfillmentTagType
} from '@/views/consumer/prescription/components/prescription-order-utils'

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 detailDrawerRef = ref<InstanceType<typeof PrescriptionOrderDetailDrawer>>()

function openDetail(id: number) {
    detailDrawerRef.value?.open(id)
}

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

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;
}
</style>
