<template>
    <view class="page">
        <view class="sign-in">
            <form bindsubmit="formSubmit">
                <view class="sign-in-form">
                    <view class="from-item">
                        <label class="label" for="cardCode">
                            <text class="star">*</text>
                            <text class="t">切换就诊人</text>
                        </label>
                        <view class="item flex">
                            <view class="item-value">
                                <view class="patient-box" bindtap="handleChangePat">
                                    <text>{{ userData.patDesc }}</text>
                                    <uni-icons type="bottom" size="16px" color="#909090" />
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="from-item">
                        <label class="label" for="cardCode">
                            <text class="star">*</text>
                            <text class="t">就诊卡号</text>
                        </label>
                        <view class="item flex">
                            <view class="item-value">
                                <input name="cardCode" type="number" placeholder="请输入" placeholder-class="placeholder"
                                    :value="cardCode" />
                            </view>
                            <view class="item-icon" @tap="onScan">
                                <image :src="imgHost + '/images/icon/user/scan@2x.png'" mode="" />
                            </view>
                        </view>
                        <view class="tips">
                            <text class="tip-text">{{ errors[0] ? errors[0] : '' }}</text>
                            <view class="tip-dialog c-blue" data-type="scan" bindtap="onCaseClose">扫描示例</view>
                        </view>
                    </view>
                    <view class="from-item">
                        <label class="label" for="name">
                            <text class="star">*</text>
                            <text class="t">姓名</text>
                        </label>
                        <view class="item">
                            <view class="item-value">
                                <input name="name" type="text" placeholder="请输入" placeholder-class="placeholder"
                                    :value="name" />
                            </view>
                        </view>
                        <view class="tips">
                            <text class="tip-text">{{ errors[1] ? errors[1] : '' }}</text>
                        </view>
                    </view>
                    <view class="from-item">
                        <label class="label" for="code">
                            <text class="star">*</text>
                            <text class="t">身份证号</text>
                        </label>
                        <view class="item">
                            <view class="item-value">
                                <input name="code" type="idcard" placeholder="请输入" placeholder-class="placeholder"
                                    :value="code" />
                            </view>
                        </view>
                        <view class="tips">
                            <text class="tip-text">{{ errors[2] ? errors[2] : '' }}</text>
                        </view>
                    </view>

                    <view class="from-item">
                        <label class="label" for="phone">
                            <text class="star">*</text>
                            <view class="t">
                                <text>电话</text>
                                <uni-icons type="help" size="14px" color="#c0c0c0" data-type="phone" @click="onCaseClose" />
                            </view>
                        </label>
                        <view class="item">
                            <view class="item-value">
                                <input name="phone" type="number" maxlength="11" placeholder="请输入"
                                    placeholder-class="placeholder" @change="phoneChange" />
                            </view>
                        </view>
                        <view class="tips">
                            <text class="tip-text">{{ errors[3] ? errors[3] : '' }}</text>
                        </view>
                    </view>
                    <view class="from-item">
                        <label class="label" for="sendCode">
                            <text class="star">*</text>
                            <text class="t">验证码</text>
                        </label>
                        <view class="item">
                            <view class="item-value flex">
                                <input name="sendCode" type="text" maxlength="6" placeholder="请输入"
                                    placeholder-class="placeholder" />
                                <button class="btn-code" :disabled="isSendCodeBtnDisable" @tap="sendCode">{{
                                    isSendCodeBtnDisable ? '(' + sendCodeCount + 's)' : '' }}{{ sendCodeText }}</button>
                            </view>
                        </view>
                        <view class="tips">
                            <text class="tip-text">{{ errors[4] ? errors[4] : '' }}</text>
                        </view>
                    </view>
                </view>
                <view class="btn-area">
                    <button class="btn-primary" formType="submit">加入会员</button>
                </view>
            </form>
        </view>
    </view>
    <van-popup show="{{ showCase }}" custom-style="height: {{ dialogType == 'scan' ? '60%' : '30%' }};">
        <view class="scan-area" wx:if="{{ dialogType == 'scan' }}">
            <view class="title">扫码示例</view>
            <view class="scan-tips-desc">
                <image src="{{ imgHost }}/images/icon/user/scan-dialog@2x.png" mode="" />
            </view>
            <view class="sub-title">请扫描挂号凭证上的条形码</view>
        </view>
        <view class="scan-area" wx:else>
            <view class="title">温馨提示</view>
            <view class="scan-tips-desc">请输入注册建档时使用的手机号码</view>
        </view>
        <view class="close" bindtap="onCaseClose">
            <van-icon name="close" size="27px" color="#fff" />
        </view>
    </van-popup>
    <hosp_pat_select id="hosp_pat_select" bind:handleReRender="updatePatInfo"></hosp_pat_select>
    <van-toast id="van-toast" />
