<template>
    <div>
        <div class="swipe-area">
            <van-swipe :autoplay="3000">
                <van-swipe-item>
                   <img src="../../static/post1.png" alt="">
                </van-swipe-item>
								<van-swipe-item>
									<img src="../../static/post2.png" alt="">
								</van-swipe-item>
								<van-swipe-item>
									<img src="../../static/post3.png" alt="">
								</van-swipe-item>
            </van-swipe>
        </div>
        <h2 class="tit">体检服务</h2>
		<div class="services">
			<div  class="services-item" @click="judgePreOrdered()">
				<img :src="preOrderImg" alt=""/>
				<span>体检预约</span>
			</div>
			<div v-if="userStatus !== 0" class="services-item" @click="judgeCareerPre()">
				<img :src="careerExamImg" alt=""/>
				<span>职业体检</span>
			</div>
			<div class="services-item" @click="jumpReport()">
				<img :src="reportImg" alt=""/>
				<span>体检报告</span>
			</div>
			<div class="services-item" @click="jumpMyPre()">
				<img :src="myPreImg" alt=""/>
				<span>我的预约</span>
			</div>
		</div>
        <TabBar/>
    </div>
</template>

<script setup lang="ts" name="Home">
    
    import TabBar from '../../components/TabBar.vue';
    import { onMounted, ref } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
		import { getUserStatus, isPreOrdered, getUserInfo } from '../../api/Home'
		// 引入图片
		import preOrderImg from '../../static/preOrder.png'
		import careerExamImg from '../../static/careerExam.png'
		import reportImg from '../../static/report.png'
		import myPreImg from '../../static/myPreOrder.png'
		import { showToast } from 'vant';

		const route = useRoute()
		const router = useRouter()
    const userStatus = ref<number>(0)
    const personnelType = ref<string>('0')
		const appoint1 = ref<number>(3)
		const appoint2 = ref<number>(2)
		const originCancel = ref<any>()
		const cancelTime = ref<any>()
		const cancelWeekStart = ref<any>()
		const cancelWeekEnd = ref<any>()
		const userInfo = ref<any>({})

		// 获取取消日期所处一周的时间范围
		// type：日期类型，start：开始时间，end：结束时间
    // dates：日期方向，默认0：本周，-1：上周，1：下周，2：下下周，以此类推
		// cancelDay：传入的日期
		const getCancelWeek = (type: string, dates = 0, cancelDay: string | number | Date) => {
        let now = new Date(cancelDay);
        let nowTime = now.getTime();
        let day = now.getDay();
				if (day == 0) {
					nowTime = nowTime - 7 * 24 * 60 * 60 * 1000
				}
        let longTime = 24 * 60 * 60 * 1000;
        let n = longTime * 7 * (dates || 0);
        let dd
        if (type == "start") {
            dd = nowTime - (day - 1) * longTime + n;
        };
        if (type == "end") {
					if (day == 0) {
						dd = nowTime + (7 - day) * longTime + n + longTime;
					} else {
						dd = nowTime + (7 - day) * longTime + n;
					}
				};
        let trueDD = new Date(dd);
        let y = trueDD.getFullYear();
        let m = trueDD.getMonth() + 1;
        let d = trueDD.getDate();
        let trueM = m < 10 ? "0" + m : m;
        let trueD = d < 10 ? "0" + d : d;
        let trueDay = y + "-" + trueM + "-" + trueD;
        return trueDay;
    };

		// 初始化时获取用户状态
		const fetchUserStatus = () => {
			getUserStatus({
					token: localStorage.getItem('token'),
					telephone: localStorage.getItem('phoneNumber')
			}).then((res: any) => {
				console.log(res)
				originCancel.value = res.data.obj.cancelTime
        userStatus.value = Number(res.data.obj.status)
        personnelType.value = res.data.obj.personnelType
				cancelTime.value = Date.parse(res.data.obj.cancelTime)
				cancelWeekStart.value = Date.parse(getCancelWeek('start', 0, cancelTime.value))
				cancelWeekEnd.value = Date.parse(getCancelWeek('end', 0, cancelTime.value))
			}).catch((err: any) => {
				console.log(err)
			})
		}

		// 判断体检预约是否已经预约和已经取消
		const judgePreOrdered = () => {
			isPreOrdered({
				token: localStorage.getItem('token'),
				appoint: appoint2.value
			}).then((res: any) => {
				console.log(res, '收到')
				if (res.data.obj === 1) {
					router.push({
						path: '/examPreOrder',
						query: {
							cancelDate: cancelTime.value + 7 * 24 * 60 * 60 * 1000
						}
					})
				} else {
					showToast({
						message: '您已经预约过，无法再次预约！',
						icon: 'fail',
						duration: 2000
					})
				}
			}).catch((err: any) => {
				console.log(err, '错误')
			})
		}

		// 判断职业体检预约是否已经预约和已经取消
		const judgeCareerPre = () => {
			isPreOrdered({
				token: localStorage.getItem('token'),
				appoint: appoint1.value
			}).then((res: any) => {
				console.log(res, '收到')
				if (res.data.obj === 1) {
					router.push({
						path: '/careerExam'
					})
				} else {
					showToast({
						message: '您已经预约过，无法再次预约！',
						icon: 'fail',
						duration: 2000
					})
				}
			}).catch((err: any) => {
				console.log(err, '错误')
			})
		}

		// 体检报告
    const jumpReport = () => {
        router.push({
            path: '/examReport'
        })
    }

		// 我的预约
    const jumpMyPre = () => {
        router.push({
            path: '/myPreOrder'
        })
    }

    onMounted(() => {
				if (route.query.pwd === 'YNsbd@123456') {
					showToast({
						message: '首次登录，请您重置密码！',
						icon: 'fail',
						duration: 3000,
						onClose: () => {
							router.replace({
								path: '/forgetPassword',
								query: {
									phoneNum: localStorage.getItem('phoneNumber')
								}
							})
						}
					})
				}
				// 如果取不到cookie，清除登录状态
				if (!document.cookie) {
					showToast({
						message: '登录状态已过期，请重新登录！',
						icon: 'fail',
						duration: 1500,
						onClose: () => {
							localStorage.removeItem('token')
							localStorage.removeItem('phoneNumber')
							localStorage.removeItem('phyName')
							localStorage.removeItem('idcard')
							localStorage.removeItem('sex')
							localStorage.removeItem('age')
							localStorage.removeItem('telepNumber')
							localStorage.removeItem('departName')
							localStorage.removeItem('id')
							history.go(0)
						}
					})
				} else {
					fetchUserStatus()
					// fetchIfSpecial()
				}
    })

	onMounted(() => {
        getUserInfo({
            token: localStorage.getItem('token')
        }).then((res: any) => {
            userInfo.value = res.data.obj[0]
            const data = res.data.obj[0]
            localStorage.setItem('idcard', data.idcard)
        }).catch((err: any) => {
            console.log(err)
        })
    })

