<template>
	<view>
		<view class="px-24rpx py-20rpx bg-[f2f2f2] min-h-[calc(100vh-230rpx)]">
			<view class="rounded-16rpx bg-#fff pt-24rpx pb-16rpx">
				<view class="flex items-center">
					<view
						class="relative flex-1 flex-col items-center flex"
						v-for="item in list"
						:key="item.id"
					>
						<image
							:src="
								current >= item.id
									? $assets('/step-active.png')
									: $assets('/step.png')
							"
							class="w-76rpx h-76rpx"
						/>
						<text class="text-white absolute top-18rpx z-10 text-28rpx">{{
							item.id
						}}</text>
						<view
							:class="current >= item.id ? 'text-#FF8CA6' : 'text-#999'"
							class="text-24rpx mt-12rpx"
							>{{ item.label }}</view
						>
						<view
							v-if="item.id < list.length"
							:class="current >= item.id ? 'bg-#FF8CA6' : 'bg-#999'"
							class="step-line absolute left-77% top-30% h-4rpx w-46% rounded-md"
						></view>
					</view>
				</view>
			</view>
			<view
				@click="handleShowPicker"
				class="rounded-16rpx bg-#fff pt-24rpx pr-16rpx pl-30rpx pt-36rpx pb-34rpx my-20rpx flex items-center justify-between"
			>
				<text class="text-34rpx font-bold">服务项目</text>
				<u-icon
					:label="typeVal"
					space="20rpx"
					labelColor="#FF8CA6"
					labelSize="28rpx"
					labelPos="left"
					name="arrow-right"
					width="48rpx"
					height="48rpx"
					color="#666"
					bold
				/>
			</view>
			<view class="rounded-16rpx overflow-hidden bg-#fff px-20rpx pb-20rpx">
				<u--form
					labelPosition="left"
					:model="model"
					:rules="rules"
					ref="formRef"
					borderBottom
					errorType="toast"
					labelWidth="auto"
				>
					<u-form-item
						v-for="item in formList"
						:key="item.key"
						:required="item.required"
						:label="item.label"
						:prop="item.key"
					>
						<u--input
							v-if="item.type === 'string'"
							v-model="model[item.key]"
							border="none"
							inputAlign="right"
							:placeholder="item.placeholder"
							:readonly="current > 1"
							maxlength="200"
						/>
						<!-- model[item.key] ? item.type === 'date' ? $u.timeFormat(model[item.key], 'yyyy-mm-dd') : model[item.key] : item.placeholder -->
						<view
							v-else
							@click="item.show = true"
							class="w-full text-right u-line-1 pl-2"
							:class="item.val ? '' : 'text-#C0C4CC'"
							>{{ item.val || item.placeholder }}
						</view>
					</u-form-item>
				</u--form>
				<view
					v-if="[4, 5].includes(curType)"
					class="mt-32rpx mb-10rpx text-28rpx"
				>
					<view
						>{{ curType === 5 ? '挂号' : '取报告' }}凭证<text
							class="u-form-item__body__left__content__required text-#f56c6c ml-4rpx"
							>*</text
						>
					</view>
					<view class="mb-10rpx text-24rpx text-#999"
						>请勿上传与医保卡相关图片</view
					>
					<upload-img
						v-model="fileList"
						:disabled="false"
						:maxCount="10"
						multiple
					></upload-img>
				</view>
				<view class="mt-22rpx mb-20rpx text-28rpx">备注</view>
				<u--textarea
					v-model="model.remark"
					placeholder=""
					maxlength="300"
					count
					:autoHeight="false"
				/>
				<view class="text-28rpx mt-20rpx mb-8rpx">注意事项</view>
				<view class="text-24rpx text-#999">
					1. 服务项目为必填项
					<br />
					2. 服务时间为必填项
					<br />
					3. 服务地点为必填项
					<br />
				</view>
				<agreed-comp v-model:agreed="agreed" :disabled="false" />
			</view>

			<u-picker
				:show="show"
				:columns="columns"
				keyName="serveName"
				valueName="id"
				@confirm="onPickerConfirm"
				@cancel="show = false"
				@close="handleShowPicker"
				:defaultIndex="[curType - 1]"
				cancelText="取消"
				confirmColor="#FF8CA6"
				closeOnClickOverlay
			></u-picker>
			<block v-for="item in dateAndSelectFormList" :key="item.key">
				<!-- :minHour="item.type === 'time' ? new Date().getHours() : 0"
					:minMinute="item.type === 'time' ? new Date().getMinutes() : 0" -->
				<u-datetime-picker
					v-if="item.type === 'date' || item.type === 'time'"
					:modelValue="model[item.key]"
					:show="item.show"
					:mode="item.type"
					:minDate="item.type === 'date' ? new Date().getTime() : 0"
					:filter="item.type === 'time' ? filterFun : null"
					@confirm="onDatePickerConfirm($event, item)"
					@cancel="item.show = false"
					@close="item.show = false"
					confirmColor="#FF8CA6"
					closeOnClickOverlay
				/>
				<u-picker
					v-if="item.type === 'select'"
					:show="item.show"
					:columns="item.options || columns"
					keyName="label"
					@confirm="onSelectPickerConfirm($event, item)"
					@cancel="item.show = false"
					@close="item.show = false"
					cancelText="取消"
					confirmColor="#FF8CA6"
					closeOnClickOverlay
				></u-picker>
				<u-popup
					v-if="item.type === 'checkbox'"
					class="overflow-hidden"
					:show="item.show"
					round="16rpx"
					@close="item.show = false"
					closeable
				>
					<view class="h-700rpx pt-90rpx relative">
						<view
							class="text-#000 absolute left-50% translate-x-[-50%] top-30rpx"
							>护理项目</view
						>
						<view
							class="h-full w-full overflow-y-auto py-4 px-30rpx rounded-16rpx overflow-hidden"
						>
							<popup-checkbox @change="onCheckboxChange($event, item)" />
						</view>
					</view>
				</u-popup>
			</block>
		</view>
		<button-contact />
		<view
			class="bg-#fff h-150rpx w-full sticky bottom-0 z-2 flex justify-between items-center pr-24rpx pl-40rpx pb-48rpx rounded-sm"
		>
			<block v-if="true">
				<view>
					<text class="text-32rpx">￥</text>
					<text class="font-bold text-54rpx">{{ selTypeItem.price || 0 }}</text>
				</view>
				<view
					@click="$u.throttle(orderPay, 1000)"
					class="text-white mr-4 bg-#FF8CA6 rounded-24rpx w-240rpx h-80rpx text-center leading-80rpx hover:shadow-md"
					>支付</view
				>
				<view
					@click="$u.throttle(onSubmit, 1000)"
					class="text-white bg-#FF8CA6 rounded-24rpx w-240rpx h-80rpx text-center leading-80rpx hover:shadow-md"
					>立即下单</view
				>
			</block>
			<view
				v-if="false"
				class="text-white bg-#FF8CA6 rounded-24rpx w-full mx-30rpx h-80rpx text-center leading-80rpx hover:shadow-md"
				>{{ true ? '开始服务' : '订单已完成，提交工作记录' }}</view
			>
		</view>
	</view>
