<template>
	<view class="container my-patient-container">
		<!-- 自定义导航栏 -->
		<CustomNavbar
			title="我的患者"
			type="center"
			:isLeft="true"
			@handleLeft="handleLeft"
			bgColor="#fff"
		/>
		<!-- 顶部搜索和日期选择 -->
		<view class="hearder">
			<!-- 搜索框 -->
			<uv-input
				placeholder="请输入患者姓名"
				prefixIcon="search"
				v-model="paramsData.patientName"
				@confirm="getData"
				customStyle="background: #f5f6f9; height:60rpx; border:unset; border-radius: 200rpx 200rpx 200rpx 200rpx;"
				prefixIconStyle="font-size: 22px; color: #B9B9B9"
			>
				<template v-slot:suffix>
					<text class="search" 	@click="search">搜索</text>
				</template>
			</uv-input>

			<!-- 日期选择框 -->
			<view class="time-box">
				<view @click="openDatePicker('start')">
					<text v-if="!paramsData.startDate">开始日期</text>
					<text v-else>{{ paramsData.startDate }}</text>
					<text :class="isOpenStartPicker ? 'up-picker' : 'down-picker'"></text>
				</view>
				<view @click="openDatePicker('end')">
					<text v-if="!paramsData.endDate">结束日期</text>
					<text v-else>{{ paramsData.endDate }}</text>
					<text :class="isOpenEndPicker ? 'up-picker' : 'down-picker'"></text>
				</view>
			</view>
		</view>
		<!-- 内容区域 -->
		<view class="all-number">患者人数合计：{{ pageTotal }}</view>
		<view class="content pd-12">
			<view class="list">
				<view
					class="item"
					v-for="(item, index) in dateList"
					:key="index"
					
				>
					<view class="top">
						<view>
							<image
								src="@/static/images/default_avatar.png"
								mode="scaleToFill"
							/>
							<text>{{item.userName}}</text>
						</view>
						<view>账号：{{item.id}}</view>
					</view>
					<view class="center">
						<view>
							<CustomIcon iconName="qrcode" color="#848D99" size="32rpx" />
							<text class="left-text">公益码</text>
							<text class="right-text">21111111</text>
						</view>
					</view>
					<view class="bottom">
						<view>
							<CustomIcon
								iconName="mobile"
								color="#848D99"
								size="32rpx"
							/>
							<text class="left-text">手机</text>
							<text class="right-text">{{item.userName}}</text>
						</view>
						<view>
							<CustomIcon
								iconName="schedule"
								color="#848D99"
								size="32rpx"
							/>
							<text class="left-text">时间</text>
							<text class="right-text">{{item.allocateTime.split(" ")[0]}}</text>
						</view>
					</view>
				</view>
				<CustomLoadMore :status="loadStatus" />
			</view>
		</view>
		<!-- 日期选择器 -->
		<uv-datetime-picker
			ref="datetimePicker"
			v-model="dateValue"
			mode="date"
			@confirm="dateTimePickerConfirm"
			@close="closePicker"
			@cancel="closePicker"
			cancelColor="#11C3AE"
			confirmColor="#11C3AE"
		/>
	</view>
</template>

<script lang="ts" setup>
import { ref, inject, onMounted } from "vue";
import baseApi from "@/api/base";
import { onDateChange } from "@/utils/common";
import { onReachBottom } from "@dcloudio/uni-app";

const $showToast: any = inject("$showToast");

const dateValue = ref(new Date().toDateString());
const datetimePicker = ref<any>(null);
const dateList = ref<any>([]); // 患者列表
const loadStatus = ref("loading");
const paramsData = ref({
	startDate: "",
	pageSize: 10,
	pageNum: 1,
	endDate: "",
	patientName: ""
});
const pageTotal = ref(0);
const dateType = ref("start");
const isOpenStartPicker = ref(false);
const isOpenEndPicker = ref(false);

/**
 * 打开日期选择器
 * @param type - 日期类型（开始日期或结束日期）
 */
const openDatePicker = (type: "start" | "end") => {
	datetimePicker.value.open(); // 打开日期选择器
	dateType.value = type; // 设置当前选择的日期类型
	isOpenStartPicker.value = type === 'start';
	isOpenEndPicker.value = type === 'end';
};

/**
 * 选择器确认回调
 * @param e - 选择器返回的数据
 */
const dateTimePickerConfirm = (e: any) => {
  const formattedDate = onDateChange(e.value); // 格式化选择的日期

  if (dateType.value === 'start') {
    paramsData.value.startDate = formattedDate.split(" ")[0]; // 设置开始日期
    // 如果结束日期存在且早于开始日期，则重置开始日期并提示用户
    if (paramsData.value.endDate && new Date(paramsData.value.endDate) < new Date(formattedDate)) {
      paramsData.value.startDate = "";
      return $showToast("开始日期不能晚于结束日期");
    }
  } else {
    paramsData.value.endDate = formattedDate.split(" ")[0]; // 设置结束日期
    // 如果开始日期存在且结束日期早于开始日期，则重置结束日期并提示用户
    if (paramsData.value.startDate && new Date(formattedDate) < new Date(paramsData.value.startDate)) {
      paramsData.value.endDate = "";
      return $showToast("结束日期不能早于开始日期");
    }
  }

  // 关闭选择器
  isOpenStartPicker.value = false;
  isOpenEndPicker.value = false;

  // 获取数据
  getData();
};
const search = () => {
	dateList.value = []
	getData()
}
/**
 * 选择器关闭回调
 */
const closePicker = () => {
	isOpenStartPicker.value = false;
	isOpenEndPicker.value = false;
	dateValue.value = new Date().toDateString();
};

/**
 * 返回上一页
 */
const handleLeft = () => {
	uni.navigateBack({ delta: 1 });
};

/**
 * 跳转到指定页面
 * @param url - 目标页面的 URL
 */
const toPage = (url: string) => {
	uni.navigateTo({ url });
};

/**
 * 获取患者数据
 */
const getData = async () => {
	loadStatus.value = 'loading'
	const { data: { records,total } } = await baseApi.queryPatientList(paramsData.value);
	dateList.value.push(...records);
	pageTotal.value = total; // 更新患者总数
	if(dateList.value.length < total) {
		loadStatus.value = "loadmore"
	}else {
		loadStatus.value = "nomore"
	}
};
onReachBottom(() => {
		loadStatus.value = 'loading'
	if(dateList.value.length < pageTotal.value) {
		++ paramsData.value.pageNum 
		getData()
	}else {
		loadStatus.value = "nomore"
	}
})

onMounted(() => {
	getData(); // 组件挂载后获取数据
});
</script>

<style lang="scss">
@import "./index.scss";
page {
	background-color: #f5f7fa;
}
</style>
