<template>
    <nav-bar ref="navbar" id="navbar" :navbar-data="navbarData"></nav-bar>
    <view class="page visitorEntry" :class="{'ov-h': showBook}" :style="{ paddingTop: height +'px'}">
        <view class="step-content">
            <uni-steps :options="steps" :active="active" active-color="#38f" />
        </view>
        <view v-if="active == 0">
            <view class="value">
                <van-cell-group>
                    <view class="row">
                        <label>姓名</label>
                        <view class="row-right">
                            <input type="text" :value="username" placeholder="请输入姓名" @input="onChangeUsername" @blur="onBlurUsername" />
                        </view>
                    </view>
                    <van-cell title="证件类型" @click="descCredType" :value="showDesclist.text">
                        <!-- <view slot="right-icon">
                            <picker mode="selector" :range="cardTypeList" range-key="label" @change="onSelectDescData">
                            	<view class="picker-content">{{ showDesclist && showDesclist.text ? showDesclist.text : '' }}</view>
                            </picker>
                        </view> -->
                    </van-cell>
					
                    <!-- <van-overlay :show="showDesc" @click="onCloseDesc" />
                    <view class="sexListValue" v-if="showDesc">
                        <picker show-toolbar title="请选择证件类型" :columns="cardTypeList" @cancel="onCloseDesc"
                            @confirm="onSelectDescData" visible-item-count="4">
                        </picker>
                    </view> -->
                    <view class="cardIcon">
                        <view class="row">
                            <label>证件号</label>
                            <view class="row-right">
                                <input type="text" :value="idCardNo" placeholder="请输入证件号" @blur="onChangeIdCardNo" />
                            </view>
                        </view>
                        <view class="uploaderCard" v-if="showDesclist.text == '居民身份证'">
                            <uni-file-picker :file-list="fileList" max-count="1" @after-read="afterRead" multiple="true" accept="image" />
                        </view>
                    </view>
                    <view class="row">
                        <label>手机号</label>
                        <view class="row-right">
                            <input type="number" :value="phone" placeholder="请输入手机号" @input="onChangePhone" />
                        </view>
                    </view>
                    <!-- <view class="row">
                        <label>短信验证码</label>
                        <view class="row-right">
                            <input type="number" :value="verificationCode" placeholder="请输入验证码" @input="onChangeVerificationCode" />
                        </view>
                    </view> -->
                </van-cell-group>
                <!--button class="code" :class="sendState ? '':'disabled'" :disabled="!sendState" @tap="getverificationCode">
                    <view :class="sendState ? getState ? 'node':'node' : 'count-down'">
                        {{ sendCount }}
                        <!-- <van-count-down ref="controlCountDown" class="control-count-down" :time="verificationState" :auto-start="false" format="ss" @finish="finished" /> >
                    </view>
                    {{ sendState ? getState ? '获取中...' : '获取验证码' : '秒后重新获取' }}
                </button-->
                <view class="read">
                    <view class="agree-css" @tap="agree2">
                        <uni-icons type="checkbox-filled" v-if="showButton" color="#1890FFFF" size="20" />
                        <uni-icons type="circle" v-if="showButton ? false : true" size="20" />
                    </view>
                    <view style="color:#666666FF;padding-top: 6rpx;">
                        <text @tap="agree2">我已阅读并同意</text>
                        <text @tap="showBookTap" style="color:#1890FF;">《{{ userData && userData.hospDesc }}在线门诊隐私协议》</text>
                    </view>
                </view>
            </view>
			<!--v-if="ageNum<18"-->
            <view v-if="false" class="child">
                <view class="urgent">你正在添加的就诊人未满18岁，为保障就诊人权益，请添加紧急联系人信息</view>
                <van-cell-group>
                    <view class="row">
                        <label>紧急联系人</label>
                        <view class="row-right">
                            <input type="text" :value="EContact" placeholder="请输入姓名" @input="onEContact">
                        </view>
                    </view>
                    <van-cell title="证件类型" is-link>
                        <view slot="right-icon">
                            <picker mode="selector" :range="cardTypeList" range-key="label" @change="onEContactCredType">
                                <text>{{ EContactCredType && EContactCredType.text ? EContactCredType.text : '' }}</text>
                            </picker>
                        </view>
                    </van-cell>
                    <view class="row">
                        <label>证件号</label>
                        <view class="row-right">
                            <input type="text" :value="EContactIDNo" placeholder="请输入证件号" @input="onEContactIDNo">
                        </view>
                    </view>
                    <view class="row">
                        <label>手机号</label>
                        <view class="row-right">
                            <input type="digit" :value="EContactMobile" placeholder="请输入手机号" @input="onEContactMobile">
                        </view>
                    </view>
                    <van-cell title="关系" is-link>
                        <view slot="right-icon">
                            <picker mode="selector" :range="relationList" range-key="label" @change="onRelation"><text>{{ relation && relation.label ? relation.label : '请选择' }}</text></picker>
                        </view>
                    </van-cell>
                </van-cell-group>
            </view>
        </view>
        <view v-if="active == 1">
            <view class="value">
                <view class="gender">
                    <van-cell title="性别" is-link>
                        <template #value>
                            <picker mode="selector" :range="sexList" range-key="label" @change="onSelectData">
                                <text>{{ genderVal.label ? genderVal.label : '请选择' }}</text>
                            </picker>
                        </template>
                    </van-cell>
                    <van-cell title="出生日期" is-link>
                        <template #value>
                            <uni-datetime-picker type="date" :border="false" :date-icon="false" :clear-icon="false" height="24px" v-model="selectDate" :start="minDate" :end="maxDate"
                                @change="confirmDate" />
                        </template>
                    </van-cell>
                    <van-cell title="民族" is-link>
                        <template #value>
                            <picker mode="selector" :range="nationList" range-key="label" @change="ongetNationData">
                                <text>{{ nationSelect && (nationSelect.label || nationSelect.text) ? (nationSelect.label || nationSelect.text) : '请选择' }}</text>
                            </picker>
                        </template>
                    </van-cell>
                    <van-cell title="职业" is-link>
                        <template #value>
                            <picker mode="selector" :range="OCCUList" range-key="label" @change="ongetOCCUData">
                                <text>{{ OCCUSelect && (OCCUSelect.label || OCCUSelect.text) ? (OCCUSelect.label || OCCUSelect.text) : '请选择' }}</text>
                            </picker>
                        </template>
                    </van-cell>
                    <van-cell-group>
                        <common v-if="isArea" ref="component" difference='difference' :provinceDesc="provinceDesc" :cityDesc="cityDesc" :areaDesc="areaDesc" :villageDesc="villageDesc"
                            @twoLevelCommentBtn='twoLevelCommentBtnClick' status="1" addressData='所在地区' :defaultProvince="defaultProvince" :defaultCity="defaultCity" :defaultArea="defaultArea"
                            :defaultIndexs="selectIndexs" />
                        <view class="row">
                            <label>详细地址</label>
                            <view class="row-right">
                                <input type="text" :value="address" placeholder="请输入详细地址" @input="onChangeAddress">
                            </view>
                        </view>
                    </van-cell-group>
                </view>
            </view>
        </view>
        <view class="success" v-if="active == 2">
            <view class="hook">
                <image class="image" :src="imgHost +'/images/icon/paySucc.png'"></image>
            </view>
            <view class="successPro">绑定成功</view>
            <view class="LinkList">
                <van-button type="info" custom-style="margin-right:100rpx;" class="info" @tap="medicareCardLink">绑定医保卡</van-button>
                <van-button type="info" @tap="cardListLink">就诊人列表</van-button>
            </view>
        </view>
        <view class="next">
            <van-button type="info" @tap="showCamera" v-if="active == 0">确定</van-button>
            <van-button :disabled="Binding ? true : false" type="info" @tap="saveCard" v-if="active == 1">{{Binding ? '绑定中...' : '绑卡'}}</van-button>
        </view>
        <!-- <view class="haveCard" v-if="active !== 2">
            <text @tap="healthItem">已有健康卡，快速绑定 ></text>
        </view> -->
        <van-overlay :show="isShowCamera">
            <view class="wrapper">
                <view class="camera-modal-content">
                    <camera :hidden="!isShowCamera" v-if="isShowCamera" :device-position="devicePosition" flash="off" binderror="cameraError" style="width: 100%; height: 100%;"></camera>
                    <image v-if="photoSrc" style="width: 100%; height: 100%;" :src="photoSrc"></image>
                </view>
                <view class="camera-modal-btn">
                    <van-button type="primary" @tap="takePhoto" loading-text="识别中..." :loading="cameraLoading">{{isVerificationSuccess ? "拍照" : "重新拍照"}}</van-button>
                    <van-button type="primary" @tap="switchCameras">切换为（{{devicePosition === 'front' ? '后置' : '前置'}}）摄像头</van-button>
                    <van-button @tap="onClickHide">取消</van-button>
                </view>
            </view>
        </van-overlay>
    </view>
    <view v-if="showBook" class="privacy-modal" :style="'top:'+ navbarData.height +'px; height: calc(100% - )'+ navbarData.height +'px);'" position="bottom" @close="onCloseBook">
			<view class="privacy-box">
				<text class="privacy-title">{{userData.hospDesc}}隐私协议</text>
				<view class="privacy-content" decode="true">
					<view class="p">用户您好！使用该小程序开展医疗或体检业务首先需要进行人脸认证，相关图片数据和您手机所在位置信息有可能将会存储在我们的服务器里，系统自动验证通过后您方可开展医疗或体检业务。</view>
					<view class="p">使用该小程序进行相关业务时需要接受该条例方可使用。</view>
					<view class="p">感谢使用！</view>
					<view class="p">重视每个用户的的隐私，郑重承诺如下：</view>
					<view class="h1">一、我们所收集的信息以及如何使用：</view>
					<view class="p">我们可能通过您的IP地址、地理位置等信息，收集一些非个人隐私的统计资料，使我们能够进一步改善小程序的服务。</view>
					<view class="p">例如，当您浏览一个网页时，此网址、当时的时间、您所使用的浏览器性质、给您提供接入服务的ISP等，可能都会被自动记录下来。</view>
					<view class="p">(1) COOKIE</view>
					<view class="p">Cookie 是指从网络服务器发送到您的手机或电脑，并储存到手机或电脑硬盘上的少量数据，通常包括一些特殊标识符，是用来记录您的使用者 ID。</view>
					<view class="p">您以根据自己的喜好，设定接收所有 cookies，拒收所有 cookies ，或在设定 cookie 时得到通知。然而您必须在开启您的cookies时才能使用小程序所提供的服务。</view>
					<view class="p">(2) 查询时输入的关键词或者是关键字。</view>
					<view class="p">服务器存储时我们有可能会对该关键字进行加密处理。</view>
					<view class="p">(3) 注册时填写的个人信息</view>
					<view class="p">不传播，不开放，不泄露。</view>
					<view class="h1">二、信息公开与共享</view>
					<view class="p">小程序不会将您的个人资料提供给任何人。但以下情况除外：</view>
					<view class="p">(1) 已获得用户的明确授权；</view>
					<view class="p">(2) 根据有关法律法规的要求或按照法院或相关政府部门的要求；</view>
					<view class="p">(3) 为维护小程序的合法权益；</view>
					<view class="p">(4) 为维护小程序的用户和社会公众的合法权益；</view>
					<view class="p">(5) 小程序认为有必要的其他情况。</view>
					<view class="h1">三、信息的更新和删除</view>
					<view class="p">在您的个人资料有变动的情况下，您可以更新和修改您的个人资料已使其有效。</view>
					<view class="h1">四、保护您的隐私</view>
					<view class="p">我们将采取严格的措施保护您的隐私，确保您的隐私权不受任何侵犯。只要您提供给我们任何个人信息，我们都会采取有效的手段保护您的信息（法律或政府的强制性规定不在此限）。</view>
					<view class="h1">五、更新隐私条款</view>
					<view class="p">我们可能会对小程序的隐私权政策进行修改，如果在使用用户个人信息政策方面有大幅度修改时，我们会通过短信或电子邮件通知您。</view>
				</view>
			</view>
			<view class="privacy-btn">
				<button class="button_agree" type="default" @click.stop="agree">已阅读并同意</button>
			</view>
    </view>
