<template>
	<ServicePageScaffold title="订单详情" fallback-url="/pages/mall/delivery/orders/index">
		<view v-if="order != null" class="page">
			<view class="status-card">
				<view class="status-head">
					<view>
						<text class="status-title">当前状态</text>
						<text class="status-subtitle">{{ order.statusText }}</text>
					</view>
					<text class="status-tag">{{ nextStepText }}</text>
				</view>
				<view class="timeline-box">
					<view v-for="item in order.timeline" :key="item.id" class="timeline-item">
						<text class="timeline-title">{{ item.title }}</text>
						<text class="timeline-meta">{{ item.time }}</text>
						<text class="timeline-desc">{{ item.description }}</text>
					</view>
				</view>
			</view>

			<view class="card">
				<text class="section-title">服务信息</text>
				<text class="row-text">服务名称：{{ order.serviceName }}</text>
				<text class="row-text">服务类型：{{ order.serviceType }}</text>
				<text class="row-text">预约时间：{{ order.appointmentTime }}</text>
				<text class="row-text">预计时长：{{ order.duration }} 分钟</text>
				<text class="row-text">服务价格：¥{{ order.price }}</text>
				<text class="row-text">预计收入：¥{{ order.staffIncome }}</text>
			</view>

			<view class="card">
				<text class="section-title">服务对象</text>
				<text class="row-text">姓名：{{ order.elderName }}</text>
				<text class="row-text">性别：{{ order.elderGender }}</text>
				<text class="row-text">年龄：{{ order.elderAge }}</text>
				<text class="row-text">电话：{{ order.elderPhone }}</text>
				<text class="row-text">健康标签：{{ joinTags(order.healthTags) }}</text>
			</view>

			<view class="card">
				<text class="section-title">联系人信息</text>
				<text class="row-text">联系人：{{ order.contactName }}</text>
				<text class="row-text">联系电话：{{ order.contactPhone }}</text>
				<text class="row-text">关系：{{ order.contactRelation }}</text>
				<view class="inline-actions">
					<view class="outline-btn" @click="makePhoneCall(order.contactPhone)"><text class="outline-btn-text">拨打联系人</text></view>
					<view class="outline-btn" @click="makePhoneCall(order.elderPhone)"><text class="outline-btn-text">拨打服务对象</text></view>
				</view>
			</view>

			<view class="card">
				<text class="section-title">地址信息</text>
				<text class="row-text">完整地址：{{ order.address }}</text>
				<text class="row-text">门牌号：{{ order.addressDetail }}</text>
				<text class="row-text">距离：{{ order.distance }}</text>
				<view class="inline-actions">
					<view class="outline-btn" @click="mockNavigate"><text class="outline-btn-text">导航按钮</text></view>
					<view class="outline-btn" @click="makePhoneCall(order.contactPhone)"><text class="outline-btn-text">拨打电话</text></view>
				</view>
			</view>

			<view class="card">
				<text class="section-title">用户备注</text>
				<text class="row-text">特殊需求：{{ order.remark }}</text>
				<text class="row-text">需家属在场：{{ order.needFamilyPresent ? '是' : '否' }}</text>
				<text class="row-text">需携带耗材：{{ order.needMaterials ? '是' : '否' }}</text>
				<text class="row-text">风险标签：{{ joinTags(order.riskTags) }}</text>
			</view>

			<view v-if="order.abnormalReport != null" class="card">
				<text class="section-title">异常记录</text>
				<text class="row-text">异常类型：{{ order.abnormalReport!.type }}</text>
				<text class="row-text">异常说明：{{ order.abnormalReport!.description }}</text>
				<text class="row-text">发生时间：{{ order.abnormalReport!.occurredAt }}</text>
			</view>

			<view class="action-card">
				<view class="action-row">
					<view class="outline-btn" @click="goException"><text class="outline-btn-text">异常上报</text></view>
					<view v-if="showRejectButton" class="warn-btn" @click="rejectOrder"><text class="warn-btn-text">拒单</text></view>
					<view class="primary-btn" @click="handlePrimary"><text class="primary-btn-text">{{ primaryText }}</text></view>
				</view>
			</view>
		</view>
	</ServicePageScaffold>
</template>

<script setup lang="uts">
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import ServicePageScaffold from '@/components/homeService/ServicePageScaffold.uvue'
import type { DeliveryOrderType } from '@/types/delivery.uts'
import {
	acceptServiceOrder,
	getServiceOrderDetail,
	rejectServiceOrder
} from '@/services/deliveryService.uts'
import { getNextStepText, getPrimaryActionText } from '@/utils/deliveryCareUi.uts'
import { requireDeliveryAuth } from '@/utils/deliveryAuth.uts'
import { getDeliveryRouteParam } from '@/utils/deliveryRoute.uts'

const orderId = ref('')
const order = ref<DeliveryOrderType | null>(null)

