<template>
	<z-paging-swiper>
		<template #top>
			<view v-if="roleName === 'common'" class="px-24rpx pt-20rpx relative">
				<u--image
					width="100%"
					height="200rpx"
					:fade="false"
					:src="$assets('/order-bg.png')"
				/>
				<view
					class="text-white flex items-center justify-between px-130rpx pt-20rpx absolute top-0 left-0 w-full h-full"
				>
					<view class="flex flex-col items-center">
						<view class="text-64rpx">{{ orderTodayIncome.count || 0 }}</view>
						<view class="text-34rpx">今日接单</view>
					</view>
					<view class="flex flex-col items-center">
						<view class="text-64rpx">{{
							orderTodayIncome.doctorPrice || 0
						}}</view>
						<view class="text-34rpx">今日收入</view>
					</view>
				</view>
			</view>
			<u-tabs
				@change="handleTabChange"
				class="w-full"
				:list="list"
				lineWidth="30"
				lineColor="#FF8CA6"
				:scrollable="false"
				:current="current"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="width: 20%; height: 100rpx;"
			></u-tabs>
		</template>
		<swiper
			class="h-full"
			:current="current"
			@animationfinish="swiperAnimationfinish"
		>
			<swiper-item v-for="(_, index) in list" :key="index">
				<view class="h-full">
					<z-paging
						:ref="(el) => (paging[index] = el)"
						v-if="dataList[index].show"
						v-model="dataList[index].data"
						@query="queryList"
						:min-delay="300"
					>
						<view
							v-for="(item, i) of dataList[index].data"
							:key="i"
							class="min-h-410rpx bg-white rounded-16rpx mx-30rpx px-20rpx py-30rpx mb-20rpx shadow-current"
						>
							<view class="flex-row-between">
								<text class="text-#999 text-24rpx"
									>订单号：{{ item.outTradeNo }}</text
								>
								<view
									v-if="item.orderStatus !== null || item.status !== null"
									class="w-124rpx h-48rpx leading-48rpx text-center rounded-sm text-24rpx"
									:class="`${stateColorList[item.orderStatus].bg} ${
										stateColorList[item.orderStatus].color
									}`"
									>{{ stateColorList[item.orderStatus].text }}</view
								>
							</view>
							<view
								class="flex-row-between items-center text-28rpx text-#999 mt-20rpx"
							>
								<view
									>服务项目：<text class="text-#000">{{
										item.projectName
									}}</text></view
								>
								<view
									v-if="roleName === 'common'"
									class="text-#FF3939 font-bold"
									>预计收入：￥{{ item.doctorPrice || '' }}</view
								>
							</view>
							<view
								class="mt-10rpx mb-24rpx flex text-24rpx bg-#f2f2f2 w-full min-h-140rpx rounded-sm px-34rpx pt-20rpx pb-10rpx"
							>
								<view
									v-if="item.result?.contact || item.result?.clinicPerson"
									class="flex flex-col text-#666 mr-40rpx"
								>
									<block v-if="item.result?.clinicPerson">
										<text>就诊人</text>
										<text class="text-#000 mt-8rpx">{{
											item.result.clinicPerson
										}}</text>
									</block>
									<block v-else-if="item.result?.contact">
										<text>联系人</text>
										<text class="text-#000 mt-8rpx">{{
											item.result.contact
										}}</text>
									</block>
								</view>
								<view class="flex flex-col flex-1 pr-20rpx text-#666">
									<text v-if="item.result?.hospitalName">医院</text>
									<text class="text-#000 mt-8rpx">{{
										item.result?.hospitalName
									}}</text>
								</view>
								<view class="flex flex-col text-#666">
									<text>预约时间：</text>
									<text class="text-#000 mt-8rpx">{{
										item.result?.clinicDate ||
										item.result?.visitDate ||
										item.result?.serviceTime
									}}</text>
									<text class="text-#000">{{
										item.result?.clinicTime || item.result?.visitTime
									}}</text>
								</view>
							</view>
							<view class="flex justify-end items-center">
								<view
									v-if="
										item.orderStatus === 4 &&
										item.refundStatus !== 0 &&
										roleName !== 'common'
									"
									@click="handleClick(item, 'refund')"
									class="btn text-30rpx px-30rpx py-14rpx ml-30rpx border-#5F5F5F text-#5F5F5F"
									>申请退款</view
								>
								<view
									v-if="roleName === 'common' && item.orderStatus < 3"
									@click="
										$u.throttle(
											() =>
												handleClick(
													item,
													item.receiveStatus !== 0 ? 'start' : 'end'
												),
											800
										)
									"
									class="btn text-30rpx px-30rpx py-14rpx ml-30rpx border-#40A0E4 text-#40A0E4"
									>{{ item.receiveStatus !== 0 ? '开始' : '完成' }}服务</view
								>
								<view
									v-if="roleName === 'common' && item.orderStatus === 3"
									@click="$u.throttle(() => handleClick(item, 'end'), 800)"
									class="btn text-30rpx px-30rpx py-14rpx ml-30rpx border-#40A0E4 text-#40A0E4"
									>工作记录</view
								>
								<view
									v-if="roleName !== 'common' && item.orderStatus === 3"
									@click="$u.throttle(() => handleClick(item, 'end'), 800)"
									class="btn text-30rpx px-30rpx py-14rpx ml-30rpx border-#40A0E4 text-#40A0E4"
									>{{ item.isEvaluate !== 0 ? '去评价' : '查看记录' }}</view
								>
								<view
									@click="$u.throttle(() => handleClick(item, 'detail'), 800)"
									class="btn text-30rpx px-30rpx py-14rpx ml-30rpx border-#FF8CA6 text-#FF8CA6"
									>查看详情</view
								>
								<view
									v-if="!item.reasonId && item.orderStatus < 3"
									@click="handleClick(item, 'cancel')"
									class="btn text-30rpx px-30rpx py-14rpx ml-30rpx border-#5F5F5F text-#5F5F5F"
									>取消订单</view
								>
							</view>
						</view>
					</z-paging>
				</view>
			</swiper-item>
		</swiper>
		<u-popup
			class="overflow-hidden"
			:show="popupShow"
			round="16rpx"
			@close="popupShow = false"
			closeable
		>
			<view class="pt-90rpx relative">
				<view class="text-#000 absolute left-50rpx top-30rpx"
					>请选择取消理由</view
				>
				<view
					class="h-full w-full overflow-y-auto py-10rpx px-40rpx rounded-16rpx overflow-hidden"
				>
					<u-radio-group v-model="cancelVal" placement="row">
						<u-radio
							labelSize="16"
							iconSize="20"
							v-for="(item, index) in reasonList"
							:key="index"
							activeColor="#FF8CA6"
							:label="item.reason"
							:name="item.id"
						></u-radio>
					</u-radio-group>
					<view class="mt-20rpx mb-20rpx text-28rpx">其他理由，请填写</view>
					<u--textarea
						v-model="remark"
						placeholder=""
						maxlength="300"
						count
						:autoHeight="false"
					/>
					<view
						@click="handleCancelSubmit"
						class="text-white bg-#FF8CA6 rounded-24rpx w-full mx-auto mt-30rpx h-80rpx text-center leading-80rpx hover:shadow-md"
						>提交</view
					>
				</view>
			</view>
		</u-popup>
		<button-contact :class="`!bottom-16%`" />
		<template #bottom><tabbar :fixed="false" /></template>
	</z-paging-swiper>
</template>

<script setup>
import { onShow } from '@dcloudio/uni-app'

const instance = getCurrentInstance()
const { $api, $store, $Router, $toast, $dialog } = instance.proxy
const roleName = computed(() => $store.user.userInfo.roleName)
// 全部 待服务 进行中 已完成 已取消
const list = ref([
	{ name: '全部', id: 0 },
	{ name: '待服务', id: 1 },
	{ name: '进行中', id: 2 },
	{ name: '已完成', id: 3 },
	{ name: '已取消', id: 4 }
])
const paging = ref([])
const dataList = ref([
	{ data: [], show: true },
	{ data: [], show: false },
	{ data: [], show: false },
	{ data: [], show: false },
	{ data: [], show: false }
])
const popupShow = ref(false)
const cancelVal = ref()
const remark = ref('')
const status = ref(0)
const current = ref(0)
const outTradeNo = ref('')
const reasonList = ref([])
const stateColorList = [
	{
		text: '待支付',
		color: 'text-#fff',
		bg: 'bg-primary-500'
	},
	{
		text: '待服务',
		color: 'text-#01BB88',
		bg: 'bg-#d4f0e7'
	},
	{
		text: '进行中',
		color: 'text-#FEA60A',
		bg: 'bg-#fceed1'
	},
	{
		text: '已完成',
		color: 'text-#40A0E4',
		bg: 'bg-#dceaf8'
	},
	{
		text: '已取消',
		color: 'text-#666',
		bg: 'bg-#ccc'
	}
]
const orderTodayIncome = ref({})

const getReasonList = () => {
	$api.reasonList().then(({ page = {} }) => {
		reasonList.value = page.list || []
	})
}
getReasonList()

onShow(() => {
	if (!roleName.value) {
		$dialog('请先登录', {
			showCancelButton: true,
			confirmButtonText: '去登录',
			cancelButtonText: '取消',
			confirmColor: '#FF8CA6'
		})
			.then(() => {
				// $Router.push('/personal')
				$store.user.login().then((user) => {
					// $store.user.setUserInfo(user)
					!user.nickName
						? $Router.push({
								path: '/pages/other/edit-userinfo'
						  })
						: userStore.setUserInfo(user) &&
						  dataList.value[current.value].show &&
						  paging.value[current.value]?.reload()
				})
			})
			.catch(() => '')
		return
	} else paging.value[current.value]?.reload()
	if (roleName.value === 'common') {
		$api.orderTodayIncome({ isToday: 0 }).then(({ data = {} }) => {
			orderTodayIncome.value = data
		})
	}
})

const handleTabChange = (item) => {
	current.value = item.id
	status.value = item.id - 1 < 0 ? 0 : item.id - 1
	dataList.value[item.id].show = true
}
//swiper滑动结束
const swiperAnimationfinish = (e) => {
	const cur = e.detail.current
	current.value = cur
	dataList.value[cur].show = true
}

watch(current, (cur) => {
	dataList.value[cur].show && paging.value[cur]?.reload()
})

const queryList = (pageNo, pageSize) => {
	if (!roleName.value) return
	const params = {
		pageNum: pageNo,
		pageSize: pageSize,
		status: current.value,
		roleName: roleName.value
	}
	$api
		.orderList(params)
		.then(({ data }) => {
			paging.value[current.value]?.complete(data?.records || [])
			dataList.value[current.value].data = data?.records || []
			dataList.value[current.value].show = true
		})
		.catch(() => {
			paging.value[current.value]?.complete(false)
		})
}

const handleClick = async (item, type) => {
	if (type === 'start') {
		$dialog('确认开始服务吗？', {
			showCancelButton: true,
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			confirmColor: '#FF8CA6'
		})
			.then(async () => {
				const res = await $api.startOrder({
					id: item.id
				})
				if (res.success) {
					paging.value?.[current.value]?.reload()
					$toast('开始服务成功!', { duration: 1000 })
				}
			})
			.catch(() => '')
	} else if (type === 'end') {
		$Router.push({
			path: '/complete',
			query: {
				id: item.id,
				isEvaluate: item.isEvaluate
			}
		})
	} else if (type === 'detail') {
		$Router.push({
			path: '/pages/form/index',
			query: {
				id: item.id
			}
		})
	} else if (type === 'cancel') {
		outTradeNo.value = item.outTradeNo
		popupShow.value = true
	} else if (type === 'refund') {
		$dialog('确定要申请退款吗？', {
			showCancelButton: true,
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			confirmColor: '#FF8CA6'
		})
			.then(() => {
				$api
					.orderRefund({
						outTradeNo: item.outTradeNo
					})
					.then((res) => {
						if (res.success)
							$toast('申请成功,请耐心等待到账！', {
								icon: 'success',
								duration: 2000
							})
					})
			})
			.catch(() => '')
	}
}

const handleCancelSubmit = async () => {
	if (!cancelVal.value) return $toast('请选择取消理由')
	if (cancelVal.value === 5 && !remark.value?.trim()) {
		return $toast('请填写取消理由')
	}
	const res = await $api.cancelOrder({
		outTradeNo: outTradeNo.value,
		reasonId: cancelVal.value,
		remark: remark.value,
		roleName: roleName.value
	})
	if (res.success) {
		$toast('取消成功')
		popupShow.value = false
		paging.value[current.value]?.reload()
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #f2f2f2;
}
.flex-row-center {
	@apply flex flex-row justify-center items-center;
}
.flex-row-between {
	@apply flex flex-row justify-between items-center;
}
.btn {
	@apply rounded-md border-solid border-1;
}
:deep {
	.u-popup__content {
		border-radius: 16rpx 16rpx 0 0;
	}
	.u-textarea,
	.u-textarea__count {
		background-color: #f2f2f2 !important;
	}
	.u-popup__content {
		overflow: hidden;
	}
	.u-radio {
		padding-bottom: 20rpx !important;
		width: 100% !important;
		.u-radio__text {
			width: 100%;
		}
	}
}
</style>
