<!-- 自助机订单缴费 -->
<template>
    <nav-bar :navbar-data="navbarData"></nav-bar>
    <view :style="{ marginTop: height + 'px' }">
        <view class="title">
            <text>自助机订单缴费</text>
        </view>
        <view>
            <view class="table">
                <text>姓名：</text>
                <text style="float:right">{{ detailObj.patName }}</text>
            </view>
            <view class="table">
                <text>人员编号：</text>
                <text style="float:right">{{ detailObj.patNo }}</text>
            </view>
            <view class="table">
                <text>订单类型</text>
                <text style="float:right" v-if="detailObj.business == 'reg'">挂号缴费</text>
                <text style="float:right" v-if="detailObj.business == 'OUT'">门诊缴费</text>
                <text style="float:right" v-if="detailObj.business == 'IN'">预交金缴费</text>
            </view>
            <view class="table">
                <text>订单金额</text>
                <view style="float:right">
                    <text>￥</text>
                    <text style="color:rgba(250,84,28,1);">{{ detailObj.totalFee }}</text>
                </view>
            </view>
            <view class="table">
                <text>订单状态</text>
                <text style="float:right" v-if="payResultState == '0'">待缴费</text>
                <text style="float:right" v-if="payResultState == '1'">已付款</text>
                <text style="float:right" v-if="payResultState == '2'">已取消</text>
                <text style="float:right" v-if="payResultState == '3'">缴费失败</text>
            </view>
            <view class="table">
                <text>订单号</text>
                <text style="float:right">{{ detailObj.orderNo }}</text>
            </view>
        </view>
        <view class="table" style="float:center; text-align:center; padding-top:50px">
            <text style="float:center;" class="tipText" v-if="payResultState == '0'">请使用微信重新扫码缴费！如长时间停留请关闭WIFI后重新扫码！</text>
            <text style="float:center; color:'#00DB00'" class="tipText"
                v-if="payResultState == '1'">缴费成功，如需查询缴费记录可前往首页添加就诊人信息！</text>
            <text style="float:center" class="tipText" v-if="payResultState == '2'">缴费取消,可使用微信重新扫码缴费！</text>
            <text style="float:center; color:'#FF2D2D'" class="tipText"
                v-if="payResultState == '3'">缴费失败,请使用微信重新扫码缴费！</text>
            <text style="float:center; color:'#FF2D2D'" class="tipText"
                v-if="payResultState == '4'">订单超时,请使用微信重新扫码缴费！</text>
        </view>
    </view>
</template>