</template>

<script>
const app = getApp();
export default {
    data() {
        return {
            imgHost: httpConfig && httpConfig.imgHost,
            showCase: false,
            dialogType: null, // 弹窗类型
            sendCodeCount: 60,
            sendCodeTimer: null,
            isSendCodeBtnDisable: false,
            sendCodeText: '获取验证码',
            errors: [],
            name: null, // 患者姓名
            cardCode: null, // 就诊卡号
            code: '500225198710113839', // 身份证号
        }
    },
    onLoad(options) {
        if (options.hasOwnProperty('cardCode') && options.cardCode) {
            this.setData({
                cardCode: options.cardCode
            })
        }
        if (options.hasOwnProperty('name') && options.name) {
            this.setData({
                name: options.name
            })
        }
        this.updateUserData()
    },
    methods: {
        // 更新UserData
        updateUserData() {
            return new Promise((resolve, reject) => {
                const userData = this.$cache.get('userData')
                if (userData) {
                    this.setData({
                        userData
                    })
                    resolve(userData)
                }
            })
        },

        // 切换就诊人后更新就诊人信息
        updatePatInfo() {
            this.updateUserData().then((userData) => {
                this.setData({
                    cardCode: userData.hisPatNo,
                    name: userData.patDesc,
                    code: userData.idCardNo
                })
            })
        },

        formSubmit(e) {
            console.log(e)
            this.setData({
                ...e.detail.value
            })
            const {
                errors,
                name,
                code,
                cardCode,
                phone,
                sendCode
            } = this.data
            errors[0] = !cardCode ? '请输入就诊卡号' : null
            errors[1] = !name ? '请输入姓名' : null
            errors[2] = !code ? '请输入身份证号' : null
            errors[3] = !phone ? '请输入正确的手机号' : null
            // errors[4] = !sendCode ? '请输入验证号' : null
            this.setData({
                errors
            })
            let bol = false
            for (let i = 0; i < errors.length; i++) {
                console.log(errors[i])
                if (errors[i] != null) bol = true
            }
            console.log(bol)
            if (bol) return
            this.idCardDetail()
            // this.verificationData()
            this.submitData()
        },

        // 手机号查询会员ID
        phoneQueryIntengralUserId(phone) {
            const self = this
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{
                        phone: phone || self.data.phone
                    }]
                }
                $http.post("urlS", self, {
                    code: "WX01031",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0 && res.result.yunxi_member_id) {
                            resolve(res.result)
                        } else if (res.errorCode === 10002) {
                            reject()
                        } else {
                            Toast(res.errorMessage)
                        }
                    }
                })
            })
        },

        // 提交数据到后台
        submitData() {
            let userData = this.$cache.get('userData');
            const {
                cardCode,
                name,
                phone,
                genderVal
            } = this.data
            let data = {
                params: [{
                    mobile: phone,
                    hospatiCode: userData.hisHospID,
                    name: name,
                    sex: genderVal.value,
                    channal: '小程序',
                    pat_no: cardCode
                }]
            }
            $http.post("urlS", this, {
                code: "WX01005",
                data: data,
                success: function (res) {
                    console.log(res)
                    if (+res.errorCode === 0) {
                        userData['integralUserId'] = res.result
                        this.$cache.set('userData', userData)
                        setTimeout(function () {
                            wx.navigateBack()
                        }, 500)
                    } else {
                        Toast.fail(res.errorMessage);
                    }
                }
            });
        },

        // 查询就诊人信息
        getPatInfo() {
            let data = {
                params: [{
                    userId: userData.userId, // 积分会员ID
                }]
            }
            $http.post("urlS", this, {
                code: "",
                data: data,
                namespace: 'Y',
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setData({
                            integralDetail: res.result
                        });
                    }
                }
            });
        },

        phoneChange(e) {
            if (e.detail.value.length == 11) {
                this.phoneQueryIntengralUserId(e.detail.value).then(res => {
                    Toast('当前手机号已注册过会员，请重新输入')
                }).catch((err) => {
                    this.setData({
                        phone: e.detail.value
                    })
                })
            }
        },

        // 更换就诊人
        handleChangePat() {
            const {
                userData
            } = this
            if (userData && userData.hisPatID) {
                var hosp_pat_select = this.selectComponent("#hosp_pat_select");
                hosp_pat_select.handleShowPatModal(); //子组件的方法
            }
        },

        // 发送验证码
        sendCode: Util.debounce(function (e) {
            const self = this
            const userData = this.$cache.get('userData');
            let {
                sendCodeCount,
                sendCodeTimer,
                isSendCodeBtnDisable,
                phone
            } = self
            const tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
            if (!phone) {
                Toast('请输入手正确的机号')
                return
            } else if (!tel.test(phone)) {
                Toast('请输入正确的手机号')
                return
            } else if (phone != userData.mobile) {
                Toast('请输入绑卡时的手机号')
                return
            }
            if (!isSendCodeBtnDisable) {
                let data = {
                    params: [{
                        mobile: self.phone
                    }]
                }
                $http.post("urlS", self, {
                    code: "01020014",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            self.setData({
                                sendCodeCount: sendCodeCount--,
                                isSendCodeBtnDisable: true,
                                sendCodeText: '后再次发送'
                            })
                            sendCodeTimer = setInterval(() => {
                                if (sendCodeCount == 0) {
                                    clearInterval(self.sendCodeTimer)
                                    self.setData({
                                        isSendCodeBtnDisable: false,
                                        sendCodeCount: 5,
                                        sendCodeText: '点击再次发送'
                                    })
                                    return
                                }
                                self.setData({
                                    sendCodeCount: sendCodeCount--
                                })
                            }, 1000)
                            self.setData({
                                sendCodeTimer
                            })
                        } else {
                            Util.showToast(res.errorMessage)
                        }
                    }
                })
            }
        }),

        /**验证验证码 */
        verificationData: function () {
            let {
                phone,
                sendCode
            } = this;
            let data = {
                params: [{
                    mobile: phone,
                    verifyCode: sendCode
                }]
            }
            console.log(data)
            $http.post("urlS", this, {
                code: "01020015",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.submitData() // 提交数据到后台
                    } else {
                        Toast(res.errorMessage);
                    }
                }
            });
        },

        /**根据身份证获取生日性别 */
        idCardDetail: function () {
            let id = this.code
            let sex
            if (parseInt(id.substr(16, 1)) % 2 == 1) {
                sex = {
                    label: '男',
                    value: '1',
                    text: '男'
                }
            } else {
                sex = {
                    label: '女',
                    value: '2',
                    text: '女'
                }
            }
            this.setData({
                genderVal: sex
            })
        },

        // 扫码
        onScan() {
            const self = this
            uni.scanCode({
                scanType: ['barCode', 'qrCode'],
                success(res) {
                    console.log(res)
                    if (res && res.result) {
                        self.setData({
                            cardCode: res.result
                        })
                    }
                }
            })
        },

        // 扫码提示案例弹窗
        onCaseClose(e) {
            this.setData({
                showCase: !this.showCase,
                dialogType: e.currentTarget.dataset.type
            })
        }
    }
}
</script>