const primaryText = computed((): string => order.value == null ? '查看详情' : getPrimaryActionText(order.value!.status))
const nextStepText = computed((): string => order.value == null ? '' : getNextStepText(order.value!.status))
const showRejectButton = computed((): boolean => order.value != null && (order.value!.status == 'pending_assignment' || order.value!.status == 'pending_accept'))

async function loadData() {
	const authResult = await requireDeliveryAuth({ redirectOnFail: true, toastOnFail: true })
	if (!authResult.ok || orderId.value == '') {
		return
	}
	order.value = await getServiceOrderDetail(orderId.value)
}

function joinTags(tags: Array<string>): string {
	if (tags.length == 0) return '无'
	return tags.join(' / ')
}

function makePhoneCall(phone: string) {
	uni.makePhoneCall({ phoneNumber: phone })
}

function mockNavigate() {
	if (order.value == null) {
		return
	}
	uni.navigateTo({ url: '/pages/mall/delivery/orders/route?id=' + order.value!.id })
}

function goException() {
	uni.navigateTo({ url: '/pages/mall/delivery/orders/exception?id=' + orderId.value })
}

function goRecord() {
	uni.navigateTo({ url: '/pages/mall/delivery/service-record/index?id=' + orderId.value })
}

async function rejectOrder() {
	uni.showActionSheet({
		itemList: ['时间冲突', '距离过远', '技能不匹配', '其他原因'],
		success: async (result) => {
			const reasons = ['时间冲突', '距离过远', '技能不匹配', '其他原因']
			await rejectServiceOrder(orderId.value, reasons[result.tapIndex])
			uni.showToast({ title: '已拒单', icon: 'success' })
			loadData()
		}
	})
}

async function handlePrimary() {
	if (order.value == null) {
		return
	}
	const status = order.value.status
	if (status == 'pending_assignment' || status == 'pending_accept') {
		await acceptServiceOrder(orderId.value)
		uni.showToast({ title: '已接单', icon: 'success' })
		loadData()
		return
	}
	if (status == 'accepted' || status == 'waiting_departure') {
		uni.navigateTo({ url: '/pages/mall/delivery/orders/route?id=' + orderId.value })
		return
	}
	if (status == 'departed' || status == 'on_the_way') {
		uni.navigateTo({ url: '/pages/mall/delivery/orders/route?id=' + orderId.value })
		return
	}
	if (status == 'arrived') {
		uni.navigateTo({ url: '/pages/mall/delivery/orders/checkin?id=' + orderId.value })
		return
	}
	if (status == 'in_service' || status == 'serving' || status == 'completed') {
		goRecord()
		return
	}
	if (status == 'pending_confirm' || status == 'pending_acceptance' || status == 'pending_submit') {
		uni.showToast({ title: '已完成服务，等待用户验收', icon: 'none' })
		return
	}
	if (status == 'abnormal' || status == 'exception_pending') {
		goException()
		return
	}
	goRecord()
}

onLoad((options) => {
	if (options != null) {
		orderId.value = getDeliveryRouteParam(options as UTSJSONObject, 'id')
	}
	loadData()
})
</script>

<style scoped>
.page {
	padding-bottom: 32rpx;
}

.status-card,
.card,
.action-card {
	margin-bottom: 18rpx;
	padding: 24rpx;
	border-radius: 24rpx;
	background-color: #ffffff;
	box-shadow: 0 10rpx 24rpx rgba(15, 35, 55, 0.06);
}

.status-head,
.inline-actions,
.action-row {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}

.status-title,
.section-title,
.timeline-title,
.primary-btn-text {
	font-weight: 700;
}

.status-title,
.section-title {
	font-size: 30rpx;
	color: #16324f;
}

.status-subtitle,
.status-tag,
.row-text,
.timeline-meta,
.timeline-desc,
.outline-btn-text,
.warn-btn-text {
	font-size: 24rpx;
	line-height: 36rpx;
}

.status-subtitle,
.timeline-meta,
.timeline-desc,
.outline-btn-text {
	color: #5e758c;
}

.status-tag {
	padding: 10rpx 18rpx;
	border-radius: 999rpx;
	background-color: #e6f3fa;
	color: #176e97;
}

.timeline-box {
	margin-top: 18rpx;
	padding: 18rpx;
	border-radius: 18rpx;
	background-color: #f7fbfd;
}

.timeline-item {
	margin-bottom: 16rpx;
}

.timeline-title {
	font-size: 26rpx;
	color: #16324f;
}

.row-text {
	display: block;
	margin-top: 12rpx;
	color: #16324f;
}

.inline-actions,
.action-row {
	margin-top: 18rpx;
}

.outline-btn,
.warn-btn,
.primary-btn {
	width: 31%;
	padding: 18rpx 0;
	border-radius: 18rpx;
	align-items: center;
	justify-content: center;
}

.outline-btn {
	background-color: #eef6fa;
}

.warn-btn {
	background-color: #fff3e6;
}

.warn-btn-text {
	color: #c77413;
	font-weight: 700;
}

.primary-btn {
	background-color: #1f7db4;
}

.primary-btn-text {
	font-size: 26rpx;
	color: #ffffff;
}
</style>