<template>
    <nav-bar :navbar-data="navbarData"></nav-bar>
    <view :style="{ marginTop: height +'px', height: 'calc(100vh - '+ height +'px)', overflow: 'hidden' }" class="prepayment-and-recharge">
        <van-cell-group>
            <van-cell title="充值用途 " :value="purPoseObj.accpurPoseDesc" />
            <van-cell title="关联就诊"
                :value="admObj && admObj.admLocDesc ? admObj.admLocDesc : '' + '  ' + admObj && admObj.admDocDesc ? admObj.admDocDesc : '' + '   ' + admObj && admObj.admDateTime ? admObj.admDateTime : ''"
                :border="false" v-if="admObj && admObj.admLocDesc" />
        </van-cell-group>
        <view style="margin-top: 12rpx;" class="par-cell-group">
            <van-cell-group>
                <van-cell class="par-last-cell" title="充值金额" />
                <view class="row">
                    <input class="par-input" :value="rechargeAmount" type="digit" label="￥" placeholder="请输入充值金额" @input="onChange" />
                    <van-button  custom-class="par-btn" type="primary" size="small" block @tap="becomeStronger">充值</van-button>
                </view>
            </van-cell-group>
        </view>
    </view>
</template>

<script>
import NavBar from '@/components/navBar/index.vue'
import VanButton from '@/components/button/index'
import VanCell from '@/components/cell/index'
import VanCellGroup from '@/components/cell-group/index'
import Util from "@/utils/utils";
import $http from "@/utils/https";
import httpConfig from '@/utils/httpConfig';
const app = getApp();

export default {
    components: {
        'nav-bar': NavBar,
        'van-cell-group': VanCellGroup,
        'van-cell': VanCell,
        'van-button': VanButton
    },
    data() {
        return {
            userData: this.$cache.get('userData'),
            height: app.globalData.height,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: "缴预交金"
            },
            rechargePurpose: {}, // 充值用途
            medicalRecords: {}, // 就诊记录
            rechargeAmount: "",
            admObj: {},
            purPoseObj: {},
            platform: app.globalData.platform,
            provider: app.globalData.provider
        }
    },
    onLoad: function (options) {
        let _tihs = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('selectAVisit', function (data) {
            _tihs.setData({
                admObj: data.admObj,
                purPoseObj: data.purPoseObj
            }, () => {
                console.log("admObj", _tihs.purPoseObj)
            });
        })
    },
    methods: {
        onChange(event) {
            this.setData({
                rechargeAmount: event.detail.value
            })
        },

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

        ////微信支付调用
        wechatPay(data) {
            let _this = this;
            wx.requestPayment({
                timeStamp: data.timeStamp + "",
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.signType,
                paySign: data.paySign,
                success(res) {
                    uni.navigateTo({
                        url: '../prepaymentRechargeSuccessful/prepaymentRechargeSuccessful?amt=' + _this.rechargeAmount,
                    })
                },
                fail(res) { }
            })
        },

        // 微信、支付宝支付调用
        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.trade_no
                } else if (platform == 'weixin') {
                    obj['orderInfo'] = {
                        timeStamp: data.timeStamp + "",
                        nonceStr: data.nonceStr,
                        package: data.package,
                        signType: data.signType,
                        paySign: data.paySign
                    }
                }
                self.paySubmitService(data, obj).then(res => {
                    uni.navigateTo({
                        url: '../prepaymentRechargeSuccessful/prepaymentRechargeSuccessful?amt=' + _this.rechargeAmount,
                    })
                    resolve()
                }).catch(err => {
                    reject(err)
                })
            })
        },

        paySubmitService(data, obj) {
            const self = this
            return new Promise((resolve, reject) => {
                uni.requestPayment({
                    ...obj,
                    success(res) {
                        console.log('pay success', res)
                        if (obj.provider == 'wxpay') {
                            self.getPayStatus("wechatPay");
                        } else if (obj.provider == 'alipay') {
                            console.log(obj.provider, res.resultCode)
                            if (res.resultCode == '9000') {
                                // self.getPayStatus("aliPay");
                                uni.showToast({
                                    title: '支付成功'
                                })
                                resolve()
                            } else if (res.resultCode == '6001') {
                                uni.showToast({
                                    title: res.memo
                                })
                                // Util.abnormalOrderDeal(data) // 取消未支付订单
                                reject(res.memo)
                            } else {
                                // Util.abnormalOrderDeal(data) // 取消未支付订单
                                reject()
                            }
                        }
                    },
                    fail(err) {
                        // isPayment = true;
                        console.log('pay fail', err)
                        // Util.abnormalOrderDeal(data) // 取消未支付订单
                        reject()
                    }
                })
            })
        }
    }
}
</script>

<style lang="scss">
.row {
    display: flex;
    justify-content: space-between;
}
.par-input,
.par-btn {
    height: 88rpx;
}
.par-btn {
    width: 160rpx;
}
</style>