<template>
    <!--
    * Creater:     shizi
    * CreateDate:  2022/10/19
    * Describe：   视光预交金充值 - pages/order/pages/oPrepaymentRecharge/index.js
    * */
    -->
    <nav-bar :navbar-data="navbarData" />
    <view class="o-prepayment-recharge"
        :style="{ paddingTop: height + 'px', paddingBottom: '20rpx', height: '100vh', boxSizing: 'border-box' }">
        <van-cell-group>
            <van-cell title="患者姓名" :value="payData.patName || '--'" />
            <van-cell title="就诊机构" :value="payData.hospDesc || '--'" />
            <van-cell title="预缴金额（元）" value-class="opr-amt" :value="payData.patAmt || '--'" />
            <van-cell title="用途" :value="payData.purPoseDesc || '--'" />
        </van-cell-group>
        <view :style="{ marginTop: '48rpx' }">
            <van-button custom-class="btn-pay" type="info" block @tap="handleConfirmPayment">确认支付</van-button>
        </view>
    </view>
</template>

<script>
import $http from "@/utils/https";
import Util from "@/utils/utils";
import { getHospList, switchHospital, dealSwitchHospital } from '@/utils/common.js';
import httpConfig from '@/utils/httpConfig';
import NavBar from '@/components/navBar/index';
import VanButton from '@/components/button/index';
import VanCellGroup from '@/components/cell-group/index';
import VanCell from '@/components/cell/index';
const app = getApp();
export default {
    components: {
        'nav-bar': NavBar,
        'van-button': VanButton,
        'van-cell-group': VanCellGroup,
        'van-cell': VanCell,
    },
    data() {
        return {
            imgHost: httpConfig && httpConfig.imgHost,
            height: app.globalData.height,
            navbarData: {
                isGoHome: true,
                homePath: '../../../../pages/tabBar/index/index',
                isGoBack: true,
                title: '缴预交金'
            },
            payData: {},
            patAmt: '', // 充值金额
            processID: '', // 进程ID
            platform: app.globalData.platform, // 当前渠道
        }
    },
    onLoad(options) {
        try {
            let userData = this.$cache.get('userData');
            // 支付宝独立处理
            // #ifdef MP-ALIPAY
            !options && (options = {})
            options['q'] = app.globalData.alipayQuery
            // #endif
            // console.log(options)
            // options['q'] = '/deposit/144^.1^H02'
            if (options && options.q) {
                // let arr = optionsParams = decodeURIComponent(options.q).split('/');
                // let optionsParams = arr[arr.length - 1];
                let optionsQ = decodeURIComponent(options.q);
                let optionsParams = optionsQ && optionsQ.indexOf('/') > -1 ? optionsQ.split('/')[optionsQ.split('/').length - 1] : optionsQ;
                let strSplit = optionsParams && optionsParams.indexOf('^') > -1 ? optionsParams.split('^') : [];
                let paramsObj = {
                    processID: strSplit && strSplit.length > 0 ? strSplit[0] : '',
                    patAmt: strSplit && strSplit.length > 1 ? strSplit[1] : '',
                    hospCode: strSplit && strSplit.length > 2 ? strSplit[2] : ''
                };
                // console.log('paramsObj', paramsObj)
                this.handleInit(paramsObj);
            } else {
                const eventChannel = this.getOpenerEventChannel()
                eventChannel.on('oPrepaymentRecharge', (data) => {
                    data.hospDesc = (userData && userData.hospDesc) || '';
                    this.setData({ payData, patAmt: (data && data.patAmt) || '' });
                })
            }
            // 支付宝独立处理
            // #ifdef MP-ALIPAY
            uni.hideBackHome(); // 隐藏
            Util.resetGlobalDataParams(app, ['alipayQuery'])
            // #endif
        } catch (error) {
            console.log(error)
        }
    },
    methods: {
        // 获取初始化数据
        handleInit(paramsObj) {
            let userData = this.$cache.get('userData');
            if (!(userData && userData.hisHospID) || (paramsObj && paramsObj.hospCode)) {
                // console.log('获取医院数据')
                // 获取医院数据
				this.setData({
				    processID: (paramsObj && paramsObj.processID) || '',
				    patAmt: (paramsObj && paramsObj.patAmt) || ''
				}, () => {
				    this.getHospSelectData(paramsObj.hospCode);
				});
            } else {
                this.setData({ 
					processID: (paramsObj && paramsObj.processID) || '', 
					patAmt: (paramsObj && paramsObj.patAmt) || '' ,
				}, () => {
                    this.getPayData();
                });
            }
        },

        // 获取支付数据
        getPayData() {
            let { processID, patAmt } = this;
            let userData = this.$cache.get('userData');
            if (processID && patAmt) {
                let data = {
                    params: [{
                        processID,
                        patAmt
                    }]
                }
                $http.post('urlS', this, {
                    code: '17030072',
                    data,
                    namespace: 'Y',
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            let payData = (res && res.result) || {};
                            payData.hospDesc = (userData && userData.hospDesc) || '';
                            payData.patAmt = (payData && payData.payData) || patAmt;
                            this.setData({ payData });
                        } else {
                            uni.showToast({
                                title: res.errorMessage,
                                icon: 'none',
                                duration: 2000
                            });
                        }
                    }
                })
            } else {
                uni.showToast({
                    title: '调用接口异常，requestID/patAmt不能为空！',
                    icon: 'none',
                    duration: 2000
                })
            }
        },

        // 获取医院数据
        getHospSelectData: async function (hospCode) {
            const _this = this
            let userData = _this.$cache.get('userData');
            if (!(userData && userData.openID)) {
                let count = _this.count ? _this.count : 1;
                if (count > 10) {
                    return;
                }
                setTimeout(() => {
                    _this.getHospSelectData(hospCode);
                }, 300)
                _this.count++
                return;
            }
			uni.showLoading();
			await getHospList(app, hospCode)
				.then(res => {
					clearInterval(timerToPost)
					uni.hideLoading()
					setTimeout(() => {
					    _this.getPayData();
					}, 300)
					
				})
				.catch(error => {})
			
			
            // let data = {
            //     params: []
            // }
            // $http.post('urlS', this, {
            //     code: '02010009',
            //     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.hospCode) {
            //                         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;
            //                 }
            //             }
            //             this.setData({
            //                 processID: (options && options.processID) || '',
            //                 patAmt: (options && options.patAmt) || ''
            //             }, () => {
            //                 setTimeout(() => {
            //                     self.getPayData();
            //                 }, 300)
            //             });
            //         }
            //     }
            // });
        },

        // 确认支付
        handleConfirmPayment: Util.debounce(function (code) {
            const self = this
            let userData = this.$cache.get('userData');
            let {
                payData,
                platform
            } = self
            const userCode = platform == "alipay" ? "alisf" : "wxsf"
            const payWayCode = platform == "alipay" ? "ALIPAY" : "WECHAT"
            const businessType = platform == "alipay" ? "OPAliPAY" : "OPPAY"
            let collbackParams = {
                code: '99070016',
                params: [{
                    patNumber: payData?.patNo || userData?.hisPatNo,
                    patAmt: payData?.patAmt || '',
                    remark: '',
                    userCode: userCode,
                    hospCode: userData.hisHospID || '',
                    patientID: payData?.patNo || userData?.hisPatNo,
                    // admID: payData?.admID || '',
                    payWayCode: payWayCode,
                    payWayAmt: payData?.patAmt || '',
                    purPoseCode: payData?.purPoseCode || '',
                    saveObjID: payData?.saveObjID || ''
                }]
            }
            let data = {
                params: [{
                    totalFee: payData?.patAmt || '',
                    ipAddress: '',
                    medicalcardid: '',
                    payReasonID: '',
                    insuType: '',
                    body: '',
                    businessType: businessType,
                    patNo: payData?.patNo || userData?.hisPatNo,
                    patName: payData?.patName || userData?.patDesc,
                    idCardNo: payData?.patIDCardNo || userData.idCardNo,
                    mobile: payData?.patMobile || userData.mobile,
                    data: collbackParams,
                    saveObjID: payData?.saveObjID || ''
                }]
            }
            uni.showLoading({
                title: '结算中,请稍后',
                mask: true
            })
            $http.post('urlS', self, {
                code: '01050002',
                data,
                success: function (res) {
                    uni.hideLoading();
                    if (+res.errorCode === 0) {
                        self.pay(res.result)
                    } else {
                        setTimeout((
                            uni.showToast({
                                title: res.errorMessage,
                                icon: 'none',
                                duration: 2000
                            })
                        ), 300)
                    }
                }
            });
        }),

        // 微信支付调用
        pay(data) {
            let self = this;
            const obj = {}
            const { platform } = app.globalData
            obj['provider'] = app.globalData.provider
            if (platform == 'alipay') {
                obj['orderInfo'] = data.trandNo
            } else if (platform == 'weixin') {
                obj['orderInfo'] = {
                    timeStamp: data.timeStamp + '',
                    nonceStr: data.nonceStr,
                    package: data.package,
                    signType: data.signType,
                    paySign: data.paySign
                }
            }
            // console.log(obj)
            uni.requestPayment({
                ...obj,
                success(res) {
                    if (res.resultCode == '9000') {
                        uni.showToast({
                            title: '支付成功'
                        })
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '../prepaymentRechargeSuccessful/prepaymentRechargeSuccessful?amt=' + self.patAmt,
                            })
                        }, 2000)
                    } else {
                        uni.showToast({
                            title: res.memo
                        })
                    }
                },
                fail(res) { }
            })
        },
    }
}
</script>


<style>
.o-prepayment-recharge {
    height: 100%;
    padding: 12rpx 24rpx;
    box-sizing: border-box;
}

.van-cell__value.opr-amt {
    color: #fa8c17;
}

.btn-pay {
    height: 80rpx;
    font-size: 32rpx;
}
</style>