</template>

<script setup>
import { useRoute } from '@/utils/uni-router'

const route = useRoute()
const instance = getCurrentInstance()
const { $u, $api, $Router, $dialog, $toast, $store, $loading } = instance.proxy
// 填写订单 在线支付 服务中 服务完成
const list = ref([
	{ label: '填写订单', id: 1 },
	{ label: '在线支付', id: 2 },
	{ label: '服务中', id: 3 },
	{ label: '服务完成', id: 4 }
])
const current = ref(1)
const show = ref(false)
const fileList = ref([])
// 半天陪诊 全天陪诊 代办约号 取送报告 代取送药 上门护理
const columns = reactive([
	[
		{ label: '半天陪诊', id: 1 },
		{ label: '全天陪诊', id: 2 },
		{ label: '代办约号', id: 3 },
		{ label: '取送报告', id: 4 },
		{ label: '代取送药', id: 5 },
		{ label: '上门护理', id: 6 }
	]
])
// 就诊医院 请输入, 预约就诊日期 请选择就诊日期,预约就诊时间 请选择就诊时间,就诊人,请填写就诊人,联系人 请填写就诊联系人,联系人手机号 请填写就诊联系人 ,挂号科室
const formItems = [
	{
		label: '收货地址',
		placeholder: '请输入收货地址',
		key: 'deliveryAddress',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请填写收货地址',
		show: true,
		cur: [4, 5],
		sort: 1
	},
	{
		label: '就诊医院',
		placeholder: '请选择就诊医院',
		key: 'hospitalId',
		required: true,
		type: 'select',
		trigger: ['blur', 'change'],
		message: '请选择就诊医院',
		show: false,
		cur: [1, 2, 3, 4, 5],
		sort: 2
	},
	{
		label: '上门护理',
		placeholder: '请选择上门护理类型',
		key: 'typeId',
		required: true,
		type: 'select',
		trigger: ['blur', 'change'],
		message: '请选择上门护理类型',
		show: false,
		options: [],
		cur: [6],
		sort: 1
	},
	{
		label: '服务时间',
		placeholder: '请选择服务时间',
		key: 'serviceTime',
		required: true,
		type: 'date',
		trigger: ['blur', 'change'],
		message: '请选择服务时间',
		show: false,
		sort: 3,
		cur: [4, 5]
	},
	{
		label: '报告类型',
		placeholder: '请选择报告类型',
		key: 'reportType',
		required: true,
		type: 'select',
		trigger: ['blur', 'change'],
		message: '请选择报告类型',
		show: false,
		sort: 3,
		cur: [4]
	},
	{
		label: '预约就诊日期',
		placeholder: '请选择就诊日期',
		key: 'clinicDate',
		required: true,
		type: 'date',
		trigger: ['blur', 'change'],
		message: '请选择预约就诊日期',
		show: false,
		sort: 3,
		cur: [1, 2]
	},
	{
		label: '预约就诊时间',
		placeholder: '请选择就诊时间',
		key: 'clinicTime',
		required: true,
		type: 'time',
		message: '请选择预约就诊时间',
		trigger: ['blur', 'change'],
		show: false,
		sort: 4,
		cur: [1, 2]
	},
	{
		label: '上门日期',
		placeholder: '请选择上门日期',
		key: 'visitDate',
		required: true,
		type: 'date',
		trigger: ['blur', 'change'],
		message: '请选择上门日期',
		show: false,
		sort: 3,
		cur: [6]
	},
	{
		label: '上门时间',
		placeholder: '请选择上门时间',
		key: 'visitTime',
		required: true,
		type: 'time',
		message: '请选择上门时间',
		trigger: ['blur', 'change'],
		show: false,
		sort: 4,
		cur: [6]
	},
	{
		label: '就诊人',
		placeholder: '请填写就诊人',
		key: 'clinicPerson',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请填写就诊人',
		show: true,
		sort: 5,
		cur: [1, 2, 5]
	},
	{
		label: '联系人',
		placeholder: '请填写联系人',
		key: 'contact',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请填写联系人',
		show: true,
		sort: 6,
		cur: [1, 2, 6]
	},
	{
		label: '联系人手机号',
		placeholder: '请填写联系人手机号',
		key: 'contactPhone',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请填写联系人手机号',
		show: true,
		sort: 7,
		cur: [1, 2, 4, 5, 6]
	},
	{
		label: '挂号科室',
		placeholder: '请选择挂号科室',
		key: 'registrationDept',
		required: true,
		type: 'string',
		trigger: ['blur', 'change'],
		message: '请选择挂号科室',
		show: true,
		sort: 8,
		cur: [1, 2]
	}
	// {
	// 	label: '备注',
	// 	placeholder: '请输入',
	// 	key: 'remark',
	// 	type: 'textarea',
	// 	required: false,
	// 	show: true
	// }
]
const formRef = ref(null)
const dateAndSelectFormList = ref()
const formList = ref()
const model = ref({})
const curType = ref(route.query.cur ? +route.query.cur : columns[0][0].id)
const typeVal = ref('')
const selTypeItem = ref({})
const rules = ref({})
const agreed = ref(false)
const hospitalList = ref([])
const serverTypelList = ref([])
const reportTypelList = ref([])
const dateKeyObj = {}
const orderId = ref(route.query.id ? +route.query.id : '')
const orderInfo = ref({})

