<template>
	<ServicePageScaffold title="完成确认" fallback-url="/pages/mall/delivery/orders/execute">
		<ServicePanel title="完成摘要" subtitle="结算由机构端或后台处理，这里只做执行完成提交。">
			<text v-if="order != null" class="row-text">开始时间：{{ order.actualStartTime }}</text>
			<text v-if="order != null" class="row-text">结束时间：{{ order.actualEndTime == '' ? '提交后生成' : order.actualEndTime }}</text>
			<text v-if="order != null" class="row-text">完成项目：{{ completedCount }}</text>
			<text v-if="order != null" class="row-text">未完成项目：{{ incompleteCount }}</text>
			<text v-if="order != null" class="row-text">有效证据：{{ evidenceCount }}</text>
		</ServicePanel>
		<ServicePanel title="确认信息" subtitle="至少要有服务记录和必要证据，签名先采用文本签名 mock。">
			<textarea class="textarea" v-model="serviceSummary" placeholder="请填写服务总结"></textarea>
			<input class="note-input" v-model="signatureName" placeholder="请输入老人或家属签名姓名" />
			<label class="confirm-row">
				<switch :checked="confirmByFamily" color="#0f766e" @change="toggleConfirm" />
				<text class="confirm-text">已由老人/家属确认本次服务结果</text>
			</label>
		</ServicePanel>
		<button class="primary-btn" :disabled="submitting" @click="submitFinish">{{ submitting ? '提交中...' : '提交完成确认' }}</button>
	</ServicePageScaffold>
</template>

<script setup lang="uts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import ServicePageScaffold from '@/components/homeService/ServicePageScaffold.uvue'
import ServicePanel from '@/components/homeService/ServicePanel.uvue'
import type { DeliveryOrderType } from '@/types/delivery.uts'
import { finishService, getDeliveryOrderDetail } from '@/services/deliveryService.uts'
import { requireDeliveryAuth } from '@/utils/deliveryAuth.uts'
import { getDeliveryRouteParam } from '@/utils/deliveryRoute.uts'

const orderId = ref('')
const order = ref<DeliveryOrderType | null>(null)
const serviceSummary = ref('')
const signatureName = ref('')
const confirmByFamily = ref(false)
const submitting = ref(false)
const completedCount = ref(0)
const incompleteCount = ref(0)
const evidenceCount = ref(0)

function rebuildCounters() {
	if (order.value == null) {
		completedCount.value = 0
		incompleteCount.value = 0
		evidenceCount.value = 0
		return
	}
	let completed = 0
	let incomplete = 0
	for (let i = 0; i < order.value.serviceItems.length; i++) {
		if (order.value.serviceItems[i].completed) {
			completed++
		} else {
			incomplete++
		}
	}
	let evidence = 0
	for (let i = 0; i < order.value.evidenceList.length; i++) {
		if (order.value.evidenceList[i].status == 'success') {
			evidence++
		}
	}
	completedCount.value = completed
	incompleteCount.value = incomplete
	evidenceCount.value = evidence
}

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

function toggleConfirm(event: any) {
	confirmByFamily.value = event.detail.value === true
}

async function submitFinish() {
	if (submitting.value) return
	if (serviceSummary.value.trim() == '') {
		uni.showToast({ title: '请填写服务总结', icon: 'none' })
		return
	}
	if (signatureName.value.trim() == '') {
		uni.showToast({ title: '请填写签名姓名', icon: 'none' })
		return
	}
	if (!confirmByFamily.value) {
		uni.showToast({ title: '请确认已取得老人/家属确认', icon: 'none' })
		return
	}
	submitting.value = true
	try {
		await finishService(orderId.value, { serviceSummary: serviceSummary.value.trim(), signatureName: signatureName.value.trim(), confirmByFamily: confirmByFamily.value })
		uni.showToast({ title: '已提交待验收', icon: 'success' })
		uni.setStorageSync('delivery_orders_tab', 'completed')
		uni.switchTab({ url: '/pages/mall/delivery/orders/index' })
	} catch (error) {
		let message = '提交失败'
		try {
			const err = error as Error
			if (err.message != null && err.message != '') {
				message = err.message
			}
		} catch (e) {}
		uni.showToast({ title: message, icon: 'none' })
	} finally {
		submitting.value = false
	}
}

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

<style scoped>
.row-text,
.confirm-text {
	display: block;
	margin-bottom: 14rpx;
	font-size: 26rpx;
	line-height: 38rpx;
	color: #16324f;
}

.textarea {
	width: 100%;
	min-height: 220rpx;
	padding: 24rpx;
	border-radius: 20rpx;
	background: #f2f7f6;
	font-size: 28rpx;
	box-sizing: border-box;
}

.note-input {
	height: 84rpx;
	padding: 0 24rpx;
	margin-top: 18rpx;
	border-radius: 18rpx;
	background: #f2f7f6;
	font-size: 28rpx;
}

.confirm-row {
	margin-top: 18rpx;
	flex-direction: row;
	align-items: center;
}

.confirm-text {
	margin-left: 16rpx;
	margin-bottom: 0;
	flex: 1;
}

.primary-btn {
	margin-top: 24rpx;
	border-radius: 18rpx;
	background: #0f766e;
	color: #ffffff;
	font-size: 28rpx;
}
</style>