<!-- 手术预约 -->
<template>
    <div class="wrapper">
        <!-- 头部背景 -->
        <div class="banner"></div>

        <!-- 就诊人 -->
        <div class="order-wrapper" style="margin-top:-1rem;">
            <van-cell title="就诊人" :icon="icon.iconOfPatient" is-link to="/familyMember?pageType=1">
                <template slot="default">
                    <span style="margin-right:.1rem;">{{familyMemberInfo.FamilyMemberName}}</span>
                    <van-tag
                        round
                        type="primary"
                        v-if="familyMemberInfo.UserRelationship"
                    >{{familyMemberInfo.UserRelationship|filterRelation}}</van-tag>
                </template>
            </van-cell>
            <van-cell
                title="病历说明"
                :icon="icon.iconCaseHistory"
                :value="caseHistoryInfo.DiagnosisResult||'选择病历'"
                is-link
                @click="chooseCase"
            />
        </div>
        <!-- 手术信息 -->
        <div class="order-wrapper">
            <van-cell title="手术城市" :value="chooseCityInfo.AreaName" is-link to="/chooseCity" />
            <van-cell
                title="医生科室"
                :value="departmentObj.text"
                is-link
                @click="departmentShow=true"
            />
            <van-cell
                title="医生职称"
                :value="currentJobTitleIndex|filterDoctorTitles"
                is-link
                @click="jobTitleShow=true"
            />
            <van-cell title="手术日期" :value="currentStr" is-link @click="dateShow=true" />
        </div>
        <!-- 手机号 -->
        <div class="order-wrapper">
            <van-cell-group>
                <van-field v-model.trim="phone" :left-icon="icon.iconPhone" placeholder="请输入手机号" />
                <van-field
                    v-model.trim="verificationCode"
                    :left-icon="icon.iconSms"
                    center
                    clearable
                    placeholder="请输入短信验证码"
                >
                    <van-button
                        slot="button"
                        size="small"
                        round
                        type="info"
                        :loading="SendSMSLoading"
                        loading-text="加载中"
                        :disabled="SendSMSDisabled"
                        @click="SendSMS"
                    >{{SMSTips}}</van-button>
                </van-field>
                <!-- <van-field value="输入框已禁用" label="验证码" left-icon="contact" /> -->
            </van-cell-group>
            <van-cell value="*填写通知手机，以方便客服人员联系您了解情况并通知您手术相关信息。" class="tipsMessage" />
        </div>
        <div class="order-wrapper">
            <van-cell title="订金" value="500.00元" value-class="red" />
            <van-cell value="*如若预约手术手术成功，订金可抵扣手术费用；如果预约失败，则订金会沿原路退还给您。" class="tipsMessage" />
        </div>

        <div class="tips">注：自提交手术预约申请后七个工作日内，会有客服联系您与您确认手术相关情况，请耐心等待。</div>

        <div class="button" @click="AddOrder">提交</div>

        <!-- 选择科室 -->
        <van-popup v-model="departmentShow" get-container="body" position="bottom">
            <ChooseDepartment @cancel="departmentShow=false" @confirm="confirmDepartment"></ChooseDepartment>
        </van-popup>

        <!-- 选择职称 -->
        <van-action-sheet
            v-model="jobTitleShow"
            :actions="actions"
            @cancel="jobTitleShow=false"
            @select="onSelect"
            close-on-click-action
            title="医生职称"
        />

        <!-- 日期选择 -->
        <van-popup v-model="dateShow" position="bottom" round>
            <van-datetime-picker
                v-model="currentTime"
                type="date"
                :max-date="MaxDate"
                :min-date="MinDate"
                :formatter="formatterDate"
                @confirm="confirmDate"
                @cancel="dateShow=false"
            />
        </van-popup>
    </div>