<script>
import $http from "./utils/https";
import Util from "@/utils/utils";
import { getHospList, switchHospital, dealSwitchHospital } from '@/utils/common.js';
const app = getApp();
let timerToPost = null;
let timer = null;
let timerNum = 0;
export default {
    data() {
        return {
            height: app.globalData.height,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: "自助机订单缴费"
            },
            detailObj: Object,
            payResultState: 0, //支付状态 0:待支付  1：支付成功 2：支付取消 3：支付异常  4:订单超时
            foreignTradeNum: '', //流水号
            platform: app.globalData.platform, // 平台
            provider: app.globalData.provider
        }
    },
    onLoad: function (options) {
        let self = this;
        try {
            uni.showLoading({
                title: '获取订单数据中',
                mask: true
            })
            timerToPost = setInterval(function () {
                // 支付宝独立处理
                // #ifdef MP-ALIPAY
                !options && (options = {})
                options['q'] = app.globalData.alipayQuery
                // #endif
                if (options && options.q) {
                    const parString = decodeURIComponent(options.q); // 获取到二维码原始链接内容
                    const parStringParms = parString.split("?")[1]
                    self.setData({
                        foreignTradeNum: parStringParms.split("^")[0]
                    })
                    self.getHospSelectData(parStringParms.split("^")[1])
                }
            }, 1000)
        } catch (error) {
            uni.showToast({
                title: '数据提取失败，请尝试重新扫码',
                icon: 'none',
            })
        }
        // 支付宝独立处理
        // #ifdef MP-ALIPAY
        uni.hideBackHome(); // 隐藏
        Util.resetGlobalDataParams(app,['alipayQuery'])
        // #endif
    },
    methods: {
        // 获取医院数据
        getHospSelectData: async function (hospCode) {
            let _this = this;
			uni.showLoading();
			await getHospList(app, hospCode)
				.then(res => {
					clearInterval(timerToPost)
					uni.hideLoading()
					setTimeout(() => {
					    _this.getPayParams();
					}, 300)
				})
				.catch(error => {})
		// 	let data = {
		// 		params: []
		// 	}
		// 	$http.post("urlS", self, {
		// 		code: "02010009",
		// 		data: data,
		// 		success: function (res) {
					
		// 			if (+res.errorCode === 0) {
		// 				if (res.result && res.result.length === 1) {
		// 					let hospOneData = res.result[0];
		// 					this.$cache.set('userData', {
		// 						...userData,
		// 						hospID: hospOneData.hospID,
		// 						hospDesc: hospOneData.hospDesc,
		// 						hisHospID: hospOneData.hisHospID,
		// 						hospAddress: hospOneData.hospAddress,
		// 						telephone: hospOneData.telephone,
		// 						menuMode: hospOneData.menuMode,
		// 						serviceCall: hospOneData.serviceCall,
		// 						serviceCallTips: hospOneData.serviceCallTips,
		// 						upLoadUrl: hospOneData.upLoadUrl,
		// 						downLoadUrl: hospOneData.downLoadUrl,
		// 					})
		// 					app.globalData.SDKAPPID = +hospOneData.imAppID;
		// 					app.globalData.SECRETKEY = hospOneData.imSecret;
		// 				} else if (res.result.length > 1) {
		// 					let isHosp = false;
		// 					let newHospData = {};
		// 					for (var i = 0; i < res.result.length; i++) {
		// 						if (res.result[i].hisHospID === options) {
		// 							isHosp = true;
		// 							newHospData = res.result[i];
		// 							break;
		// 						}
		// 					}
		// 					if (isHosp) {
		// 						this.$cache.set('userData', {
		// 							...userData,
		// 							hospID: newHospData.hospID,
		// 							hospDesc: newHospData.hospDesc,
		// 							hisHospID: newHospData.hisHospID,
		// 							hospAddress: newHospData.hospAddress,
		// 							telephone: newHospData.telephone,
		// 							menuMode: newHospData.menuMode,
		// 							serviceCall: newHospData.serviceCall,
		// 							serviceCallTips: newHospData.serviceCallTips,
		// 							upLoadUrl: newHospData.upLoadUrl,
		// 							downLoadUrl: newHospData.downLoadUrl,
		// 						})
		// 						app.globalData.SDKAPPID = +newHospData.imAppID;
		// 						app.globalData.SECRETKEY = newHospData.imSecret;
		// 					}
		// 				}
		// 				setTimeout(() => {
		// 					self.getPayParams();
		// 				}, 300)
		// 			}
		// 		},
		// 		error: function () {
		// 			uni.hideLoading();
		// 			uni.showToast({
		// 				title: '网络异常',
		// 				icon: 'none',
		// 				duration: 2000
		// 			})
		// 		}
		// 	});
		},

        //查询支付入参
        getPayParams: function () {
            uni.hideLoading();
            let self = this
            let data = {
                params: [{
                    payTradeNum: this.foreignTradeNum
                }]
            }
            $http.post("urlS", self, {
                code: "130992",
                data: data,
                namespace: "UPP",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        self.setData({
                            detailObj: res.result
                        })
                        if (+this.detailObj.totalFee !== 0) {
                            self.settlementPay(res.result)
                        } else {
                            //价格为0时不需要支付
                            this.sendReqPayState(res.result)
                        }
                    } else {
                        uni.showToast({
                            title: res.errorMessage,
                            icon: 'none',
                        })
                    }
                },
                error: function () {
                    uni.showToast({
                        title: '接口连接异常，请稍后重试。',
                        icon: 'none',
                    })
                }
            });
        },

        // 支付预结算
        settlementPay: Util.debounce(function (result) {
            const { platform, provider } = this
            let patData = {}
            const userCode = platform == "alipay" ? "alisf" : "ZZJSF"
            const payWayCode = platform == "alipay" ? "ALIPAY" : "WECHAT"
            if (result.business == 'reg') { //挂号/预约挂号
                patData = {
                    code: "03100041",
                    params: [{
                        resTimeID: result.resTimeID,
                        resDetailID: result.resDetailID,
                        hospCode: result.hospCode,
                        patID: result.patID,
                        patName: result.patName,
                        patNo: result.patNo,
                        userCode,
                        bookMethodID: "Y",
                        bookMethodID: "Win",
                        insuFlag: result.insuFlag,
                        orderNo: result.orderNo,
                        symptom: {},
                        paywStr: [{
                            payWayCode,
                            payWayID: "",
                            payWayAmt: result.payWayAmt,
                        }],
                    }],
                }
            } else if (result.business == 'OUT') { //门诊缴费
                patData = {
                    code: "99070009",
                    params: [{
                        prescribeTradeNum: result.prescribeTradeNum,
                        patAmt: result.patAmt,
                        orderAdmReasonID: result.orderAdmReasonID,
                        userCode,
                        hospCode: result.hospCode,
                        patientID: result.patID,
                        admID: result.admID,
                        payWayCode,
                        payWayAmt: result.payWayAmt,
                        orderInfo: ""
                    }]
                }
            } else if (result.business == 'IN') { //预交金
                patData = {
                    code: "99070016",
                    params: [{
                        patNumber: result.patNumber,
                        patAmt: result.patAmt,
                        remark: "",
                        userCode,
                        hospCode: result.hospCode,
                        patientID: result.patID,
                        admID: result.admID,
                        payWayCode,
                        payWayAmt: result.payWayAmt,
                        purPoseCode: result.purPoseCode,
                    }]
                }
            }
            let data = {
                params: [{
                    totalFee: result.totalFee,
                    ipAddress: "",
                    medicalcardid: result.medicalcardid,
                    payReasonID: result.payReasonID,
                    insuType: result.insuType,
                    body: result.body,
                    businessType: result.businessType,
                    patNo: result.patNo,
                    patName: result.patName,
                    idCardNo: result.idCardNo,
                    mobile: result.mobile,
                    foreignTradeNum: result.foreignTradeNum,
                    userCode,
                    insuFlag: result.insuFlag,
                    patID: result.patID,
                    prescribeTradeNum: result.prescribeTradeNum,
                    appointID: result.appointID,
                    data: patData
                }]
            }
            uni.showLoading({
                title: '结算中,请稍后',
                mask: true
            })
            $http.post("urlS", this, {
                code: "01050002",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.unifyPay(res.result)
                    } else {
                        setTimeout((
                            uni.showToast({
                                title: res.errorMessage,
                                icon: 'none',
                                duration: 2000
                            })
                        ), 300)
                    }
                },
                error(err) {
                    console.log(err)
                }
            })
        }),

        // 微信、支付宝支付调用
        unifyPay(data) {
            let self = this;
            return new Promise((resolve, reject) => {
                const { platform, provider } = self
                const obj = {}
                obj['provider'] = provider
                if (platform == 'alipay') {
                    obj['orderInfo'] = data.tradeNo
                } else if (platform == 'weixin') {
                    obj['orderInfo'] = {
                        timeStamp: data.timeStamp + "",
                        nonceStr: data.nonceStr,
                        package: data.package,
                        signType: data.signType,
                        paySign: data.paySign
                    }
                }
                uni.requestPayment({
                    ...obj,
                    success(res) {
                        //开始轮询查询订单结果
                        timer = setInterval(function () {
                            timerNum = timerNum + 1;
                            self.getPayStatus();
                        }, 1000)
                        resolve()
                    },
                    fail(err) {
                        uni.hideLoading();
                        uni.showToast({
                            title: "支付取消" + JSON.stringify(err),
                            icon: 'none',
                            duration: 2000
                        })
                        self.setData({
                            payResultState: 2
                        })
                        reject(err)
                    }
                })
            })
        },

        //不需要调用支付-0元挂号
        sendReqPayState: function (result) {
            let self = this
            const { platform } = app.globalData
            let data = {
                params: [{
                    resTimeID: result.resTimeID,
                    resDetailID: result.resDetailID,
                    hospCode: result.hospCode,
                    patID: result.patID,
                    patientId: result.patID,
                    patName: result.patName,
                    patNo: result.patNo,
                    userCode: platform == 'alipay' ? "alisf" : "ZZJSF",
                    bookMethodID: "Y",
                    bookMethodID: "Win",
                    insuFlag: result.insuFlag,
                    orderNo: result.orderNo,
                    symptom: {
                        illnessTime: "",
                        symptom: "",
                        imageAddress: "",
                        appointID: result.appointID,
                    },
                    paywStr: [{
                        payWayCode: platform == 'alipay' ? "ALIPAY" : "WECHAT",
                        payWayID: "",
                        payWayAmt: result.payWayAmt,
                    }]
                }]
            }
            $http.post("urlS", this, {
                code: "03100041",
                data: data,
                namespace: "Y",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        //开始轮询查询订单结果
                        timer = setInterval(function () {
                            timerNum = timerNum + 1;
                            self.getPayStatus();
                        }, 1000)
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: "支付异常取消" + JSON.stringify(res),
                            icon: 'none',
                            duration: 2000
                        })
                        self.setData({
                            payResultState: 2
                        })
                    }
                }
            });
        },

        //轮询查询
        getPayStatus: function () {
            let self = this
            let data = {
                params: [{
                    foreignTradeNum: this.foreignTradeNum
                }]
            }
            $http.post("urlS", this, {
                code: "130993",
                data: data,
                namespace: "UPP",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        // statusFlag | 状态标志：Y （已产生支付），N（未产生支付） |
                        // status | 收费状态：N 正常，T 退款，TP，预结算，TR 退款 ，UN 异常(交易记录确认完成，his结果状态未明)
                        if (res.result && res.result.statusFlag == 'Y') {
                            if (res.result && res.result.status == 'N') {
                                uni.showToast({
                                    title: "缴费成功",
                                    icon: 'none',
                                    duration: 2000
                                })
                                timerNum = 0;
                                clearInterval(timer)
                                self.setData({
                                    payResultState: 1
                                })
                                uni.hideLoading();
                            } else if (res.result && res.result.status == 'UN') {
                                uni.showToast({
                                    title: "缴费失败",
                                    icon: 'none',
                                    duration: 2000
                                })
                                timerNum = 0;
                                clearInterval(timer)
                                self.setData({
                                    payResultState: 3
                                })
                                uni.hideLoading();
                            }
                        }
                    } else {
                        setTimeout((
                            uni.showToast({
                                title: res.errorMessage,
                                icon: 'none',
                                duration: 2000
                            })
                        ), 300)
                    }
                }
            });

            if (timerNum == 60) {
                uni.hideLoading();
                timerNum = 0;
                clearInterval(timer)
                self.setData({
                    payResultState: 4
                })
            }
        },
    }
}
</script>

