<template>
    <nav-bar id="nav-bar" ref="navBar" :navbar-data="navbarData"></nav-bar>
    <view class="order" :style="{paddingTop: height +'px', height: 'calc(100vh - '+ height + 'px)', overflow: 'hidden'}">
        <van-tabs ref="tabs" :value="active" :tabs="tabs" :scroll="false" height="88rpx" :lineScale="0.5" lineHeight="8rpx" @change="onChange" :fixed="tabFixed"></van-tabs>
        <scroll-view class="tab-content" scroll-y="true" :style="{height: 'calc(100vh - '+ (height + tabBarHeight) +'px)'}">
            <view class="content">
                <view class="order-card" v-for="(item,index) in orderList" :key="index" @tap.stop="toJump" :data-index="item">
                    <view class="order-card-head">
                        <view class="order-card-title ">
                            <view class="order-card-title-text1">
                                <image v-if=" item.businessDesc=='视频问诊(微信)' " style="width:40rpx;height:30rpx;" :src="imgHost +'/images/icon/order_video.png'" />
                                <image v-else-if=" item.businessDesc=='住院缴费(微信)' " style="width:32rpx;height:40rpx;" :src="imgHost +'/images/icon/order_hospital.png'" />
                                <image v-else-if="item.businessDesc=='门诊缴费(微信)'||item.businessDesc=='门诊缴费'" style="width:40rpx;height:40rpx;" :src="imgHost +'/images/icon/order_offline.png'" />
                                <image v-else-if="item.businessDesc=='图文问诊(微信)'" style="width:36rpx;height:36rpx;" :src="imgHost +'/images/icon/order_pic.png'" />
                                <image v-else-if="item.businessDesc=='门诊待缴费'" style="width:32rpx;height:34rpx;" :src="imgHost +'/images/icon/order_online.png'" />
                                <image v-else-if="item.businessDesc=='自助下单(微信)'" style="width:32rpx;height:36rpx;" :src="imgHost +'/images/icon/order_selfhelp.png'" />
                                <image v-else style="width:32rpx;height:36rpx;" :src="imgHost +'/images/icon/order_selfhelp.png'" />
                                <text style="margin-left:16rpx">{{item.businessDesc}}</text>
                            </view>
                            <view v-if="item.orderType==='P'&&(item.refundApp===''||!item.refundApp)" class="order-card-title-text2">已付款</view>
                            <view v-if="item.orderType==='B'&&(item.refundApp===''||!item.refundApp)" class="order-card-title-text3">待付款</view>
                            <view v-if="(item.orderType==='PART' || item.orderType==='T')&&(item.refundApp===''||!item.refundApp)" class="order-card-title-text4">已退款</view>
                            <view v-if="item.orderType==='UN'&&(item.refundApp===''||!item.refundApp)" class="order-card-title-text3" style="color: red;">订单异常</view>
                            <view v-if="item.refundApp&&item.refundApp!=''" class="order-card-title-text3" style="color: #007AFF;">退款{{item.refundApp}}</view>
                        </view>
                        <view class="order-card-title-text5" v-if="(item.orderType=='T'||item.orderType=='P'||item.orderType=='PART')&&item.payTradeNum">订单编号：{{item.payTradeNum}}</view>
                        <view class="order-card-title-text5" v-if="item.invType=='O'&&((item.orderType=='NB')||(item.orderType=='B'))">处方流水号：{{item.prescribeTradeNum}}</view>
                    </view>
                    <view class="order-card-boby">
                        <view>
                            <image style="width:100rpx;height:100rpx;border-radius: 50%;" :src="item.admDocImage?item.admDocImage:imgHost + '/images/icon/avatar_doctor_act.png'" onerror="imageError"
                                :data-index="index"></image>
                        </view>
                        <view class="order-card-boby-text">
                            <view>医生：{{item.admDocDesc}}</view>
                            <view>就诊人：{{item.patName}}</view>
                            <view>类别：{{item.orderAdmReason}}</view>
                            <view>下单时间：{{item.payDateTime}}</view>
                        </view>
                    </view>
                    <view class="order-card-footer">
                        <view style="margin-left:20rpx">
                            <view class="order-card-footer-text1" v-if="item.orderState!='TP'">¥{{item.ordReasonPatAmt}}</view>
                            <view class="order-card-footer-text2" v-if="item.orderState!='TP' && item.orderType!='B'">
                                {{ item.businessCode && item.businessCode.indexOf('AliPAY') > -1 ? '支付宝支付':'微信支付' }}
                            </view>
                        </view>
                        <view class="order-card-footer-btn">
                            <view class="btn1" @tap.stop="toJump(item)" :data-index="item">订单详情</view>
                            <!-- <view class="btn1" @catchtap.native="item.invType=='R' ? 'getOrderDetail':item.orderType!='NB'? item.admTypeCode==='W'?'getOrderType':'goFeeQuery':''" :data-index="item">订单详情</view> -->
                            <view class="btn1" v-if="item.orderType=='P'&&item.pictureUrl" @tap.stop="electronicinv" :data-index="item">电子发票</view>
                            <view class="btn2" v-if="item.onlineYBFalg != 'Y' && (item.admTypeCode=='W'||!item.admTypeCode)&&item.orderType=='P'&&item.orderState!='TP'&&(!item.refundApp||item.refundApp==='')" @tap.stop="turnReturn" :data-index="item">申请退款</view>
                            <view class="btn2" v-if="item.onlineYBFalg == 'Y' && (item.admTypeCode=='W'||!item.admTypeCode)&&item.orderType=='P'&&item.orderState!='TP'&&(!item.refundApp||item.refundApp==='')" @tap.stop="turnYBReturn" :data-index="item">医保退款申请</view>
                            <view class="btn2" v-if="(item.admTypeCode=='W'||!item.admTypeCode)&&item.orderType=='TP'&&(!item.refundApp||item.refundApp==='')" @tap.stop="returnUnusual" :data-index="item">撤销异常订单</view>
							<view class="btn3" v-if="item.orderType=='B'" @tap.stop="turnTrans(item)" :data-index="item">
							    {{!!(item.purPoseCode) ? '预付款' : '立即付款'}}
							</view>
                        </view>
                    </view>
                </view>
                <van-divider contentPosition="center">数据已全部加载</van-divider>
            </view>
        </scroll-view>
    </view>