</template>
<script>
    // 小图标
    import {
        iconPhone,
        iconSms,
        iconOfPatient,
        iconCaseHistory
    } from "@/assets/js/icon.js";
    import ChooseDepartment from "@/components/ChooseDepartment.vue"; //选择科室
    import { setInterval } from "timers";

    export default {
        name: "surgery",
        data() {
            return {
                SendSMSLoading: false, // 发送验证码加载状态
                SendSMSDisabled: false, // 发送验证码是否禁用
                SMSTips: "发送验证码", // 发送短信验证码提示文字
                icon: {
                    iconOfPatient,
                    iconCaseHistory,
                    iconPhone,
                    iconSms
                },
                // 科室组件参数
                departmentShow: false, // 科室组件显示
                // 科室组件提示文本
                departmentObj: {
                    id: -1,
                    text: "选择科室"
                },

                //职称组件参数on
                jobTitleShow: false, //职称组件显示
                actions: [
                    { name: "主任医生", index: 1, className: "" },
                    { name: "副主任医生", index: 2, className: "" },
                    { name: "主治医生", index: 3, className: "" },
                    { name: "医师", index: 4, className: "" }
                ],
                currentJobTitleIndex: 0, // 当前职称
                //职称组件参数end

                /** 选择日期参数on */
                dateShow: false, //日期显示
                currentTime: new Date(), // 当前时间
                currentStr: "选择日期", // 当前时间提示
                MinDate: new Date(Date.now() + 1000 * 60 * 60 * 24), // 最小值加1天,
                MaxDate: (_ => {
                    // 当前时间到往后的一个月
                    return new Date(+new Date() + 1000 * 60 * 60 * 24 * 30);
                })(),
                /** 选择日期参数end */

                // 预约人信息
                familyMemberInfo: {
                    ID: "", // 预约人ID
                    FamilyMemberName: "就诊人"
                },
                // 病历信息
                caseHistoryInfo: {
                    //ID:''  病人ID
                    FamilyMemberID: "", // 病人ID
                    DiagnosisResult: "选择病历",
                    ID: ""
                },
                // 选择的城市信息
                chooseCityInfo: {
                    AreaCode: "", // 地址编码
                    AreaName: "选择城市", //地址名字
                    CooperationStatus: 0 //地址状态 1未开通，2已开通，3即将开通 ,
                },
                phone: "", //手机号码
                verificationCode: "", // 短信验证码
                timeId: null, // 计时器id
                time: 0 // 计时器倒计时
            };
        },
        methods: {
            init() {
                // 设置预约人信息
                let data = JSON.parse(
                    sessionStorage.getItem("FamilyMemberData")
                ) || {
                    FamilyMemberName: "就诊人"
                };
                this.familyMemberInfo = data;

                // 设置病历信息 FamilyMemberID
                let info =
                    JSON.parse(sessionStorage.getItem("caseHistoryInfo")) || {};
                if (info.FamilyMemberID === this.familyMemberInfo.ID) {
                    this.caseHistoryInfo = info;
                }

                // 获取城市地址
                let chooseCity = JSON.parse(
                    sessionStorage.getItem("chooseCity")
                ) || {
                    AreaCode: "", // 地址编码
                    AreaName: "选择城市" //地址名字
                };
                this.chooseCityInfo = chooseCity;
            },
            // 选择科室
            confirmDepartment(data) {
                this.departmentShow = false;
                if (data.id == -1) data.text = "选择科室";
                this.departmentObj = data;
                console.log(data);
            },
            // 选择病历
            chooseCase() {
                if (this.familyMemberInfo.ID) {
                    this.$router.push({
                        name: "memberFile",
                        query: { id: this.familyMemberInfo.ID, isSelectCase: 1 }
                    });
                } else {
                    this.$toast("请先选择就诊人");
                }
            },
            // 选择职称
            onSelect(data) {
                this.currentJobTitleIndex = data.index;
            },
            // 日期格式化
            formatterDate(type, value) {
                if (type === "year") {
                    return `${value}年`;
                } else if (type === "month") {
                    return `${value}月`;
                }
                return `${value}日`;
            },
            // 确认时间
            confirmDate(date) {
                this.dateShow = false;
                var str =
                    date.getFullYear() +
                    "/" +
                    String(date.getMonth() + 1).padStart(2, "0") +
                    "/" +
                    String(date.getDate()).padStart(2, "0");
                this.currentStr = str;
                console.log(str);
            },
            // 发送短信验证码
            SendSMS() {
                var MobileReg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
                if (!this.phone) {
                    return this.$toast("请输入手机号");
                }
                if (!MobileReg.test(this.phone)) {
                    return this.$toast("请输入正确的手机号");
                }
                this.SendSMSLoading = true;
                this.countDown();
                setTimeout(() => {
                    this.$http
                        .SendModifyPswdSMS({
                            mobile: this.phone,
                            verificationCode: ""
                        })
                        .then(res => {
                            this.SendSMSLoading = false;
                            this.$toast(res.data.ResultMsg);

                            if (res.data.IsSuccess) {
                            } else {
                                this.time = 0;
                            }
                        })
                        .catch(err => {
                            this.SendSMSLoading = false;
                            this.time = 0;
                        });
                }, 100);
            },
            // 倒计时  callback => 回调函数
            countDown() {
                // 按钮禁用
                this.SendSMSDisabled = true;
                this.time = 120;

                this.timeId = setInterval(
                    function() {
                        this.time = this.time - 1;
                        this.SMSTips = `还剩${this.time}秒`;

                        if (this.time <= 0) {
                            clearInterval(this.timeId);
                            this.time = 0;
                            this.timeId = null;
                            // 按钮解禁
                            this.SendSMSDisabled = false;
                            this.SMSTips = `发送验证码`;
                            // this.ClearInterval();
                        }
                    }.bind(this),
                    1000
                );
            },
            // 清除定时器
            // ClearInterval() {
            //     let _this = this;
            //     clearInterval(_this.timeId);
            //     // 按钮解禁
            //     _this.SendSMSDisabled = false;
            //     _this.SMSTips = `发送验证码`;
            // },
            // 新增手术订单
            AddOrder() {
                var MobileReg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
                var SMSReg = /^[0-9]{6}$/;
                let obj = {
                    familyMemberId: this.familyMemberInfo.ID, //就诊人id
                    medicalFileId: this.caseHistoryInfo.ID, //(string, optional): 病例id ,
                    departmentId: this.departmentObj.id, // -1为初始值//(string, optional): 科室id ,
                    department: this.departmentObj.text, //(string, optional): 科室名称 ,
                    positionalTitles: this.currentJobTitleIndex, //0为初始值//(integer, optional): 职称 ,
                    operationTime: this.currentStr, //选择日期为初始值 //(string, optional): 就诊时间 ,
                    areaCode: this.chooseCityInfo.AreaCode, //(string, optional): 就诊地点 ,
                    areaName: this.chooseCityInfo.AreaName, //(string, optional): 区域名称 ,
                    phone: this.phone, //(string, optional): 电话号码 ,
                    verificationCode: this.verificationCode //(string, optional): 短信验证码
                };

                if (!obj.familyMemberId) return this.$toast("请选择就诊人");
                if (!obj.medicalFileId) return this.$toast("请选择病例");
                if (obj.departmentId == -1) return this.$toast("请选择科室");
                if (!obj.positionalTitles) return this.$toast("请选择职称");
                if (obj.operationTime == "选择日期")
                    return this.$toast("请选择就诊时间");
                if (!obj.areaCode) return this.$toast("请选择就诊地点");
                if (!obj.phone) return this.$toast("请输入电话号码");
                if (!MobileReg.test(obj.phone))
                    return this.$toast("请输入正确的电话号码");
                if (!obj.verificationCode) return this.$toast("请输入短信验证码");
                if (!SMSReg.test(obj.verificationCode))
                    return this.$toast("请输入6位短信验证码");

                // 提交订单
                this.$toast.loading({
                    message: "加载中...",
                    forbidClick: true
                });
                this.$http
                    .AddOrder(obj)
                    .then(res => {
                        this.$toast.clear();

                        if (res.data.IsSuccess) {
                            // 跳转到支付页面
                            this.$router.push({
                                name: "confirmPay",
                                query: {
                                    ordercode: res.data.ResultObject, // 订单编号
                                    price: 50000, // 默认500元
                                    type: 2 // 手术预约状态
                                }
                            });
                        } else {
                            this.$toast(res.data.ResultMsg);
                        }
                    })
                    .catch(err => {
                        this.$toast.clear();
                        this.$toast("网络错误");
                    });
            }
        },
        components: {
            ChooseDepartment
        },
        watch: {
            // 监听当前激活职称
            currentJobTitleIndex(newVal, oldVal) {
                this.actions = this.actions.map(v => {
                    if (v.index == newVal) {
                        v.className = "active";
                    } else {
                        v.className = "";
                    }
                    return v;
                });
            },
            // 预约人信息
            familyMemberInfo(newVal, oldVal) {
                let data = sessionStorage.getItem("FamilyMemberData") || {};
            }
        },
        filters: {
            filterDoctorTitles(index) {
                let arr = [
                    "选择职称",
                    "主任医生",
                    "副主任医生",
                    "主治医生",
                    "医师"
                ];
                return arr[index];
            }
        },
        created() {
            this.init();
        }
    };
