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

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

<script setup lang="ts">
import { computed, watch } from 'vue'
import { usePaging } from '@/hooks/usePaging'
import { prescriptionOrderLists } from '@/api/tcm'

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 formatAmount = (value: unknown) => {
    const n = Number(value)
    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)
}

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

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>