</template>

<script>
	import Utils from '@/utils/utils';
	import $http from "@/utils/https";
	import { getHospList, switchHospital, dealSwitchHospital } from '@/utils/common.js';
	import httpConfig from '@/utils/httpConfig';
    import navBar from '@/components/navBar/index.vue';
    import vanTabs from '@/components/tabs/tabs.vue';
    import vanDivider from '@/components/divider/index.vue';
    const app = getApp();
    export default {
        components: {
            'nav-bar': navBar,
            'van-tabs': vanTabs,
            'van-divider': vanDivider
        },
        data() {
            return {
                tabBarHeight: 70,
                tabs: ['待付款', '已付款', '全部'],
                active: 0,
                tabFixed: false,
                height: app.globalData.height, // 头部标题栏和状态栏总高度
                imgHost: httpConfig && httpConfig.imgHost,
                windowHost: httpConfig && httpConfig.ipDeault,
                navbarData: {
                    isGoHome: false,
                    isGoBack: false,
                    title: "账单"
                },
                orderList: Array,
                count: 0,
                patID: '',
                patNo: '',
                admID: '',
                qrFlag: "0",
                detailObj: null,
				platform: app.globalData.platform,
				provider: app.globalData.provider,
				appId: app.globalData.appId, // 应用ID
				latitude: null, //维度
				longitude: null, //经度
            }
        },
        onReady() {
            const height = this.$refs.tabs.height
            this.tabBarHeight = height && parseInt(height)
        },
        onShow: function() {
            uni.showLoading({
                mask: true,
                title: '加载中...'
            })
			
			// 微信独立处理
            // #ifdef MP-WEIXIN
            if (typeof this.getTabBar === 'function' &&
                this.getTabBar()) {
                this.getTabBar().setData({
                    selected: 1
                })
            }
            // #endif
			
            const userData = this.$cache.get('userData')

            // 获取当前小程序的页面栈
            let pages = getCurrentPages();
            // 数组中索引最大的页面--当前页面
            let currentPage = pages[pages.length - 1];
            // 打印出当前页面中的 options

            let options
            // 支付宝独立处理
            // #ifdef MP-ALIPAY
            !options && (options = {})
			options['q'] = app.globalData.alipayQuery
            // #endif

            // #ifndef MP-ALIPAY
            options = currentPage.options
            // #endif

            if (options && options.q) {
                //let qrUrl = decodeURIComponent(options.q).split('/');
                //let parString = decodeURIComponent(options.q).split("=")[1];
                let parString = decodeURIComponent(options.q);
                let patID = parString.split("^")[0];
                let patNo = parString.split("^")[1];
                let admID = parString.split("^")[2];
                let hospCode = parString.split("^")[3];
                currentPage.options = {}
                this.setData({
                    patID: patID,
                    patNo: patNo,
                    admID: admID,
                    qrFlag: "1"
                }, () => {
                    // 获取医院数据
                    this.getHospSelectData(hospCode);
                })
            } else {
                this.setData({
                    patID: userData && userData.hisPatID,
                    patNo: userData && userData.hisPatNo,
                    admID: ''
                }, () => {
                    this.orderQuery();
                })
            }
            // console.log(userData.onlineYBFalg)
            // console.log(app.globalData.authCode)
            if (app.globalData.authCode && this.detailObj) {
                this.turnReturn({
                    currentTarget: {
                        dataset: {
                            index: this.detailObj
                        }
                    }
                })
            }

            // 支付宝独立处理
            // #ifdef MP-ALIPAY
			// 获取当前位置经纬度
			Utils.getLatLong().then(res => {
			    this.latitude = res.latitude
			    this.longitude = res.longitude
			})
            uni.hideBackHome(); // 隐藏
            Utils.resetGlobalDataParams(app, ['alipayQuery'])
            // #endif
        },
        methods: {
            toJump(detailObj) {
                let type = detailObj.invType == 'R' ? 'getOrderDetail' : (detailObj.orderType != 'NB' ? (detailObj.admTypeCode === 'W' ? 'getOrderType' : 'goFeeQuery') : '')
                switch (type) {
                    case 'getOrderDetail':
                        this.getOrderDetail(detailObj)
                        break;
                    case 'getOrderType':
                        this.getOrderType(detailObj)
                        break;
                    case 'goFeeQuery':
                        this.goFeeQuery(detailObj)
                        break;
                }
            },

            // 获取医院数据
            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 => {
						uni.hideLoading()
						setTimeout(() => {
						    _this.orderQuery();
						}, 300)
					})
					.catch(error => {})
            },

            onChange(event) {
				// this.handleDataset()
				console.log('onChange === ', event)
                this.setData({
                    active: `${event.detail.name}`,
                }, () => {
                    this.orderQuery()
                });
            },

            orderQuery: Utils.debounce(function() {
                const self = this
                let userData = this.$cache.get('userData')
                let {
                    patID,
                    patNo,
                    admID,
                    windowHost
                } = self
                var payFlag = self.active
                var orderType = "A"
                if (payFlag == "0") {
                    var orderType = "B"
                } else if (payFlag == "1") {
                    var orderType = "P"
                } else {
                    var orderType = "A"
                }
                let data = {
                    params: [{
                        patID: patID ? patID : (userData.hisPatID ? userData.hisPatID : ''),
                        //patID: "36118",
                        hisHospID: userData.hisHospID || "",
                        patNo: patNo ? patNo : (userData.hisPatNo ? userData.hisPatNo : ''),
                        //patNo: '0000036118',
                        orderType: orderType,
                        admID: admID || ""
                    }]
                }
                $http.post("urlS", self, {
                    code: "01050003",
                    data: data,
                    success: function(res) {
						console.log(res)
                        uni.hideLoading();
                        if (+res.errorCode === 0) {
                            let orderList = res.result
                            for (var i = 0; i < orderList.length; i++) {
                                let url = orderList[i] && orderList[i].admDocImage ? orderList[i].admDocImage : "";
                                orderList[i].admDocImage = url.indexOf("http") !== -1 ? url : url ? windowHost + "/images/photo/" + url : '';
                            }
                            self.setData({
                                orderList: orderList
                            });
                        } else {
                            self.setData({
                                orderList: []
                            });
                            uni.showToast({
                                title: res.errorMessage,
                                icon: 'none',
                                duration: 2000
                            })
                        }
                    },
                    error: function() {
                        uni.hideLoading();
                    }
                });
            }),

            getOrderDetail: Utils.debounce(function(detailObj) {
                uni.navigateTo({
                    url: "../../order/pages/orderDetail/orderDetail",
                    success: (res) => {
                        // res.eventChannel.emit('detailObj', {
                        //     detailObj: detailObj
                        // })
						this.$cache.set('orderDetailObj', detailObj)
                    },
                })
            }),

            getOrderType: Utils.debounce(function(detailObj) {
                detailObj.hisPatID = this.patID
                detailObj.hisPatID = this.qrFlag
                uni.navigateTo({
                    url: "../../order/pages/orderType/orderType",
                    success: (res) => {
                        res.eventChannel.emit('detailObj', {
                            detailObj: detailObj
                        })
                    },
                })
            }),

            turnPay: Utils.debounce(function() {
                uni.navigateTo({
                    url: "../../order/pages/orderType/orderType"
                })
            }),

            // 申请退款
            turnReturn: Utils.debounce(function(e) {
                let detailObj = e.currentTarget.dataset.index
                let obj = {
                    detailObj: detailObj
                }
                if (app.globalData.authCode) {
                    obj['authCode'] = app.globalData.authCode
                }
                uni.navigateTo({
                    url: "../../order/pages/orderRefund/orderRefund",
                    success: (res) => {
                        res.eventChannel.emit('detailObj', obj)
                    },
                })
            }),

            // 医保退款
            turnYBReturn: Utils.debounce(function(e) {
                this.setData({
                    detailObj: e.currentTarget.dataset.index
                })
                Utils.getAuthCode()
            }),

            // 撤销异常订单
            returnUnusual: Utils.debounce(function(e) {
                const self = this
                let detailObj = e.currentTarget.dataset.index
                if (!detailObj) return
                Dialog.confirm({
                        title: '确认提示',
                        message: '您确定要撤销该订单吗？',
                    })
                    .then(() => {
                        Utils.abnormalOrderDeal({
                            payTradeNum: detailObj.payTradeNum,
                            prescribeTradeNum: detailObj.prescribeTradeNum
                        }).then(res => {
                            self.orderQuery();
                        })
                    })
                    .catch(() => {
                    });
            }),

            // 付款
            turnTrans: Utils.debounce(function(detailObj) {
                console.log('点击了付款', detailObj)
				console.log(detailObj, detailObj?.purPoseCode)
				if (!!(detailObj?.purPoseCode)) { // 存在支付方式，走押金充值
			      this.handlePrepaidDepositRecharge(detailObj);
			      return;
			    };
				detailObj.hisPatID = this.patID;
			    uni.navigateTo({
			      url: "../../order/pages/distributionInfo/distributionInfo",
			      success: (res) => {
			        // res.eventChannel.emit('detailObj', {
			        //   detailObj: detailObj
			        // })
					console.log(detailObj)
					this.$cache.set('orderDetailObj', detailObj)
			      },
			    })
				
                // let detailObj = e.currentTarget.dataset.index
                // detailObj.hisPatID = this.patID
                // // detailObj.hisPatID = this.qrFlag
                // uni.navigateTo({
                //     url: "/pages/order/pages/distributionInfo/distributionInfo",
                //     success: (res) => {
                //         // this.$cache.set('detailObj', detailObj)
                //         res.eventChannel.emit('detailObj', {
                //             detailObj: detailObj
                //         })
                //     },
                // })
            }),

            checkFee: Utils.debounce(function(e) {
                uni.showToast({
                    title: "处方审核中,请稍后付款",
                    icon: 'none',
                    duration: 2000
                })
            }),

            electronicinv: Utils.debounce(function(e) {
                let detailObj = e.currentTarget.dataset.index
                let pictureUrlObj = detailObj.pictureUrl
                uni.navigateTo({
                    url: "/pages/index/pages/electronicinv/electronicinv" + "?url=" + pictureUrlObj
                })
            }),

            // 更新userData数据
            upDateUserData() {
                let newUserData = this.$cache.get('userData');
                if (newUserData && newUserData.mobile) {
                    newUserData.mobile = (newUserData.mobile && newUserData.mobile.length === 11) ? Utils.phoneAddGap(newUserData.mobile) : "";
                }
                if (!(this.userData && (this.userData.hisPatID === newUserData.hisPatID))) {
                    this.setData({
                        userData: newUserData
                    }, () => {
                        this.orderQuery();
                    });
                }
            },

            goFeeQuery: Utils.debounce(function(e) {
                let detailObj = e.currentTarget.dataset.index
                uni.navigateTo({
                    url: "/pages/order/pages/feeInquiryDetail/feeInquiryDetail",
                    success: (res) => {
                        res.eventChannel.emit('detailObj', {
                            detailObj: detailObj
                        })
                    },
                })
            }),
			
			// 预交金充值
			handlePrepaidDepositRecharge: function (record) {
				const { appId, platform, latitude, longitude  } = this
			    let userData = this.$cache.get('userData');
				const userCode = platform == "alipay" ? "alisf" : "wxsf"
				const payWayCode = platform == "alipay" ? "ALIPAY" : "WECHAT"
			    let collbackParams = {
			      code: '99070016',
			      params: [{
			        patNumber: record?.patNo || userData?.hisPatNo,
			        patAmt: record?.patAmt || record?.ordReasonPatAmt || '',
			        remark: '',
			        userCode,
			        hospCode: userData.hisHospID || '',
			        patientID: record?.patNo || userData?.hisPatNo,
			        admID: '',
			        payWayCode,
			        payWayAmt: record?.patAmt || record?.ordReasonPatAmt || '',
			        purPoseCode: record?.purPoseCode || '',
			        saveObjID: record?.saveObjID || ''
			      }]
			    }
			    let data = {
			      params: [{
					//#ifdef MP-ALIPAY
					appID: appId || '', // 应用APPID
					latitude: (latitude && longitude) ? `${latitude},${longitude}` : '', // 当前用户所在位置经纬度
					//#endif
			        totalFee: record?.patAmt || record?.ordReasonPatAmt || '',
			        ipAddress: '',
			        medicalcardid: '',
			        payReasonID: '',
			        insuType: '',
			        body: '',
			        businessType: 'DEPPAY',
			        patNo: record?.patNo || userData?.hisPatNo || '',
			        patName: record?.patName || userData?.patDesc || '',
			        idCardNo: record?.patIDCardNo || userData?.idCardNo || '',
			        mobile: record?.patMobile || userData?.mobile || '',
			        data: collbackParams,
			        saveObjID: record?.saveObjID || ''
			      }]
			    }
			    uni.showLoading({
			      title: '结算中,请稍后',
			      mask: true
			    })
			    $http.post('urlS', this, {
			      code: '01050002',
			      data,
			      success: function (res) {
			        uni.hideLoading();
			        if (+res.errorCode === 0) {
			          this.handlePay(res.result, record?.patAmt || record?.ordReasonPatAmt || '', )
			        } else {
			          setTimeout((
			            uni.showToast({
			              title: res.errorMessage,
			              icon: 'none',
			              duration: 2000
			            })
			          ), 300)
			        }
			      }
			    });
			},
			
			//微信/支付宝通用支付调用
			handlePay(data, patAmt) {
			    console.log('uniapp通用支付',data)
			    return new Promise((resolve, reject) => {
			        uni.requestPayment({
			            timeStamp: data.timeStamp + "",
			            nonceStr: data.nonceStr,
			            package: data.package,
			            signType: data.signType,
			            paySign: data.paySign,
			            success(res) {
			                console.log('pay success', res)
							uni.navigateTo({
							  url: '/pages/order/pages/prepaymentRechargeSuccessful/prepaymentRechargeSuccessful?amt=' + patAmt,
							})
			                resolve()
			            },
			            fail(err) {
			                isPayment = true;
			                console.log('pay fail', err)
			                Utils.abnormalOrderDeal(data) // 取消未支付订单
			                reject()
			            }
			        })
			    })
			},
			
			// 微信支付调用
			wechatPay(data, patAmt) {
			    wx.requestPayment({
			      timeStamp: data.timeStamp + '',
			      nonceStr: data.nonceStr,
			      package: data.package,
			      signType: data.signType,
			      paySign: data.paySign,
			      success(res) {
			        uni.navigateTo({
			          url: '/pages/order/pages/prepaymentRechargeSuccessful/prepaymentRechargeSuccessful?amt=' + patAmt,
			        })
			      },
			      fail(res) { }
			    })
			},
			
            imageError(e) {
                let {
                    imgHost,
                    orderList
                } = this;
                var index = e.target.dataset.index;
                orderList[index].admDocImage = imgHost + "/images/icon/avatar_doctor_act.png";
                this.setData({
                    orderList: orderList
                });
            },
        },
    }
