<template>
    <van-nav-bar
        title="体检预约"
        left-arrow
        @click-left="onClickLeft"
    />
    <van-form @submit="subForm" @failed="subFormFail" class="form-area">
        <div class="upper-info">
            <h2 style="font-size: 18px; font-weight: bold; margin-bottom: 0.3rem;">选择医院</h2>
            <van-field
                v-model="result1"
                is-link
                readonly
                name="hospitalId"
                placeholder="点击选择医院"
                @click="showHospitalPicker = true"
                style="margin-bottom: 0.3rem"
                autocomplete="off"
                :rules="[
                    {
                        required: true,
                        message: '请选择一个医院！'
                    }
                ]"
            />
            <van-popup 
                v-model:show="showHospitalPicker"
                position="bottom"
            >
                <van-picker
                    :columns="hospitalColumns"
                    @confirm="onHospitalConfirm"
                    @cancel="showHospitalPicker = false"
                />
            </van-popup>
            <h2 style="font-size: 18px; font-weight: bold; margin-bottom: 0.3rem;">选择套餐</h2>
            <van-field
                v-model="result2"
                is-link
                readonly
                name="checkId"
                placeholder="点击选择套餐"
                @click="showTypePicker = true"
                style="margin-bottom: 0.3rem"
                autocomplete="off"
                :rules="[
                    {
                        required: true,
                        message: '请选择一个套餐！'
                    }
                ]"
            />
            <van-popup 
                v-model:show="showTypePicker" 
                position="bottom"
            >
            <van-cascader
                v-model="result3"
                title="请选择套餐"
                :options="typeColumns"
                @close="cascaderClose"
                @change="onChange"
            />
            <!-- <div class="inner-package" v-if="showTotalTc">
                <h2 class="inner-tit">
                    {{ personalPackageName }}
                    <span style="display: flex; align-items: center;" v-if="pushBtn" @click="flodTc"> 展开 <van-icon name="arrow-down" size="26"/></span> 
                    <span style="display: flex; align-items: center;" v-if="!pushBtn" @click="blowTc"> 收起 <van-icon name="arrow-up" size="26"/></span>
                </h2>
                <div style="height: 300px; overflow: auto;" v-if="showTc">
                    <div class="package-area" v-for="(item, index) in sonPackageDetails" :key="index">
                        <div class="package-name">{{ item.combinName }}</div>
                        <div class="package-content">项目内容：{{ item.combinContent }}</div>
                        <div class="package-price">项目价格：<span>{{ item.combinPrice }}元</span></div>
                    </div>
                    <div class="total-price">
                        <span style="padding-right: 0.3rem;">合计</span>
                        <span style="color: red;">{{ totalPrice }}元</span> 
                    </div>
                </div>
                <div class="cfm-btn">
                    <van-button class="confirm-package" type="primary" @click="closePopup">确认套餐</van-button>
                </div>
            </div> -->
            
            </van-popup>
            <h2 style="font-size: 18px; font-weight: bold; margin-bottom: 0.3rem;">体检时间</h2>
            <h2 style="font-size: 14px; margin-bottom: 0.3rem; color: #9c9898">注意：一个自然周内，仅限预约一次</h2>
            <vue-hash-calendar
                @change="calendarChange"
                format="YY-MM-DD"
                :min-date="minDate"
                ref="calendar"
                picker-type="date"
                :disabled-date="disabledDate"
                :disabled-week-view="true"
            />
        </div>
        <div class="left-pre-order" v-if="leftPre">当天剩余可预约人数：<span id="people-left"></span>人</div>
        <div class="hospital-info-area" v-for="(item, index) in selectedHospital" :key="index">
            <h2 style="font-size: 18px; font-weight: bold; margin-bottom: 0.4rem;">医院信息</h2>
            <div class="info">
                <h4 style="margin-bottom: 0.4rem; color: #2c97ef; font-size: 20px; font-weight: bold;">{{ item.text }}</h4>
                <h5>地址：{{ item.address }}</h5>
                <h5>营业时间：{{ item.businessStart }} -- {{ item.businessEnd }}</h5>
                <h5>负责人：{{ item.responsible }}</h5>
                <h5>联系方式：{{ item.telPhone }}</h5>
            </div>
        </div>
        <div class="btn">
            <van-button 
                type="primary" 
                native-type="submit" 
                :disabled="disBtn"
                style="width: 50%; border-radius: 0.1rem; font-size: 18px; font-weight: bold;">确定预约
            </van-button>
        </div>
    </van-form>
    