const getPzList = async () => {
	const res = await $api.fetchPzServerList()
	columns[0] = res?.page?.list || []
}

const getPzHospitalList = async () => {
	const res = await $api.fetchPzHospitalList()
	hospitalList.value = (res?.list || []).map((item) => ({
		label: item.name,
		id: item.id + ''
	}))
}
const getServerTypeList = async () => {
	const res = await $api.fetchServerTypeList()
	serverTypelList.value = (res?.data || []).map((item) => ({
		label: item.name,
		id: item.id + ''
	}))
}
const getReportTypelList = async () => {
	const res = await $api.fetchReportTypelList()
	reportTypelList.value = (res?.data || []).map((item) => ({
		label: item.name,
		id: item.id + ''
	}))
}
const getOrderInfo = async () => {
	// if (!orderId.value) return
	$loading(true)
	const res = await $api.orderInfo({ id: orderId.value || 12 })
	if (res.success) {
		const { order = {} } = res
		orderInfo.value = order
		curType.value = order.serverId
	}
	$loading(false)
}

getPzList()
getPzHospitalList()
getServerTypeList()
getReportTypelList()
getOrderInfo()

const orderPay = async () => {
	const res = await $api.orderPay({
		orderId: orderId.value || model.value.contactPhone
	})
	if (res?.success) {
		const { timeStamp, nonce_str, prepay_id, signType = 'MD5', sign } = res
		uni.requestPayment({
			provider: 'wxpay', // 支付宝支付：alipay，微信支付：wxpay
			timeStamp,
			nonceStr: nonce_str,
			package: prepay_id,
			signType,
			paySign: sign,
			success: function (res) {
				// 在这里处理支付成功的回调
				console.log(res)
				$toast('支付成功!')
			},
			fail: function (err) {
				// 处理支付失败的回调
				console.error(err.errMsg)
			}
		})
	}
}