</template>

<script>
    import $http from "@/utils/https";
    import Utils from '@/utils/utils';
    import httpConfig from '@/utils/httpConfig';
    import GenerateTestUserSig from '@/debug/GenerateTestUserSig';
    import navBar from '@/components/navBar/index'
    import VanCountDown from '@/components/count-down/index'
    import VanButton from '@/components/button/index'
	import VanPopup from '@/components/popup/index'
    import VanCellGroup from '@/components/cell-group/index'
    import VanCell from '@/components/cell/index'
    import VanOverlay from '@/components/overlay/index'
    import VanUploader from '@/components/overlay/index'
    import common from '../../common/address'
    import {
        bindMarketerPatient,
        addOrSwitchPatient,
        checkCurrentHospitalAdmRecord
    } from '@/utils/common';

    const app = getApp();
    export default {
        components: {
            'nav-bar': navBar,
            'van-count-down': VanCountDown,
            'van-button': VanButton,
            'van-cell-group': VanCellGroup,
            'van-cell': VanCell,
            'van-overlay': VanOverlay,
            'van-uploader': VanUploader,
            'van-popup': VanPopup,
            'common': common
        },
        data() {
            return {
				array: ['中国', '美国', '巴西', '日本'],
				index: 0,
                height: app.globalData.height,
                imgHost: httpConfig && httpConfig.imgHost,
                windowHost: httpConfig && httpConfig.ipDeault,
                navbarData: {
                    isGoHome: true,
                    homePath: '../../../../pages/tabBar/index/index',
                    isGoBack: true,
                    title: "添加就诊人",
					height: 0
                },
                url: '',
                userData: null,
                steps: [{
                        title: '基本信息',
                    },
                    {
                        title: '其他信息',
                    },
                    {
                        title: '成功',
                    }
                ],
                value1: '0',
                show: false,
                Binding: false,
                active: 0,
                maxStepActive: 0,
                radio: 0,
                username: '', //姓名
                phone: '', // 手机号
                idCardNo: '', // 身份证号
                verificationCode: '666666', // 验证码
                genderVal: {}, // 性别
                address: '', // 地址
                relation: {}, //关系
                show: false,
                showNation: false,
                showOCCU: false,
                sendState: true, // 验证码发送状态
                sendCount: 60, // 发送间隔时间
                timer: null, // 
                idCardState: false,
                showCardType: false,
                showRelation: false,
                idCardContact: false,
                showDesc: false,
                verificationState: null,
                EContactIDShow: false,
                ageNum: 19,
                sexList: [],
                nationList: [],
                nationSelect: {},
                OCCUSelect: {},
                showDesclist: {},
                selectDate: '1994-12-05',
                showDay: false,
                currentDate: new Date().getTime(),
                minDate: new Date(1900, 1, 1).getTime(),
                maxDate: new Date().getTime(),
                formatter: function(type, value) {
                    if (type === 'year') {
                        return `${value}`;
                    } else if (type === 'month') {
                        return `${value}`;
                    } else if (type === 'day') {
                        return `${value}`;
                    }
                    return value;
                },
                selectIndexs: [],
                selectAddress: [],
                cardTypeList: [],
                relationList: [],
                OCCUList: [], //职业
                EContact: '', //联系人
                EContactIDNo: '',
                EContactMobile: '',
                EContactCredType: {},
                relation: {},
                flag: '',
                // totalData:{},
                getState: false,
                fileList: [],
                provinceDesc: "",
                cityDesc: "",
                areaDesc: "",
                villageDesc: "",
                defaultProvince: {},
                defaultCity: {},
                defaultArea: {},
                isShowCamera: false,
                photoSrc: "",
                cameraLoading: false,
                devicePosition: "front", // 摄像头方向
                isVerificationSuccess: true,
                historyIdCardNo: "",
                historyName: "",
                faceValue: "", // 人脸特征值
                downPath: "", // 人脸验证过后的人脸照片
                MedicalCard: "", // 就诊卡
                showButton: false,
                showBook: false,

                isArea: false, // 所在地区是否显示
            }
        },
        onLoad() {
            const userData = this.$cache.get('userData')
            this.setData({
                userData: userData ? userData : {}
            })
            const eventChannel = this.getOpenerEventChannel()
            if (eventChannel && eventChannel.hasOwnProperty('on')) {
                eventChannel.on("turnBack", (data) => {
                    if (data.url) {
                        this.setData({
                            url: data.url,
                        });
                    }
                })
            }

            // #ifdef H5
            // 监听 postMessage：接收通过 window.open 打开的外部页面发送的参数（跨域可用、不刷新当前页）
            window.addEventListener('message', function(event) {
                if (event.data && event.data.type === 'addUsersuccess' && event.data.value === '1') {
                    // 收到外部页面传参后自动触发绑卡
                    this.saveCard();
                }
            });
            // #endif
        },
        onReady: function() {
            this.getcardDetailList();
            const eventChannel = this.getOpenerEventChannel();
            if (eventChannel && eventChannel.hasOwnProperty('on')) {
                eventChannel.on('back', (data) => {
                    this.setData({
                        flag: data.url,
                        // totalData: data.totalData
                    })
                });
            }
			const { navbarData } = this
			console.log('this.$refs.navbar==', this.zpSelectComponent('#navbar'))
			navbarData.height = this.zpSelectComponent('#navbar').height
			this.setData({
				navbarData
			})
        },
		methods: {
            showToast(title, icon) {
                uni.showToast({
                    icon: icon ? icon : 'none',
                    title: title,
                    duration: 3000
                })
            },
            //子组件传值
            twoLevelCommentBtnClick(e) {
                this.setData({
                    selectIndexs: e.detail.indexs,
                    selectAddress: e.detail.value
                }, () => {
                    this.setData({
                        provinceDesc: this.selectAddress[0] ? this.selectAddress[0].label : '', //现住址
                        cityDesc: this.selectAddress[1] ? this.selectAddress[1].label : '',
                        areaDesc: this.selectAddress[2] ? this.selectAddress[2].label : '',
                        villageDesc: this.selectAddress[3] ? this.selectAddress[3].label : '',
                    })
                });
            },

            onInput: Utils.throttle(function(event) {
                this.setData({
                    currentDate: event.detail
                });
            }, 0),

            confirmDate: function() {
                var d = new Date(this.currentDate);
                var date = (d.getFullYear()) + "-" + (d.getMonth() + 1) + "-" + (d.getDate());
                this.setData({
                    selectDate: date,
                    showDay: false
                })
            },

            shoeTimeDate: function() {
                this.setData({
                    showDay: true
                })
            },

            closeTiem: function() {
                this.setData({
                    showDay: false
                })
            },

            start() {
                this.$refs.controlCountDown.start();
            },

            pause() {
                this.$refs.controlCountDown.pause();
            },

            reset() {
                this.$refs.controlCountDown.reset();
            },

            finished() {
                this.setData({
                    verificationState: null,
                    sendState: true,
                    getState: false
                });
            },

            /**请求就诊人列表下拉数据
             * **/
            getcardDetailList: function() {
                let data = {
                    params: []
                }
                $http.post("urlS", this, {
                    code: "01030011",
                    data: data,
                    success: function(res) {
                        console.log('01030011===', res, +res.errorCode)
                        if (+res.errorCode === 0) {
                            this.setData({
                                defaultProvince: res.defalutProvince ? res.defalutProvince : {},
                                defaultCity: res.defalutCity ? res.defalutCity : {},
                                defaultArea: res.defalutArea ? res.defalutArea : {}
                            }, () => {
                                // console.log(this.defaultProvince)
                            })
                            if (res.sex.length > 0) {
                                for (var i = 0; i < res.sex.length; i++) {
                                    res.sex[i].text = res.sex[i].label
                                }
                                this.setData({
                                    sexList: res.sex
                                });
                            }
                            if (res.nation.length > 0) {
                                for (var k = 0; k < res.nation.length; k++) {
                                    res.nation[k].text = res.nation[k].label
                                }
                                let nationDefault = res.nation.filter((item) => item.label == '汉族');
                                this.setData({
                                    nationList: res.nation,
                                    nationSelect: nationDefault[0]
                                });
                            }
                            if (res.credType.length > 0) {
                                for (var j = 0; j < res.credType.length; j++) {
                                    res.credType[j].name = res.credType[j].label;
                                    res.credType[j].text = res.credType[j].label;
                                    if (res.credType[j].label == '居民身份证') {
                                        this.setData({
                                            showDesclist: res.credType[j],
                                            EContactCredType: res.credType[j]
                                        });
                                    }
                                }
								console.log('res.credType === ', res.credType)
                                this.setData({
                                    cardTypeList: res.credType
                                });
                            }
                            if (res.OCCU.length > 0) {
                                for (var j = 0; j < res.OCCU.length; j++) {
                                    res.OCCU[j].name = res.OCCU[j].label;
                                    res.OCCU[j].text = res.OCCU[j].label;
                                }
                                this.setData({
                                    OCCUList: res.OCCU
                                });
                            }
                            if (res.relation.length > 0) {
                                for (var h = 0; h < res.relation.length; h++) {
                                    res.relation[h].text = res.relation[h].label
                                }
                                this.setData({
                                    relationList: res.relation,
                                    relation: res.relation && res.relation.length > 0 ? res.relation[0] : null
                                });
                            }
                        } else {
                            this.setData({
                                nationList: [],
                                sexList: []
                            });
                        }
                        this.setData({
                            isArea: true
                        })
                    },
                    fail(err) {
                        this.setData({
                            isArea: true
                        })
                    }
                });
            },
			
			// 身份证号校验
            idCardcode: function(idCard, val) {
				console.log('验证身份证号开始')
                idCard = (idCard + "").replace(/(^\s+)|\s+$/g, '');
                //15位或者18位身份证号码的正则表达式
                var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
                //如果通过该验证，说明身份证格式正确，但准确性还需计算
                if (regIdCard.test(idCard)) {
                    if (idCard.length == 18) {
                        var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
                        var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
                        var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
                        for (var i = 0; i < 17; i++) {
                            idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
                        }
                        var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
                        var idCardLast = idCard.substring(17); //得到最后一位身份证号码

                        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
                        if (idCardMod == 2) {
                            if (idCardLast == "X" || idCardLast == "x") {
                                if (val) {
                                    this.setData({
                                        idCardContact: true,
                                        EContactIDNo: idCard
                                    });
                                } else {
                                    this.setData({
                                        idCardNo: idCard,
                                        idCardState: true
                                    }, () => {
                                        console.log("idCard1", this.idCard)
                                    });
                                    this.calculateAge(idCard)
                                }
                            } else {
                                if (val) {
                                    this.setData({
                                        idCardContact: false,
                                    })
                                } else {
                                    this.setData({
                                        idCardState: false
                                    })
                                }
                            }
                        } else {
                            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                            if (idCardLast == idCardY[idCardMod]) {
								console.log('校验通过==')
                                if (val) {
                                    this.setData({
                                        idCardContact: true,
                                        EContactIDNo: idCard
                                    });
                                } else {
									console.log('身份证号--', idCard)
                                    this.setData({
                                        idCardNo: idCard,
                                        idCardState: true
                                    });
									console.log('保存后的身份证号--', this.idCardNo)
                                    this.calculateAge(idCard)
                                }
                            } else {
                                if (val) {
                                    this.setData({
                                        idCardContact: false
                                    })
                                } else {
                                    this.setData({
                                        idCardState: false
                                    })
                                }
                            }
                        }
                    }
                } else {
                    if (val) {
                        this.setData({
                            idCardContact: false
                        })
                    } else {
                        this.setData({
                            idCardState: false
                        })
                    }
                }

            },

            // 通过身份证号获取年龄大小
            calculateAge: function(certificateNum) {
                if (certificateNum) {
                    var myDate = new Date();
                    var month = myDate.getMonth() + 1;
                    var day = myDate.getDate();
                    var age = myDate.getFullYear() - certificateNum.substring(6, 10) - 1;
                    if (certificateNum.substring(10, 12) < month || certificateNum.substring(10, 12) == month && certificateNum.substring(12, 14) <= day) {
                        age++;
                    }
					console.log('age==', age)
					if(age < 6) {
						uni.showToast({
							icon: "none",
							title: "患者年龄小于6岁，无法添加就诊人",
							duration: 3000
						})
					}
                    this.setData({
                        ageNum: age
                    })
                }
            },

            // 手机号验证
            handleVerificationMobile: function(value) {
                if (value && (/^1[3456789]\d{9}$/.test(value.replace(/\s*/g, '')))) {
                    return false;
                } else {
                    return true
                }
            },

            /**获取验证码
             * **/
            getverificationCode: function() {
                const self = this;
                self.setData({
                    getState: true
                })
                if (!self.phone) {
                    self.showToast('手机号码有误', 'error')
                    self.setData({
                        getState: false
                    })
                    return
                }
                if (!self.sendState) {
                    self.setData({
                        getState: false
                    })
                    return
                }
                let data = {
                    params: [{
                        mobile: self.phone
                    }]
                }

                $http.post("urlS", self, {
                    code: "01020014",
                    data: data,
                    success: function(res) {
                        if (+res.errorCode === 0) {
                            let a = res.result ? res.result.effectTime : 60;
                            // self.setData({
                            //     verificationState: a,
                            //     sendState: false
                            // })
                            self.setData({
                                verificationState: 300 * 1000,
                                sendCount: a,
                                sendState: false,
                                getState: false
                            }, () => {
                                self.timer = setInterval(() => {
                                    this.sendCount--
                                    if (this.sendCount < 0) {
                                        clearInterval(self.timer)
                                        self.setData({
                                            sendCount: 300,
                                            sendState: true,
                                            getState: false
                                        })
                                        return
                                    }
                                }, 1000)
                            })
                        } else {
                            self.showToast(res.errorMessage)
                            self.setData({
                                sendState: true,
                                getState: false
                            })
                        }
                    }
                });
            },

            /**验证验证码 */
            verificationData: function() {
                let {
                    historyName,
                    historyIdCardNo
                } = this;
                let data = {
                    params: [{
                        mobile: this.phone,
                        verifyCode: this.verificationCode,
                    }]
                }
                $http.post("urlS", this, {
                    code: "01020015",
                    data: data,
                    success: function(res) {
                        if (+res.errorCode === 0) {
                            // 需要人脸识别时去掉下面注释 - 2021/10/19 11:11
                            // if ((this.username !== historyName) || (this.idCardNo !== historyIdCardNo)) {
                            //   this.setData({
                            //     isShowCamera: true
                            //   })
                            // }
                            this.nextStep()
                        } else {
                            this.showToast(res.errorMessage)
                        }
                    }
                });
            },

            /**根据身份证获取生日性别 */
            idCardDetail: function() {
                let {
                    defaultProvince,
                    defaultCity,
                    defaultArea
                } = this;
                let id = this.idCardNo;
                if (parseInt(id.substr(16, 1)) % 2 == 1) {
                    let sex = {
                        label: '男',
                        value: '1',
                        text: '男'
                    }
                    if (this.showDesclist.text == '居民身份证') {
                        this.setData({
                            genderVal: sex
                        })
                    }
                } else {
                    let sex = {
                        label: '女',
                        value: '2',
                        text: '女'
                    }
                    if (this.showDesclist.text == '居民身份证') {
                        this.setData({
                            genderVal: sex
                        })
                    }
                }
                if (this.showDesclist.text == '居民身份证') {
                    let date1 = id.substring(6, 10) + "-" + id.substring(10, 12) + "-" + id.substring(12, 14);
                    this.setData({
                        selectDate: date1
                    });
                }

                // if (defaultProvince.descripts) {
                //     this.selectComponent("#component").getProvinceDetail(defaultProvince.descripts);
                // } else {
                //     this.selectComponent("#component").getProvinceDetail();
                // }
                // if (defaultCity.descripts) {
                //     this.selectComponent("#component").getCityDetail(defaultProvince.id, defaultCity.descripts);
                // }
                // if (defaultArea.descripts) {
                //     this.selectComponent("#component").getAreaDetail(defaultCity.id, defaultArea.descripts);
                // }
                // if (defaultArea.id) {
                //     this.selectComponent("#component").getStreetDetail(defaultArea.id, '');
                // }
            },

            // 姓名
            onChangeUsername: function(e) {
                // console.log('onChangeUsername', e)
                this.setData({
                    username: e.detail.value
                })
            },

            // 证件号
            onChangeIdCardNo: function(e) {
                console.log('onChangeIdCardNo', this.showDesclist.text !== '居民身份证')
                if (this.showDesclist.text !== '居民身份证') {
                    this.setData({
                        idCardNo: e.detail.value
                    });
                } else {
                    this.idCardcode(e.detail.value);
                }
            },

            // 手机号
            onChangePhone: function(e) {
                // console.log(e)
                if (e.detail.value && (/^1[3456789]\d{9}$/.test(e.detail.value.replace(/\s*/g, '')))) {
                    this.setData({
                        verificationState: null,
                        sendState: true,
                        getState: false
                    });
                    this.setData({
                        phone: e.detail.value
                    })
                }
            },

            onChangeVerificationCode: function(e) {
                this.setData({
                    verificationCode: e.detail.value
                })
            },

            onChangeAddress: function(event) {
                // console.log(event)
                this.setData({
                    address: event.detail.value
                })
            },

            onBlurAddress: function(event) {
                this.setData({
                    address: event.detail.value
                })
            },

            // 绑定就诊人时，调用02、03
            bindMarketer(patID) {
                console.log(patID, app.globalData.activityObj)
                if (app.globalData.activityObj) {
                    bindMarketerPatient(this, patID).then(() => {
                        addOrSwitchPatient(this, patID).then(() => {
                            app.globalData.scene = '' // 操作完成，清空场景值
                        })
                    })
                }
            },

            // 下一步
            nextStep: function() {
                if (!this.username) {
                    this.showToast('姓名有误', 'error')
                    return
                }

                // if (!this.MedicalCard) {
                //   this.showToast(就诊卡有误,'error')
                //   return
                // }

                if (!this.phone) {
                    this.showToast('手机号码有误', 'error')
                    return
                }
                if (!this.verificationCode) {
                    this.showToast('验证码不能为空', 'error')
                    return
                }
                if (!this.showButton) {
                    this.showToast('请先阅读并勾选在线门诊隐私协议')
                    return;
                }
				
				if(this.ageNum < 6) {
					uni.showToast({
						icon: "none",
						title: "患者年龄小于6岁，无法添加就诊人",
						duration: 3000
					})
					return
				}
				
				// let data = {
				//     params: [{
				// 		"cardTypeID": "1", // 1:身份证 2：就诊卡 
				// 		"cardNo": "",
				// 		"patNo": "",
				// 		"IDCardNo": this.idCardNo,
				//         "verificationCode": this.verificationCode
				//     }]
				// }
				// uni.showLoading({
				// 	title: "处理中..."
				// })
				// $http.post("urlS", this, {
				//     code: "12110001",
				//     data: data,
				//     success: function(res) {
				// 		uni.hideLoading()
				// 		console.log('就诊人信息===', res)
				//         if (+res.errorCode == 0) {
				// 			if(res.result[0].patID) {
				// 				app.globalData.isUpdatePatList = true;
				// 				this.setData({
				// 				    active: 2,
				// 				});
				// 				let {
				// 				    userData
				// 				} = this;
				// 				this.$cache.set('userData', {
				// 				    ...userData,
				// 				    patID: res.result[0].patID
				// 				})
				// 				this.getAdmSelectData(res.patID)
								
				// 				if (this.flag === 'home') {
				// 				    uni.switchTab({
				// 				        url: '/pages/tabBar/index/index'
				// 				    })
				// 				} else if (this.url) {
				// 				    let that = this;
				// 				    uni.redirectTo({
				// 				        url: that.data.url,
				// 				    })
				// 				} else {
				// 				    setTimeout(function() {
				// 				        let pages = getCurrentPages(); // 获取所需页面
				// 				        let prevPage = pages[pages.length - 2]; // 上一页
				// 				        prevPage.setData({
				// 				            refreshData: 1
				// 				        }) // 设置需参数
				// 				        uni.navigateBack({
				// 				            delta: 1
				// 				        })
				// 				    }, 2000)
				// 				}
				// 			} else {
				// 				uni.showModal({
				// 					title: "温馨提示",
				// 					content: "未查询到医院就诊信息，请到院进行诊疗",
				// 					showCancel: false,
				// 					confirmText: "关闭"
				// 				})
				// 			}
				// 		}
				// 	},
				// })
                let data = {
                    params: [{
                        idCardNo: this.idCardNo,
                        mobile: this.phone,
                        name: this.username,
                        // medicalCard: this.MedicalCard, // 就诊卡
                        verificationCode: this.verificationCode
                    }]
                }
                $http.post("urlS", this, {
                    code: "01030008",
                    data: data,
                    success: function(res) {
                        if (+res.errorCode == 0) {
                            app.globalData.isUpdatePatList = true;
                            this.setData({
                                active: 2,
                            });
                            let {
                                userData
                            } = this;
                            this.$cache.set('userData', {
                                ...userData,
                                patID: res.patID
                            })

                            this.getAdmSelectData(res.patID)

                            //#ifdef MP-WEIXIN
                            // 老用户在当前医院有没有就诊记录，如果有就调用03，如果没有就调用02、03
                            // checkCurrentHospitalAdmRecord().then(res => {
                            //     if (res && res.result.visitFlag == 'Y') {
                            //         addOrSwitchPatient(self, res.patID).then(() => {
                            //             app.globalData.scene = '' // 操作完成，清空场景值
                            //         })
                            //     } else {
                            //         self.bindMarketer(res.patID)
                            //     }
                            // })
                            //#endif

                            if (this.flag === 'home') {
                                uni.switchTab({
                                    url: '/pages/tabBar/index/index'
                                })
                            } else if (this.url) {
                                let that = this;
                                uni.redirectTo({
                                    url: that.data.url,
                                })
                            } else {
                                setTimeout(function() {
                                    // uni.navigateTo({
                                    //   url: '../addAVisitor/addAVisitor'
                                    // })
                                    let pages = getCurrentPages(); // 获取所需页面
                                    let prevPage = pages[pages.length - 2]; // 上一页
                                    prevPage.setData({
                                        refreshData: 1
                                    }) // 设置需参数
                                    uni.navigateBack({
                                        delta: 1
                                    })
                                }, 2000)
                            }
                            // 需要人脸识别时去掉下面注释 - 2021/10/19 11:11
                            // this.handleUploadFile()
                        } 
                        else if (+res.errorCode == 100) {
                           this.setData({
                               active: 1,
                               maxStepActive: 1,
                           })
                           this.idCardDetail()
                           // 需要人脸识别时去掉下面注释 - 2021/10/19 11:11
                           // this.handleUploadFile().then(res => {
                           //   if(res) {
                           //     this.setData({
                           //       active: 1,
                           //       maxStepActive: 1,
                           //     })
                           //     this.idCardDetail()
                           //   }
                           // });
                        } 
                        // else {
                        //     // this.showToast(res.errorMessage)
                        //     console.log('error===', res)
                        //     // this.showToast('')
                        //     uni.showModal({
                        //         title: "温馨提示",
                        //         content: res.errorMessage + '，请您进入绵阳市骨科医院微信公众号完成就诊卡注册',
                        //         showCancel: false,
                        //         confirmText: "关闭"
                        //     })  
                        // }
                    }
                });
            },

            // 绑卡
            saveCard: function() {
                const self = this
                this.setData({
                    Binding: true
                })
                if (!this.genderVal.text) {
                    this.showToast('请选择性别', 'error')
                    this.setData({
                        Binding: false
                    })
                    return
                }
                if (this.selectAddress.length < 1) {
                    this.showToast('所在地区不能为空', 'error')
                    this.setData({
                        Binding: false
                    })
                    return
                }
                if (!this.address) {
                    this.showToast('详细地址不能为空', 'error')
                    this.setData({
                        Binding: false
                    })
                    return
                };
                let defaultPro = this.defaultProvince.id ? this.defaultProvince.id : '';
                let defaultCi = this.defaultCity.id ? this.defaultCity.id : '';
                let data = {
                    params: [{
                        errorCode: 0,
                        location: "",
                        patAddress: this.address,
                        patAreaID: this.selectAddress.length > 0 && this.selectAddress[2][0] ? this.selectAddress[2][0].value : '',
                        patBirthDate: this.selectDate,
                        patCityID: this.selectAddress.length > 0 && this.selectAddress[1][0] ? this.selectAddress[1][0].value : defaultCi,
                        patIDCardNo: this.idCardNo,
                        patMobile: this.phone,
                        patName: this.username,
                        patNationID: this.nationSelect.text ? this.nationSelect.value : '',
                        OCCUID: this.OCCUSelect.text ? this.OCCUSelect.value : '', //职业
                        patCredTypeID: this.showDesclist.text ? this.showDesclist.value : '',
                        patCredTypeCode: this.showDesclist.code ? this.showDesclist.code : '',
                        patProvinceID: this.selectAddress.length > 0 && this.selectAddress[0][0] ? this.selectAddress[0][0].value : defaultPro,
                        patSexID: this.genderVal.text ? this.genderVal.value : "",
                        patVillageID: this.selectAddress.length > 0 && this.selectAddress[3][0] ? this.selectAddress[3][0].value : '',
                        verificationCode: this.verificationCode,
                        patEContact: this.EContact,
                        patEContactMobile: this.EContactMobile,
                        patEContactCredTypeIDNo: this.EContactIDNo,
                        patEContactCredTypeID: this.EContactCredType.text ? this.EContactCredType.value : '',
                        patEContactCredTypeCode: this.EContactCredType.code ? this.EContactCredType.code : '',
                        relationID: this.relation.text ? this.relation.value : '',
                        faceValue: this.faceValue, // 人脸特征值
                        patPhoto: this.downPath, // 人脸验证过后的人脸照片
                        // patMedicalCard: this.MedicalCard ? this.MedicalCard : '',
                    }]
                }
                console.log('data', data)
                // return;
                $http.post("urlS", this, {
                    code: "01030004",
                    data: data,
                    success: function(res) {
                        this.setData({
                            Binding: false
                        })
                        if (+res.errorCode === 0) {
                            app.globalData.isUpdatePatList = true;
                            this.showToast(res.errorMessage, 'success')
                            this.setData({
                                active: 2
                            });

                            let {
                                userData
                            } = this;
                            this.$cache.set('userData', {
                                ...userData,
                                patID: res.result && res.result.patID ? res.result.patID : ''
                            })
                            this.login("patient" + res.result.hisPatID) // 登录TIM 
                            this.getAdmSelectData(res.result.patID)

                            if (this.flag === 'home') {
                                setTimeout(function() {
                                    uni.switchTab({
                                        url: '/pages/tabBar/index/index'
                                    })
                                }, 2000)
                            } else if (self.url) {
                                uni.redirectTo({
                                    url: self.url,
                                })
                            } else {
                                // setTimeout(function(){
                                //   uni.navigateTo({
                                //     url:'../addAVisitor/addAVisitor'
                                //   },2000)
                                // })
                            }
                        } else {
                            // this.showToast(res.errorMessage, 'error')
                            const userData = this.$cache.get('userData');
                            uni.showModal({
                                title: "温馨提示",
                                content: res.errorMessage + '，请您进入'+ userData.hospDesc +'微信公众号完成就诊卡注册',
                                showCancel: false,
                                confirmText: "关闭",
								success(res) {
									if(res.confirm) {
										// 使用 window.open 打开外部页面，保持当前页面不关闭
										// 外部页面可通过 window.opener.postMessage 向本页传递参数（支持跨域，不刷新）
										//window.open("http://wechat.scsmysgkyy.cn/pageA/outpat/health_card/reg_other/index");
									}
								}
                            })  
                        }
                    }
                })
            },

            onClose: function() {
                this.setData({
                    show: false
                });
            },

            onRelationshow: function() {
                this.setData({
                    showRelation: true
                });
            },

            onRelation: function(event) {
                const index = event.detail.value
                const {
                    relationList
                } = this
                this.setData({
                    showRelation: false,
                    relation: {
                        text: relationList[index].label,
                        name: relationList[index].label,
                        label: relationList[index].label,
                        code: relationList[index].code,
                        descriptsSPCode: relationList[index].descriptsSPCode,
                        enDescrips: relationList[index].enDescrips,
                        value: relationList[index].value
                    }
                });
            },

            onCloseRelation: function() {
                this.setData({
                    showRelation: false
                });
            },

            onSelectShow: function() {
                this.setData({
                    show: true
                });

            },

            onSelectData: function(e) {
                const index = e.detail.value
                const {
                    sexList
                } = this
                this.setData({
                    show: false,
                    genderVal: {
                        descriptsSPCode: sexList[index].descriptsSPCode,
                        text: sexList[index].label,
                        label: sexList[index].label,
                        value: sexList[index].value
                    }
                });
            },

            onCloseNation: function() {
                this.setData({
                    showNation: false
                });
            },

            onShowNation: function() {
                this.setData({
                    showNation: true
                });
            },

            onShowOCCU: function() {
                this.setData({
                    showOCCU: true
                });
            },

            onCloseOCCU: function() {
                this.setData({
                    showOCCU: false
                });
            },

            onSelectNation: function() {
                this.setData({
                    showNation: true
                });
            },

            ongetNationData: function(event) {
                const {
                    nationList
                } = this
                // console.log(event)
                this.setData({
                    showNation: false,
                    nationSelect: nationList[event.detail.value]
                });
            },

            ongetOCCUData: function(event) {
                const {
                    OCCUList
                } = this
                this.setData({
                    showOCCU: false,
                    OCCUSelect: OCCUList[event.detail.value]
                });
            },

            descCredType: function() {
                this.setData({
                    showDesc: true
                })
            },

            onSelectDescData: function(event) {
                // console.log(event)
                const {
                    cardTypeList
                } = this
                const index = event.detail.value
                this.setData({
                    showDesc: false,
                    showDesclist: {
                        value: cardTypeList[index].value,
                        text: cardTypeList[index].label,
                        label: cardTypeList[index].label,
                        name: cardTypeList[index].name,
                        code: cardTypeList[index].code,
                        descriptsSPCode: cardTypeList[index].descriptsSPCode,
                        enDescrips: cardTypeList[index].enDescrips
                    }
                });
            },

            onCloseDesc: function() {
                this.setData({
                    showDesc: false
                });
            },

            healthItem: function() {
                uni.navigateTo({
                    url: '../../healthCard/healthCard'
                })
            },

            onEContactCredTypeShow: function() {
                this.setData({
                    showCardType: true
                });
            },

            onEContactCredType: function(event) {
                const index = event.detail.value
                const {
                    cardTypeList
                } = this
                this.setData({
                    showCardType: false,
                    EContactCredType: {
                        value: cardTypeList[index].value,
                        text: cardTypeList[index].label,
                        label: cardTypeList[index].label,
                        name: cardTypeList[index].name,
                        code: cardTypeList[index].code,
                        descriptsSPCode: cardTypeList[index].descriptsSPCode,
                        enDescrips: cardTypeList[index].enDescrips
                    }
                });
            },

            onCloseCardType: function() {
                this.setData({
                    showCardType: false
                });
            },

            onEContact: function(event) {
                this.setData({
                    EContact: event.detail
                })
            },

            onBlurEContact: function(event) {
                this.setData({
                    EContact: event.detail.value
                })
            },

            onEContactIDNo: function(event) {
                if (this.EContactCredType.text !== '居民身份证') {
                    this.setData({
                        EContactIDNo: event.detail
                    });
                } else {
                    if (event.detail) {
                        this.setData({
                            EContactIDShow: false
                        })
                        this.idCardcode(event.detail, '1');
                    } else {
                        this.setData({
                            EContactIDShow: true
                        })
                    }
                }
                // this.setData({
                //   EContactIDNo: event.detail
                // });
                // this.idCardcode(event.detail, '1')
            },

            onEContactMobile: function(event) {
                if (event.detail && (/^1[3456789]\d{9}$/.test(event.detail.replace(/\s*/g, '')))) {
                    this.setData({
                        EContactMobile: event.detail
                    })
                }
            },

            //识别身份证
            afterRead(event) {
                const {
                    file
                } = event.detail;
                var _this = this;
                let newUserData = this.$cache.get('userData');
                // console.log("识别身份证", this.windowHost + newUserData.upLoadUrl)
                for (var i = 0; i < file.length; i++) {
                    // console.log("this.windowHost+newUserData.upLoadUrl", this.windowHost + newUserData.upLoadUrl)
                    uni.uploadFile({
                        url: newUserData && newUserData.upLoadUrl ? this.windowHost + newUserData.upLoadUrl : this.windowHost +'/uploadFile?fileType=picture',
                        filePath: file[i].path,
                        name: 'file',
                        success(res) {
                            // 上传完成需要更新
                            if (res.statusCode === 200) {
                                let imgName = JSON.parse(res.data).filePath;
                                let path = (newUserData && newUserData.downLoadUrl ? this.windowHost + newUserData.downLoadUrl : this.windowHost +"/images/picture/") + imgName;
                                let data = {
                                    params: [{
                                        imageUrl: path,
                                        pubAccCode: _this.userData.pubAccCode,
                                    }]
                                }
                                $http.post("urlS", this, {
                                    code: "01020017",
                                    data: data,
                                    success: function(res) {
                                        if (+res.errorCode == 0) {
                                            if (res.result.id) {
                                                _this.idCardcode(res.result.id);
                                            }
                                            if (res.result.name) {
                                                _this.setData({
                                                    username: res.result.name
                                                })
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    });
                }
            },

            //跳转到绑定医保卡
            medicareCardLink: function() {
                let userData = this.$cache.get('userData');
                let data = {
                    params: [{
                        pubAccCode: userData.pubAccCode || '',
                        openID: userData.openID || '',
                    }]
                }
                $http.post("urlS", this, {
                    code: "01050010",
                    data: data,
                    success: function(res) {
                        if (+res.errorCode === 0) {
                            let result = res.result;
                            uni.navigateToMiniProgram({
                                appId: result.bind_appid || '',
                                path: result.bind_url || '',
                                envVersion: 'release',
                                success(res) {
                                    // 打开成功
                                },
                                fail(error) {
                                    console.log(error)
                                }
                            })
                        }
                    }
                });
            },

            //跳转到就诊卡列表
            cardListLink: function() {
                uni.navigateTo({
                    url: '../addAVisitor/addAVisitor'
                })
            },

            handleStepClick: function(event) {
                let {
                    maxStepActive,
                    villageDesc,
                    areaDesc,
                    cityDesc,
                    provinceDesc
                } = this;
                let detail = event.detail;
                if (detail <= maxStepActive && maxStepActive < 2) {
                    this.setData({
                        active: detail
                    }, () => {
                        if (+this.active === 1) {
                            let cityData = this.selectAddress[1] && this.selectAddress[1][0] ? this.selectAddress[1][0] : {};
                            let areaData = this.selectAddress[2] && this.selectAddress[2][0] ? this.selectAddress[2][0] : {};
                            let villageData = this.selectAddress[3] && this.selectAddress[3][0] ? this.selectAddress[3][0] : {};
                            this.selectComponent("#component").getProvinceDetail(provinceDesc);
                            this.selectComponent("#component").getCityDetail(cityData, cityDesc);
                            this.selectComponent("#component").getAreaDetail(areaData, areaDesc);
                            this.selectComponent("#component").getStreetDetail(villageData, villageDesc);
                        }
                    })
                }
            },

            // 登录
            login: Utils.debounce(function(userID) {
                let userData = GenerateTestUserSig.genTestUserSig(userID || '');
                let promise = app.globalData.tim.login({
                    userID: userID || '',
                    userSig: userData && userData.userSig ? userData.userSig : ""
                });
                promise.then((imResponse) => {
                    // console.log("tim登录成功：", userID);
                    app.globalData.isLogOut = true;
                }).catch((imError) => {
                    // console.log('tim登录失败', userID, imError); // 登录失败的相关信息
                    // this.signOut('signOut', userID);
                });
            }),

            handleMedicalCardChange: function(event) {
                this.setData({
                    MedicalCard: event.detail
                });
            },

            // 打开人脸识别弹窗
            showCamera: function() {
                if (!this.username) {
                    this.showToast('姓名有误', 'error')
                    return
                }

                if (!this.phone) {
                    this.showToast('手机号码有误', 'error')
                    return
                }

                if (!this.idCardNo) {
                    this.showToast('请输入身份证号', 'error')
                    return
                }

                if (!this.verificationCode) {
                    this.showToast('验证码不能为空', 'error')
                    return
                }
				
                if (!this.showButton) {
                    this.showToast('请先阅读并勾选在线门诊隐私协议')
                    return;
                }

                this.verificationData();
            },

            onClickHide: function() {
                this.setData({
                    isShowCamera: false,
                    cameraLoading: false,
                    photoSrc: "",
                    isVerificationSuccess: true
                })
            },

            cameraError: function(error) {
                console.log(error)
            },

            takePhoto: function() {
                const ctx = uni.createCameraContext()
                ctx.takePhoto({
                    success: (res) => {
                        this.setData({
                            photoSrc: res.tempImagePath,
                            cameraLoading: true,
                        }, () => {
                            this.faceVerification();
                        })
                    },
                    fail(res) {
                        console.log(res)
                    },
                    complete(res) {
                        console.log(res)
                    }
                })
            },

            // 人脸验证
            faceVerification: function() {
                let _this = this;
                let {
                    username,
                    idCardNo
                } = this;
                const fileSystemManager = uni.getFileSystemManager();
                fileSystemManager.readFile({
                    "filePath": _this.photoSrc,
                    "encoding": "base64",
                    success(baseData) {
                        let data = {
                            params: [{
                                idCardNo: idCardNo,
                                name: username,
                                imageBase64: baseData.data
                            }]
                        }
                        // console.log(idCardNo, username, baseData.data)
                        $http.post("urlS", _this, {
                            code: "01020023",
                            data: data,
                            // namespace: "Y",
                            success: function(res) {
                                if (+res.errorCode === 0) {
                                    _this.setData({
                                        isShowCamera: false,
                                        historyIdCardNo: idCardNo,
                                        historyName: username,
                                        faceValue: res.result && res.result.faceValue ? res.result.faceValue : ""
                                    }, () => {
                                        _this.nextStep();
                                    })
                                } else {
                                    _this.showToastAndResetInfo(res.errorMessage)
                                }
                            }
                        });
                    },
                    fail(error) {
                        _this.showToastAndResetInfo(error)
                    }
                })
            },

            // 显示错误信息并清空照片信息
            showToastAndResetInfo: function(msg) {
                uni.showToast({
                    title: msg,
                    icon: 'none',
                })
                this.setData({
                    isVerificationSuccess: false,
                    cameraLoading: false,
                    photoSrc: ""
                })
            },

            // 切换摄像头
            switchCameras: function() {
                let devicePosition = this.devicePosition === 'front' ? "back" : "front";
                this.setData({
                    devicePosition
                })
            },

            // 图片上传
            handleUploadFile: function() {
                return new Promise((resolve, reject) => {
                    let newUserData = this.$cache.get('userData');
                    let path = this.photoSrc;
                    let imgType = path.split('.')[path.split('.').length - 1];
                    if ((imgType === "jpg") || (imgType === "png") || (imgType === "jpeg") || (imgType === "gif")) {
                        uni.uploadFile({
                            url: newUserData && newUserData.upLoadUrl ? newUserData.upLoadUrl.indexOf("http") !== -1 ? newUserData.upLoadUrl : this.windowHost + newUserData.upLoadUrl : this.windowHost +'/uploadFile?fileType=picture', //仅为示例，非真实的接口地址
                            filePath: path,
                            name: 'file',
                            success: (unloadres) => {
                                if (unloadres.statusCode === 200) {
                                    let imgName = JSON.parse(unloadres.data).filePath;
                                    let imgPath = (newUserData && newUserData.downLoadUrl ? newUserData.downLoadUrl.indexOf("http") !== -1 ? newUserData.downLoadUrl : this.windowHost + newUserData.downLoadUrl : this.windowHost +"/images/picture/") + imgName;
                                    this.setData({
                                        downPath: imgName
                                    }, () => {
                                        console.log("imgPath", this.downPath)
                                    })
                                    resolve(true)
                                } else {
                                    uni.showToast({
                                        title: "网络异常，请稍后再试。",
                                        icon: 'none',
                                    })
                                    resolve(false)
                                }
                            },
                            fail: (error) => {
                                uni.showToast({
                                    title: "网络异常，请稍后再试。",
                                    icon: 'none',
                                })
                                resolve(false)
                            }
                        })
                    } else {
                        uni.showToast({
                            title: "发送失败：图片类型有误或图片图片太大。",
                            icon: 'none',
                        })
                        resolve(false)
                    }
                })
            },

            // 获取就诊人下拉数据
            getAdmSelectData: function(patID) {
                let data = {
                    params: [{}]
                }
                $http.post("urlS", this, {
                    code: "01030001",
                    data: data,
                    success: function(res) {
                        if (+res.errorCode === 0) {
                            app.globalData.isUpdatePatList = true;
                            let admSelectData = res.result.rows && res.result.rows.length > 0 ? res.result.rows : [];
                            for (var i = 0; i < admSelectData.length; i++) {
                                admSelectData[i].value = admSelectData[i].patID;
                                admSelectData[i].key = i;
                            }
                            this.judgeWhetherThePatientExists(admSelectData, patID);
                        } else {
                            Toast(res.errorMessage);
                            this.judgeWhetherThePatientExists(admSelectData, patID);
                        }
                    }
                });
            },

            // 判断就诊人数据中是否包含storage中选中的数据，如果不包含则清空storage就诊人数据
            judgeWhetherThePatientExists: function(admSelectData, patID) {
                let userData = this.$cache.get('userData');
                let isExistence = false;
                let newData = {};
                for (var i = 0; i < admSelectData.length; i++) {
                    if (patID && (admSelectData[i].patID === patID)) {
                        isExistence = true;
                        newData = admSelectData[i];
                        break
                    }
                }
                if (!isExistence) {
                    this.$cache.set('userData', {
                        ...userData,
                        idCardNo: '',
                        imUserID: '',
                        patDesc: '',
                        patID: '',
                        hisPatNo: '',
                        hisPatID: '',
                        mobile: '',
                        patValue: '',
                        patSexDesc: '',
                        medCardID: ''
                    })
                } else {
                    this.$cache.set('userData', {
                        ...userData,
                        idCardNo: newData.idCardNo || '',
                        imUserID: newData.imUserID || '',
                        patDesc: newData.patName || '',
                        patID: newData.patID || '',
                        hisPatNo: newData.hisPatNo || '',
                        hisPatID: newData.hisPatID || '',
                        mobile: newData.mobile || '',
                        patValue: newData.key || '',
                        patSexDesc: newData.patSexDesc || '',
                        medCardID: newData.medCardID || ''
                    });
                }
                // this.login("patient" + newData.hisPatID) // 登录TIM
                console.log("触发了this.triggerEvent")
            },

            onCloseBook() {
                this.setData({
                    showBook: false
                });
            },

            agree() {
                this.setData({
                    showButton: true
                }, () => {
                    this.onCloseBook();
                })
            },

            agree2() {
                this.setData({
                    showButton: this.showButton == false ? true : false
                })
            },
            showBookTap() {
                this.setData({
                    showBook: true
                });
            },
        }
    }
</script>

<style lang="scss">
    @use '../../common/style/card.scss' as *;
	
	.picker-content {
		text-align: right;
	}
</style>