</template>

<script setup lang="ts">

    import { onMounted, ref, reactive } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { showToast } from 'vant'
    import Crypoto from '../../api/AesCbc'
    import { 
        getActualHospital, 
        getPackageDetail, 
        submitForm, 
        getDaysFull,
        getPeopleLeft,
        getPhysicalExamination
    } from '../../api/ExamPreOrder';

    // 初始值定义
    const cry: any = new Crypoto()
    const router = useRouter()
    const route = useRoute()
    const result1 = ref<any>('')
    const result2 = ref<any>('')
    const result3 = ref<any>('')
    const showHospitalPicker = ref<boolean>(false)
    const showTypePicker = ref<boolean>(false)
    const personalPackageName = ref<any>('')
    const sonPackageDetails = ref<any[]>([])
    const basePackageDetails = ref<any[]>([])
    const totalPrice = ref<number>(0)
    const packageId = ref<any>('')
    const hospitalName = ref<any>('')
    const examType = ref<any>('')
    // 使用reactive定义响应式对象
    const selectedHospital = reactive<any>({})
    // 设置日历日期选择的范围，默认选择当天---当天+30天
    const minDate = ref<any>(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()))
    const selectedDate = ref<any>('')
    const calendar = ref(null)
    const showTotalTc = ref<boolean>(false)
    const showTc = ref<boolean>(false)
    const pushBtn = ref<boolean>(true)
    const disBtn = ref<boolean>(false)
    const realToday = ref<any>('')
    const cancelWeekList = ref<any[]>([])
    const daysFullArr = ref<any[]>([])
    const leftPre = ref<boolean>(false)

    const flodTc = () => {
        showTc.value = true
        pushBtn.value = false
    }

    const blowTc = () => {
        showTc.value = false
        pushBtn.value = true
    }

    // 返回上一页
    const onClickLeft = () => {
        history.back()
    }

    // 获取今天
    const getJT = (date: any) => {
        const year = date.getFullYear();
        const month = (date.getMonth()+1);
        const day = date.getDate();
        const currDate = ref<any>(``)
        // 判断日期
        if (day < 10 && month < 10) { 
            currDate.value = `${year}-0${month}-0${day}`;
        } else if (month >= 10 && day < 10) {
            currDate.value = `${year}-${month}-0${day}`;
        } else if (day >= 10 && month < 10) {
            currDate.value = `${year}-0${month}-${day}`;
        } else {
            currDate.value = `${year}-${month}-${day}`;
        }

        return currDate.value

    }

    // 获取下周第一天
    // type：日期类型，start：开始时间，end：结束时间
    // dates：日期方向，默认0：本周，-1：上周，1：下周，2：下下周，以此类推
    const getNextWeekFirst = (type: any, dates = 0) => {
        let now = new Date();
        let nowTime = now.getTime();
        let day = now.getDay();
        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") {
            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 subForm = (res: any) => {
        console.log(selectedDate.value)
        disBtn.value = true
        // 将获取的日历日期等数据添加到表单提交对象中
        res.hospitalId = hospitalName.value
        res.setMealId = packageId.value
        res.checkId = examType.value
        res.phyAppontTime = String(selectedDate.value)
        res.setMealType = 2
        res.combName = personalPackageName.value
        let params = res
        console.log('提交表单', res)
        if (selectedDate.value == realToday.value) {
            showToast({
                message: '不可以预约今天！',
                icon: 'fail',
                duration: 1500,
                onClose: () => {
                    disBtn.value = false
                }
            })
        } else {
            submitForm({
                // hospitalId: res.hospitalId,
                // setMealId: res.setMealId,
                // checkId: res.checkId,
                // phyAppontTime: res.phyAppontTime,
                // setMealType: res.setMealType,
                // combName: res.combName,
                encryptedData:cry.encrypt(JSON.stringify(params)),
                token: localStorage.getItem('token')
            }).then((res: any) => {
                console.log(res)
                if (res.data.res == 0) {
                    showToast({
                        message: '今日可预约人数已满，请重新选择日期预约！',
                        icon: 'fail',
                        duration: 2500,
                        onClose: () => {
                            disBtn.value = false
                        }
                    })
                } else {
                    showToast({
                        message: '预约成功！',
                        icon: 'success',
                        duration: 1500,
                        onClose: () => {
                            router.replace({
                                path: '/preOrderSucceed',
                                query: {
                                    id: packageId.value
                                }
                            })
                        }
                    })
                }
            }).catch(() => {
                showToast({
                    message: '预约超时，请返回重新预约！',
                    icon: 'fail',
                    duration: 2000,
                    onClose: () => {
                        history.go(-1)
                    }
                })
            })
        }
    }

    // 表单提交失败
    const subFormFail = (err: any) => {
        console.log(err)
    }

    // 级联框关闭
    const cascaderClose = () => {
        showTypePicker.value = false
        result2.value = ''
    }

    // 定义下拉框的选项
    const hospitalColumns = ref<any[]>([])
    // const typeColumns = ref<any[]>([
    //     { text: '心血管', value: 1 },
    //     { text: '肿瘤', value: 2 },
    //     { text: '综合', value: 3 }
    // ])
    const typeColumns = ref<any[]>([])

    // 获取真实医院接口
    const fetchActualHospital = () => {
        getActualHospital({
            token: localStorage.getItem('token'),
            idcard: localStorage.getItem('idcard')
        }).then((res: any) => {
            console.log(res);
            
            if (res.data.obj[0] == 'null' || res.data.obj[0] == null) {
                showToast({
                    message: '请联系后台管理员添加医院！',
                    icon: 'fail',
                    duration: 1500
                })
            } else {
                // 设置选择医院单选框的内容
                const newHospitalObj = res.data.obj.map((item: any) => {
                    return {
                        text: item['hospitalName'],
                        value: item['id'],
                        address: item['address'],
                        businessStart: item['businessStart'],
                        businessEnd: item['businessEnd'],
                        responsible: item['responsible'],
                        telPhone: item['telPhone']
                    }
                })
                hospitalColumns.value = newHospitalObj
            }
        }).catch((err: any) => {
            console.log(err)
        })
    }

    // 获取体检套餐接口
    const physicalExamination = () => {
        getPhysicalExamination({
            token: localStorage.getItem('token'),
            idcard: localStorage.getItem('idcard')
        }).then((res: any) => {
            if (res.data.obj === 'isnull') {
                showToast({
                    message: '请联系后台管理员添加人员体检套餐！',
                    icon: 'fail',
                    duration: 1500
                })
            } else {
                // 设置选择医院单选框的内容
                const newHospitalObj = res.data.obj.map((item: any) => {
                    return {
                        text: item['text'],
                        value: item['id'],
                    }
                })
                typeColumns.value = newHospitalObj
            }
        }).catch((err: any) => {
            console.log(err)
        })
    }

    // 点击关闭弹出框popup，并监听选择医院的变化
    const onHospitalConfirm = (res: any) => {
        daysFullArr.value = []
        selectedHospital.value = {}
        result1.value = res.selectedOptions[0]?.text;
        showHospitalPicker.value = false;
        selectedHospital.value = res.selectedOptions[0]
        console.log('选择医院', res.selectedOptions[0].value)
        hospitalName.value = res.selectedOptions[0]?.value
        // 获取哪些天数预约人数已满
        getDaysFull({
            today: getJT(new Date()),
            hosId: res.selectedValues[0],
            token: localStorage.getItem('token')
        }).then((result: any) => {
            for (let i = 0; i < result.data.obj.length; i++) {
                daysFullArr.value.push(result.data.obj[i].notAppointTime)
            }
        }).catch((err: any) => {
            console.log(err)
        })
    };

    // 日历选择日期改变触发
    const calendarChange = (res: any) => {
        console.log(res);
        // hospitalName.value = ''
        selectedDate.value = res;
        if (hospitalName.value != '') {
            leftPre.value = true
            getPeopleLeft({
                hosId: hospitalName.value,
                phyAppontTime: res,
                type: '2',
                token: localStorage.getItem('token')
            }).then((result: any) => {
                let elem = document.querySelector('#people-left') as HTMLElement
                elem.innerHTML = result.data.obj
            }).catch((err: any) => {
                console.log(err);
            });
        }
    };

    // 级联选择器变化
    const onChange = (res: any) => {
        console.log("孙亮",res)
        result2.value = res.selectedOptions[0]?.text;
        examType.value = res.selectedOptions[0]?.value;
		
		
		personalPackageName.value =res.selectedOptions[0]?.text;
		packageId.value = res.selectedOptions[0]?.value;
        /* getPackageDetail({
            checkId: JSON.stringify(res.selectedOptions[0].value),
            token: localStorage.getItem('token'),
            combType: 2
        }).then((result: any) => {
            console.log(result)
            if (result.data.obj.tibean.length === 0) {
                showToast({
                    message: '体检套餐为空，请联系后台管理员发布体检套餐！',
                    icon: 'fail',
                    duration: 2000
                })
                result2.value = ''
            } else {
                showTotalTc.value = true
                personalPackageName.value = result.data.obj.tibean[0].combName
                packageId.value = result.data.obj.tibean[0].id
                sonPackageDetails.value = result.data.obj.tibeanson
                basePackageDetails.value = result.data.obj.basebean
                console.log(packageId.value)
                totalPrice.value = 0
                // 计算总价回显至弹出层
                for (let i = 0; i < sonPackageDetails.value.length; i++) {
                    totalPrice.value += Number(sonPackageDetails.value[i].combinPrice)
                }
                for (let j = 0; j < basePackageDetails.value.length; j++) {
                    totalPrice.value += Number(basePackageDetails.value[j].combinPrice)
                }
            }
        }).catch((err: any) => {
            console.log(err)
        }) */
    }

    // 级联选择器点击关闭按钮
    const closePopup = () =>{
        if (result2.value === '') {
            showToast({
                message: '未选择职工套餐！',
                icon: 'fail',
                duration: 1500
            })
        } else {
            showTypePicker.value = false
        }
    }

    // 获取某天所处的一周
    const fetchDayWeek = (chosenDay: any) => {
        let oneDayTime = 1000 * 60 * 60 * 24 
        let today = new Date(chosenDay)
        // 若那一天是周末时，则强制赋值为7
        let todayDay = today.getDay() || 7 
        let startDate = new Date(
            today.getTime() - oneDayTime * (todayDay - 1)
        )
        let dateList = new Array()
        // 获取当天所处的一周
        for(let i = 0; i < 7; i++){
            let temp = new Date(startDate.getTime() + i * oneDayTime)
            let year = temp.getFullYear()
            let month = temp.getMonth() + 1
            let day = temp.getDate()
				if (day < 10 && month < 10) {
					dateList[i] = `${year}-0${month}-0${day}`
				} else if (month >= 10 && day < 10) {
					dateList[i] = `${year}-${month}-0${day}`
				} else if (day >= 10 && month < 10) {
					dateList[i] = `${year}-0${month}-${day}`
				} else {
					dateList[i] = `${year}-${month}-${day}`
				}
        }
        return dateList
    }

    // 设置日历禁用日期
    const disabledDate = (date: any) => {
        const year = date.getFullYear();
        // 月份需要+1
        const month = (date.getMonth()+1);
        const day = date.getDate();
        const currDate = ref<any>(``)
        // 判断日期
        if (day < 10 && month < 10) { 
            currDate.value = `${year}-0${month}-0${day}`;
        } else if (month >= 10 && day < 10) {
            currDate.value = `${year}-${month}-0${day}`;
        } else if (day >= 10 && month < 10) {
            currDate.value = `${year}-0${month}-${day}`;
        } else {
            currDate.value = `${year}-${month}-${day}`;
        }

        // 生成禁用日期
        const disabledDateArr = [];

        // 获取当天所处的一周
            let oneDayTime = 1000 * 60 * 60 * 24 
            let today = new Date() // selectedDate.value
            // 若那一天是周末时，则强制赋值为7
            let todayDay = today.getDay() || 7 
            let startDate = new Date(
                today.getTime() - oneDayTime * (todayDay - 1)
            )
            let dateList = new Array()

            // 获取当天所处的一周
            for(let i = 0; i < 7; i++){
                let temp = new Date(startDate.getTime() + i * oneDayTime)
                let year = temp.getFullYear()
                let month = temp.getMonth() + 1
                let day = temp.getDate()
					if (day < 10 && month < 10) {
						dateList[i] = `${year}-0${month}-0${day}`
					} else if (month >= 10 && day < 10) {
						dateList[i] = `${year}-${month}-0${day}`
					} else if (day >= 10 && month < 10) {
						dateList[i] = `${year}-0${month}-${day}`
					} else {
						dateList[i] = `${year}-${month}-${day}`
					}
                    // disabledDateArr.push(dateList[i])
            }

            // 预约人数已满的天数不可预约
            for (let i = 0; i < daysFullArr.value.length; i ++) {
                disabledDateArr.push(daysFullArr.value[i])
            }

        if (disabledDateArr.includes(currDate.value)) {
            return true;
        }
        return false;
    }

    onMounted(() => {
        fetchActualHospital()
        physicalExamination()
        realToday.value = getJT(new Date())
        console.log(route.query)
        cancelWeekList.value = fetchDayWeek(Number(route.query.cancelDate))
    })

</script>

<style scoped lang="scss">
    .form-area{
        width: 100%;
        margin: 0.2rem auto;
        .upper-info{
            width: 96%;
            margin: 0 auto;
            background-color: #f8f8f8;
            box-sizing: border-box;
            padding: 0.3rem;
            border-radius: 0.1rem;
            position: relative;
            .inner-package{
                width: 100%;
                box-sizing: border-box;
                padding: 0.2rem;
                height: 10.5rem;
                .inner-tit{
                    font-size: 20px; 
                    font-weight: bold; 
                    color: #2c97ef;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    box-sizing: border-box;
                    padding: 0.2rem 0;
                    border-bottom: 1px solid #d3d3d3;
                }
                h1{
                    font-size: 20px;
                    color: #2c97ef;
                    margin-bottom: 0.4rem;
                    font-weight: bold;
                }
                h2{
                    margin-bottom: 0.4rem;
                    line-height: 26px;
                }
                .cfm-btn{
                    width: 100%;
                    position: fixed;
                    left: 10px;
                    bottom: 10px;
                    margin-top: 0.5rem;
                }
            }
        }
        .personal-area{
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }
    .left-pre-order{
        width: 90%;
        margin: 0.15rem auto;
        background-color: #fff;
        border-radius: 0.1rem;
        box-sizing: border-box;
        padding: 0.3rem;
        font-size: 16px;
        color: #9c9898;
    }
    .hospital-info-area{
        width: 94%;
        margin: 0.5rem auto;
        background-color: #fff;
        border-radius: 0.1rem;
        box-sizing: border-box;
        padding: 0.3rem;
        .info{
            width: 100%;
			height: 80%;
			display: flex;
			flex-direction: column;
			margin: 0.1rem auto;
            h5{
                font-size: 16px;
                margin-bottom: 0.2rem;
                line-height: 20px;
            }
            h5:nth-child(5){
                margin-bottom: 0;
            }
        }
    }
    .btn{
        width: 100%;
        margin: 0.5rem auto;
        display: flex;
        justify-content: center;
    }
    .package-area{
        .package-name{
            font-size: 20px;
            margin-bottom: 0.15rem;
            font-weight: bold;
            color: #2c97ef;
        }
        .package-price, .package-content{
            font-size: 16px;
            line-height: 26px;
        }
        .package-price{
            margin-bottom: 0.5rem;
        }
        .package-price{
            span{
                color: red;
            }
        }
    }
    .total-price{
        display: flex;
        justify-content: right;
        margin-top: 1rem;
        font-size: 18px;
    }
</style>