<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; " class="personal-area">
                职工套餐
            </h2>
            <van-field
                v-model="result2"
                readonly
                :label="personalPackageName"
                label-width="3rem"
                placeholder="请选择职工套餐"
                @click="showCrewPicker = true"
                style="margin-bottom: 0.3rem;"
                :rules="[
                    {
                        required: true,
                        message: '请选择一个套餐！'
                    }
                ]"  
            />
            <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 } from 'vue-router'
    import { showToast } from 'vant'
    import Crypoto from '../../api/AesCbc'
    import { 
        submitForm,
        getCrewPackage,
        getCareerDaysFull ,
        getPeopleLeft,
        getCareerHospitalInfo
    } from '../../api/CareerExam'

    // 初始值定义
    const cry: any = new Crypoto()
    const router = useRouter()
    const result1 = ref<any>('')
    const result2 = ref<any>('')
    const showHospitalPicker = ref<boolean>(false)
    const showCrewPicker = ref<boolean>(false)
    // 使用reactive定义响应式对象
    const selectedHospital = reactive<any>({})
    const hospitalName = ref<any>('')
    const examType = ref<any>('')
    const packageId = ref<any>('')
    const personalPackageName = ref<any>('')

    // 设置日历日期选择的范围，默认选择当天---当天+30天
    const minDate = ref<any>(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()))
    // const maxDate = ref<any>(new Date(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).getFullYear(), new Date(Date.now() + 30 * 24* 60 * 60 * 1000).getMonth(), new Date(Date.now() + 30 * 24* 60 * 60 * 1000).getDate()))

    const selectedDate = ref<any>('')

    const disBtn = ref<boolean>(false)
    const realToday = ref<any>('')
    const careerDaysFullArr = ref<any[]>([])
    const leftPre = ref<boolean>(false)
    const peopleLeft = ref<any>('')

    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：下周
    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 cascaderClose = () => {
        showCrewPicker.value = false
        result2.value = ''
    } */

    // 提交表单并跳转
    const subForm = (res: any) => {
        disBtn.value = true
        res.hospitalId = hospitalName.value
        res.setMealId = packageId.value
        res.checkId = examType.value
        res.phyAppontTime = String(selectedDate.value)
        res.setMealType = 3
        res.combName = result2.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: cry.encrypt(JSON.stringify(res.hospitalId)),
                // setMealId: res.setMealId,
                // 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'
                            })
                        }
                    })
                }
            }).catch(() => {
                showToast({
                    message: '预约超时，请返回重新预约！',
                    icon: 'fail',
                    duration: 2000,
                    onClose: () => {
                        history.go(-1)
                    }
                })
            })
        }
        
    }
    // 提交失败
    const subFormFail = (err: any) => {
        console.log(err)
    }

    // 定义两个下拉框的选项
    const hospitalColumns = ref<any[]>([])

    // 获取医院信息
    const fetchHospitalInfo = () => {
        getCareerHospitalInfo({
            token: localStorage.getItem('token')
        }).then((res: any) => {
            if (res.data.obj === 'isnull') {
                showToast({
                    message: '请联系管理员添加医院！',
                    icon: 'fail',
                    duration: 1500
                })
            } else {
                let filteredArr = []
                for (let i = 0; i < res.data.obj.length; i++) {
                    if (res.data.obj[i].hospitalName.includes('铁路医院')) {
                        filteredArr.push(res.data.obj[i])
                    }
                }
                const newHospitalInfo = filteredArr.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 = newHospitalInfo
            }
        })
    }

    // 获取职工套餐信息
        const fetchCrewPackage = () => {
            getCrewPackage({
                token: localStorage.getItem('token')
            }).then((res: any) => {
                const data = res.data.obj
                console.log(data)
                result2.value = data.combName
                packageId.value = data.id
                /* const newArr = Object.keys(data)
                const crewPackageNameArr = ref<any[]>([])
                const crewPackageIdArr = ref<any[]>([])
                const crewPackageContentArr = ref<any>('')
                const crewPackageCombinNameArr = ref<any>('')
                const crewPackagePriceArr = ref<any[]>([])
                const innerPrice = ref<number>(0)
                const totalData = ref<any[]>([])
                const nameTotal = ref<any[]>([])
                const contentTotal = ref<any[]>([])
                for (let i = 0; i < newArr.length; i++) {
                    innerPrice.value = 0
                    crewPackageContentArr.value = ''
                    crewPackageCombinNameArr.value = ''
                    for (let j = 0; j < data[i].length; j++) {
                        innerPrice.value += Number(data[i][j].combinPrice)
                        crewPackageContentArr.value += (data[i][j].combinContent + ' , ')
                        crewPackageCombinNameArr.value += (data[i][j].combinName + ' , ')
                    }
                    crewPackageNameArr.value.push(data[i][i].combName)
                    crewPackageIdArr.value.push(data[i][i].combId)
                    crewPackagePriceArr.value.push(innerPrice.value)
                    // 去除末尾逗号
                    nameTotal.value.push(crewPackageCombinNameArr.value.slice(0, -2))
                    contentTotal.value.push(crewPackageContentArr.value.slice(0, -2))
                }
                crewPackageNameArr.value.forEach((one: any, index: any) => {
                    const item = ref<any>({})
                    item.text = one
                    item.value = crewPackageIdArr.value[index]
                    item.combinContent = contentTotal.value[index]
                    item.combinName = nameTotal.value[index]
                    item.combinPrice = crewPackagePriceArr.value[index]
                    totalData.value.push(item)
                    const settleInfo = totalData.value.map((item: any) => {
                        return {
                            text: item['text'],
                            value: item['value'],
                            combinContent: item['combinContent'],
                            combinName: item['combinName'],
                            combinPrice: item['combinPrice']
                        }
                    })
                    crewColumns.value = settleInfo
                }) */
            }).catch((err: any) => {
                console.log(err)
            })
        }

    // 关闭级联框
    /* const closePopup = () => {
        if (result2.value === '') {
            showToast({
                message: '未选择职工套餐！',
                icon: 'fail',
                duration: 1500,
                onClose: () => {
                    result2.value = ''
                }
            })
        } else {
            showCrewPicker.value = false
        }
    } */

    // 点击关闭两个弹出框popup，并监听选择医院的变化
    const onHospitalConfirm = (res: any) => {
      careerDaysFullArr.value = []
      selectedHospital.value = {}
      result1.value = res.selectedOptions[0]?.text;
      showHospitalPicker.value = false;
      selectedHospital.value = res.selectedOptions[0]
      hospitalName.value = res.selectedOptions[0]?.value
      // 获取职业体检哪些天预约人数已满
      getCareerDaysFull({
        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++) {
            careerDaysFullArr.value.push(result.data.obj[i].notAppointTime)
        }
      }).catch((err: any) => {
        console.log(err)
      })
    };

    // 日历选择日期改变触发
    const calendarChange = (res: any) => {
        selectedDate.value = res
        if (hospitalName.value != '') {
            leftPre.value = true
            getPeopleLeft({
                hosId: hospitalName.value,
                phyAppontTime: res,
                type: '3',
                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 disabledDate = (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}`;
        }

        // 生成禁用日期
        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 < careerDaysFullArr.value.length; i++) {
                disabledDateArr.push(careerDaysFullArr.value[i])
            }

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

    onMounted(() => {
        fetchHospitalInfo()
        fetchCrewPackage()
        realToday.value = getJT(new Date())
        console.log(getNextWeekFirst('start', 1))
    })

</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;
            .inner-content{
                width: 100%;
                margin-top: 0.3rem;
                box-sizing: border-box;
                padding: 0.3rem;
                position: relative;
                .btn-upper{
                    margin-bottom: 1.4rem;
                    font-size: 18px;
                    display: flex;
                    flex-direction: column;
                    .content-tit{
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                    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;
                    }
                }
            }
        }
    }
    .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{
        display: flex;
        justify-content: space-between;
        .package-name, .package-price{
            font-size: 16px;
            line-height: 26px;
        }
    }
    .total-price{
        display: flex;
        justify-content: right;
        margin-top: 1.5rem;
        font-size: 18px;
    }
</style>