</script>
<style lang='less' scoped>
    .red {
        color: red;
    }

    /deep/ .van-popup {
        padding: 0.1rem;
    }

    .active {
        color: #7bb7fe;
        background: #f4f4f6;
    }

    // 预约信息模块
    .order-wrapper {
        position: relative;
        width: 7.1rem;
        background-color: #ffffff;
        box-shadow: 0.03rem 0.04rem 0.1rem 0rem rgba(218, 218, 218, 0.25);
        border-radius: 0.1rem;
        margin: 0 auto 0.2rem;
        overflow: hidden;
        z-index: 2;
        /deep/ .van-cell__title {
            flex: none;
        }
        /deep/ .van-cell__value {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-left: 0.2rem;
        }

        // 提示信息样式
        .tipsMessage /deep/ .van-cell__value {
            font-size: 0.2rem;
            line-height: 0.3rem;
            color: #999999;
            overflow: auto;
            white-space: pre-wrap;
            text-overflow: clip;
        }
    }
    .wrapper {
        min-height: 100vh;
        background: #f4f4f6;
        padding-bottom: 0.4rem;
        overflow: hidden;
        .banner {
            position: relative;
            height: 2.66rem;
            background-image: linear-gradient(-24deg, #3575fa 0%, #4eb2ff 100%);
            box-shadow: 0rem 0.02rem 0.16rem 0rem rgba(57, 138, 250, 0.35);
            &:before {
                content: "";
                display: block;
                height: 1.66rem;
                background: url("../../../assets/images/surgery/subBanner.png")
                    no-repeat bottom/100%;
            }
            &::after {
                content: "";
                position: absolute;
                z-index: 1;
                background: #f4f4f6;
                left: -1.5rem;
                bottom: -0.5rem;
                width: 10rem;
                height: 1rem;
                transform: rotate(-5deg);
            }
        }

        .tips {
            line-height: 1.5;
            text-align: left;
            padding: 0.05rem 0.26rem;
            font-size: 0.22rem;
            color: #999999;
        }

        .button {
            width: 6rem;
        }
    }
</style>