<style>
.title {
    padding: 23rpx 0 23rpx 49rpx
}

.table {
    background: rgba(255, 255, 255, 1);
    margin-top: 1rpx;
    padding: 20rpx 23rpx 20rpx 23rpx;
}

text {
    font-size: 32rpx;
    font-family: PingFang SC;
    color: rgba(102, 102, 102, 1);
}

.card {
    background: rgba(255, 255, 255, 1);
    margin-top: 10rpx;
}

.bottom_line {
    width: 750rpx;
    height: 1rpx;
    background: rgba(245, 244, 244, 1);
}



.van-icon__image {
    width: 120rpx !important;
    height: 120rpx !important;
    border-radius: 50% !important;
    margin: 38rpx 0 0 34rpx !important;
}

.card_introduce_name {
    font-size: 36rpx;
    font-family: PingFang SC;
    color: rgba(51, 51, 51, 1);
}

.card_introduce_text {
    margin-left: 1.5rpx;
    margin-top: 24rpx;
}

.card_introduce_title {
    font-size: 32rpx;
    font-family: PingFang SC;
    color: rgba(102, 102, 102, 1);
    margin-left: 14rpx;
}

.card_introduce_locDesc {
    font-size: 32rpx;
    font-family: PingFang SC;
    color: rgba(102, 102, 102, 1);
    margin-left: 17rpx;
}