</script>

<style scoped lang="scss">
    .background {
      width: 10rem;
		  height: 8rem;
		  background: url('../../static/bg.jpg');
		  background-size: 100% 100%;
		  width: 100%;
		  position: absolute;
		  left: 0;
		  top: 0;
		  .section_1 {
			  background-color: rgba(255, 255, 255, 0.1);
			  border-radius: 50%;
			  width: 4rem;
			  height: 4rem;
			  position: absolute;
			}
		
		.section_2 {
			  background-color: rgba(255, 255, 255, 0.1);
			  border-radius: 50%;
			  position: absolute;
			  left: 0.1rem;
			  top: 1.2rem;
			  width: 6rem;
			  height: 6rem;
			}
		
		.section_3 {
			  background-color: rgba(255, 255, 255, 0.0624);
			  border-radius: 50%;
			  position: absolute;
			  left: 6rem;
			  top: 0.5rem;
			  width: 4rem;
			  height: 4rem;
			}
		}
        .swipe-area{
            width: 95%;
						height: 70%;
            margin: 0 auto;
						padding-top: 0.8rem;
						img{
							width: 100%;
							height: 100%;
						}
        }
        .tit{
            margin: 0.6rem 0 0 0;
						padding-left: 0.2rem;
						font-size: 20px;
						font-weight: bold;
        }
        .services{
            width: 95%;
            margin: 0.3rem auto;
            height: 7rem;
            border-radius: 0.2rem;
						display: flex;
						flex-wrap: wrap;
						box-sizing: border-box;
						padding: 1rem 0 0 1.2rem;
						background-color: #fff;
            .services-item{
                width: 20%;
								height: 30%;
								display: flex;
								flex-direction: column;
								flex-wrap: nowrap;
								margin-right: 1rem;
								margin-bottom: 0.1rem;
								image{
									width: 100%;
									height: 100%;
									margin-bottom: 0.2rem;
								}
								span{
									text-align: center;
									font-size: 16px;
									padding-top: 0.3rem;
								}
						}
        }
</style>