</script>

<style lang="scss">
    $white: #ffffff;
    $fontFamily: 'PingFangSC-Regular, PingFang SC';
    $gray-e5: #E5E5E5;
    $gray-f7: #f7f7f7;
    $gray-9: #999999;
    $gray-6: #666666;
    $gray-3: #333333;
    $blue: #007AFF;
    $green: #20A735;
    $black: #000000;
    $red: #FB3349;


    .order {
        box-sizing: border-box;
    }

    .tab-content {
        box-sizing: border-box;
        border: 1px solid $gray-e5;
        background-color: $gray-f7;
    }

    .content {
        padding-bottom: 40rpx;
    }

    .order-card {
        padding: 30rpx;
        margin-top: 20rpx;
        background: $white;

        &-title {
            display: flex;
            justify-content: space-between;
            align-items: center;

            &-text1,
            &-text2,
            &-text3,
            &-text4,
            &-text5 {
                font-size: 26rpx;
                font-weight: 400;
                line-height: 36rpx;
            }

            &-text1 {
                color: $gray-3;
                display: flex;
                align-items: center;
            }

            &-text2 {
                color: $green;
            }

            &-text3 {
                color: $blue;
            }

            &-text4 {
                color: $black;
            }

            &-text5 {
                color: $gray-9;
                margin-top: 6rpx;
            }
        }

        &-head {
            border-bottom: 2rpx solid $gray-e5;
            padding-bottom: 20rpx;
        }

        &-boby {
            padding: 20rpx 0;
            display: flex;
            align-items: center;
            border-bottom: 2rpx solid $gray-e5;

            &-text {
                view {
                    font-size: 28rpx;
                    font-weight: 400;
                    color: $gray-3;
                    line-height: 40rpx;
                    margin-bottom: 6rpx;
                    margin-left: 30rpx;
                }
            }
        }

        &-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 12rpx;

            &-text1 {
                font-size: 28rpx;
                font-weight: 400;
                line-height: 40rpx;
                color: $red;
            }

            &-text2 {
                font-size: 22rpx;
                font-weight: 400;
                line-height: 32rpx;
                color: $gray-9;
            }

            &-btn {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .btn1,
                .btn2,
                .btn3 {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    box-sizing: border-box;
                    min-width: 140rpx;
                    min-height: 56rpx;
                    border-radius: 8rpx;
                    padding: 0 20rpx;
                    font-size: 26rpx;
                    font-weight: 400;
                    margin-left: 30rpx;
                    line-height: 36rpx;
                }

                .btn1 {
                    background: $white;
                    border: 2rpx solid $blue;
                    color: $blue;
                }

                .btn2 {
                    background: $white;
                    border: 2rpx solid $gray-6;
                    color: $gray-6;

                }

                .btn3 {
                    background: $blue;
                    border: 2rpx solid $blue;
                    color: $white;
                }
            }
        }

    }
</style>