/* pages/index//pages/doctorInfo/doctorInfo.wxss */
.itdc-head {
    max-height: 390rpx;
    padding: 10rpx 24rpx 0 24rpx;
    position: relative;
    margin-bottom: 10rpx;
}

.itdc-head-bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 168rpx;
    z-index: -1;
}

.itdc-head-content {
    /* max-height: 380rpx; */
    background: #fff;
    overflow: hidden;
    border-radius: 10rpx;
}

.itdc-head-content-top {
    width: 100%;
    padding: 32rpx;
    padding-bottom: 24rpx;
    box-sizing: border-box;
}

.itdc-head-portrait {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    margin-right: 24rpx;
}

.itdc-head-content-top-text {
    font-size: 28rpx;
    color: #666;
}

.itdc-head-content-top-text text:nth-child(1) {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
}

.itdc-head-content-top-text text:nth-child(2) {
    margin: 0 16rpx;
}

.itdc-head-content-top .van-rate {
    border-radius: 10rpx;
    width: 240rpx;
    height: 40rpx;
    margin: 16rpx 0;
    line-height: 40rpx;
    background: #feeee8;
    display: flex;
    justify-content: space-between;
    padding: 0 12rpx;
    padding-bottom: 4rpx;
    align-items: center;
    box-sizing: border-box;
}