const onSubmit = () => {
	formRef.value.validate().then(async () => {
		if ([4, 5].includes(curType.value)) {
			if (fileList.value.length)
				model.value.pictureUrl = JSON.stringify(fileList.value)
			else {
				$toast(`请上传${curType.value === 5 ? '挂号' : '取报告'}凭证!`)
				return
			}
		}
		const { date, time } = dateKeyObj
		if (time && date) {
			const selDate = `${model.value[date]}T${model.value[time]}:00`
			if (new Date(selDate) < new Date()) {
				$toast('选择时间不能小于当前时间！', {
					type: 'error',
					duration: 2 * 1000
				})
				return
			}
		}
		if (!agreed.value) {
			try {
				await $dialog('是否已阅读并同意《服务条款》?', {
					showCancelButton: true,
					confirmButtonText: '同意',
					cancelButtonText: '取消',
					confirmColor: '#FF8CA6'
				})
				agreed.value = true
			} catch (error) {
				return
			}
		}
		// $loading(true)
		model.value.serverId = curType.value
		const { success, order } = await $api.orderCreate(model.value)
		if (success) {
			orderId.value = order.id
			orderInfo.value = order
			orderPay()
			$toast('提交订单成功!')
		}
	})
}

watch(curType, () => {
	const item = columns[0].find((item) => item.id === curType.value)
	typeVal.value = item?.serveName
	selTypeItem.value = item || {}
	dateAndSelectFormList.value = []
	formList.value = []
	formItems.forEach((item) => {
		const { required, key, message, trigger, type } = item
		if (item.cur.includes(curType.value)) {
			if (key === 'hospitalId') item.options = [hospitalList.value]
			if (key === 'typeId') item.options = [serverTypelList.value]
			if (key === 'reportType') item.options = [reportTypelList.value]
			formList.value.push(item)
			if (type !== 'string') {
				dateAndSelectFormList.value.push(item)
			}
			rules.value[item.key] = { required, message, trigger }
			if (orderInfo.value.srReport) {
				item.val = model.value[key] = orderInfo.value.srReport[key]
			} else {
				model.value[key] = ''
				if (type === 'time') model.value[key] = `${new Date().getHours()}:00`
				if (type === 'date' || type === 'time') dateKeyObj[type] = key
			}
		}
	})
	if (typeof orderInfo.value.srReport?.pictureUrl === 'string') {
		fileList.value = JSON.parse(orderInfo.value.srReport.pictureUrl)
	}
	console.log('🚀 ~ file: index.vue:572 ~ model.value:', model.value)
})

const handleShowPicker = () => {
	if (current.value > 1) {
		return
	}
	show.value = !show.value
}
const onPickerConfirm = ({ value: [val] }) => {
	show.value = false
	typeVal.value = val.serveName
	curType.value = val.id
}
// 列表选择器
const onSelectPickerConfirm = ({ value: [val] } = { value: [] }, item) => {
	item.show = false
	model.value[item.key] = val?.id
	item.val = val?.label
}
const onDatePickerConfirm = ({ value }, item) => {
	item.show = false
	if (item.type === 'date')
		item.val = model.value[item.key] = $u.timeFormat(value, 'yyyy-mm-dd')
	else item.val = model.value[item.key] = value
}
// 护理项目点击
const onCheckboxChange = (val, item) => {
	model.value[item.key] = val
	item.val = val
}

const filterFun = (type, value) => {
	if (type === 'minute') return value.filter((item) => item % 15 === 0)
	return value
}
</script>

<style lang="scss" scoped>
:deep {
	.u-form-item__body {
		border-bottom: 2rpx solid #f2f2f2;
		padding: 32rpx 0 !important;
	}
	.u-form-item__body__left__content__required {
		// margin-left: 6rpx;
		font-size: 24rpx !important;
		top: 0rpx !important;
		right: -6rpx !important;
		left: auto !important;
	}
	.u-popup__content {
		border-radius: 16rpx 16rpx 0 0;
	}
	.u-textarea,
	.u-textarea__count {
		background-color: #f2f2f2 !important;
	}
	.u-popup__content {
		overflow: hidden;
	}
}
</style>