.choose-doctor-content {
    width: 100%;
    padding: 0 24rpx;
    margin-bottom: 10rpx;
    box-sizing: border-box;
}

.doctor-list-introduce {
    width: 100%;
    padding: 16rpx 29rpx 16rpx 25rpx;
    box-sizing: border-box;
}

.doctor-list-introduce text {
    width: 100%;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    color: #666;
    line-height: 48rpx;
    text-indent: 2em;
    font-size: 28rpx;
    word-wrap: break-word;
}

.after-text-css {
    -webkit-line-clamp: 0 !important;
    display: block !important;
}

.choose-doctor-date {
    background: #fff;
    width: 100%;
    box-sizing: border-box;
    border-radius: 10rpx;
}

.cdt-header {
    text-align: center;
    height: 56rpx;
    line-height: 56rpx;
    font-size: 28rpx;
    color: #666;
}

.choose-doctor-tabs-header {
    display: flex;
    width: 100%;
    padding: 24rpx 0;
    box-sizing: border-box;
    justify-content: space-around;
}

.choose-doctor-tabs-header-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 80rpx;
    height: 136rpx;
    color: #666;
    font-size: 28rpx;
    font-weight: bold;
    align-items: center;
}

.active-tabs {
    background: #1890FF;
    color: #fff;
}

.cdthc-title {
    color: #333;
    font-size: 32rpx;
    font-weight: 600;
    margin: 6rpx 0;
}

.cdthc-number {
    color: #1890FF;
}

.cdthc-no-number {
    color: #ccc
}

.active-tabs .cdthc-title,
.active-tabs .cdthc-number,
.active-tabs .cdthc-no-number {
    color: #fff;
}

.choose-doctor-date-content-top {
    width: 100%;
    padding: 0 24rpx;
    box-sizing: border-box;
}

.choose-doctor-date-content-content {
    width: 100%;
    padding: 32rpx 0;
    display: flex;
    box-sizing: border-box;
}

.choose-doctor-date-content-top-text {
    font-size: 28rpx;
    color: #666;
}

.choose-doctor-date-content-top-text .turn-title {
    font-size: 32rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 4rpx;
}

.choose-doctor-date-content-top .image-css {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
}

.choose-doctor-date-content-bottom {
    width: 100%;
    padding: 0 24rpx;
    box-sizing: border-box;
    height: 110rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.choose-doctor-date-content-bottom-left {
    color: #666;
    font-size: 28rpx
}

.choose-doctor-date-content-bottom-left text {
    color: #13C2C2;
}

.choose-doctor-date-content-bottom-right {
    display: flex;
    align-items: center;
}

.choose-doctor-date-content-bottom-right-price {
    margin-right: 16rpx;
    color: #FA541C;
    font-size: 32rpx;
}

.choose-doctor-date-content-bottom-right-price .price-ico {
    color: #999;
    font-size: 28rpx
}

.choose-doctor-date-content-bottom-right-btn .van-button {
    min-width: 160rpx;
    height: 60rpx;
    text-align: center;
    line-height: 60rpx;
}

.choose-doctor-evaluate-title {
    height: 100rpx;
    font-size: 32rpx;
    color: #333;
    font-weight: 600;
    line-height: 100rpx;
    padding: 0 24rpx;
    box-sizing: border-box;
}

.choose-doctor-evaluate-content {
    display: flex;
    background: #fff;
    border-radius: 10rpx;
    min-height: 117rpx;
    padding: 24rpx 0;
    width: 100%;
    box-sizing: border-box;
}

.choose-doctor-evaluate-content view {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    color: #666;
}

.choose-doctor-evaluate-content view:nth-child(1) {
    border-right: 1px solid #F5F4F4;
}

.choose-doctor-evaluate-content view text {
    font-size: 36rpx;
    color: #FA541C;
    margin-bottom: 4rpx;
}

.choose-doctor-evaluation-content {
    min-height: 230rpx;
    margin-top: 4rpx;
    border-radius: 10rpx;
    background: #fff;
}

.choose-doctor-evaluation-content:last-child {
    margin-bottom: 0;
}

.choose-doctor-evaluation-content-header {
    height: 92rpx;
    display: flex;
    padding: 0 24rpx;
    box-sizing: border-box;
    justify-content: space-between;
    align-items: center;
    color: #999;
    font-size: 28rpx;
}

.choose-doctor-evaluation-content-header-left text {
    font-size: 32rpx;
    color: #333;
    font-weight: 600;
    margin-right: 14rpx;
}

.choose-doctor-evaluation-content-text {
    width: 100%;
    padding: 24rpx 24rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    color: #999;
}

.choose-doctor-evaluation-content-text view:nth-child(1) {
    margin-bottom: 8px;
}

.choose-doctor-evaluation-content-text text {
    color: #333;
}

.logistics_view-head {
    height: 98rpx;
    line-height: 98rpx;
    width: 100%;
    text-align: center;
    color: #333;
    font-size: 32rpx;
}

.consulTime {
    height: 72rpx;
    line-height: 72rpx;
    padding-left: 24rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #666;
    background: #FAF9F9;
    box-sizing: border-box;
}

.consul-list {
    width: 100%;
    padding: 24rpx;
    padding-bottom: 0;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
}

.consul-list-item {
    width: 31%;
    margin-right: 3.5%
}

.consul-list-item-child {
    border: 1px solid #E1E1E1;
    border-radius: 10rpx;
    height: 94rpx;
    text-align: center;
    margin-bottom: 24rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #666;
    font-size: 28rpx;
}

.consul-list-item:nth-child(3n) {
    margin-right: 0;
}

.timeCroCheck {
    background: #1890FF;
    color: #fff;
}

.btn-box {
    margin-top: 100rpx;
    padding: 0 24rpx;
}

.button {
    width: 100%;
}

.tipText {
    font-size: 18px;
}
</style>