<template>
    <nav-bar :navbar-data="navbarData"></nav-bar>
    <view :style="{ marginTop: height + 'rpx' }">
        <van-tabs :value="active" :tabs="tabs" :scroll="false" height="88rpx" :lineScale="0.5" lineHeight="8rpx" @change="onChange" sticky></van-tabs>
    </view>
    <view style="padding-top: 10rpx;" v-if="active == 0">
        <view class="card_address">
            <view style="padding:20rpx 0 0 72rpx" v-if="addressObj">
                <text>{{ addressObj && addressObj.name }}</text>
                <text style="margin-left:9rpx;color:#949494">{{ addressObj && addressObj.mobile }}</text>
            </view>
            <view style="padding:20rpx 24rpx 20rpx 16rpx" class="distribution-info-head" @tap.stop="showPopup">
                <van-icon name="location" color="#42b983" size="20px" />
                <view style="margin-left:17rpx;width:580rpx">
                    <text v-if="addressObj">{{ addressObj.cityDesc }}{{ addressObj.areaDesc }}{{ addressObj.villageDesc }}{{addressObj.address }}</text>
                    <text v-else>请选择地址</text>
                </view>
                <view style="float:right; display: flex;">
                    <van-icon name="arrow" color="#cccccc" size="20px" />
                </view>
            </view>
        </view>
    </view>
    <view style="padding-top: 10rpx;" v-if="active == 1">
        <view class="card_address1">
            <view style="padding:20rpx 24rpx 20rpx 16rpx;display:flex">
                <van-icon name="location" color="#42b983" size="20px" />
                <view style="margin-left:17rpx;width:580rpx">
                    <text>{{ hospAddress }}</text>
                </view>
            </view>
        </view>
        <view style="margin:-10rpx 24rpx 0 24rpx">
            <van-cell-group>
                <view class="row">
                    <label>预留手机号</label>
                    <view class="row-right">
                        <input type="number" :value="mobile" placeholder="请输入手机号" @input="changePhone" style="text-align: right;" />
                    </view>
                </view>
                <!-- <van-cell title="取药时间" is-link value="{{dateShow}}" value-class="time_show" bindtap="showPopup2" /> -->
                <van-cell title="取药时间" value="每天8:00~17:30" />
            </van-cell-group>
            <!-- <view class="pay-type border-bottom-after">
			<text >支付类型</text>
			<view style="float:right">
				<van-radio-group class="radio" value="{{detailObj.insuType!='Y'?'1':payTypeRadio }}" bind:change="onChangePayType">
					<van-radio name="1">自费</van-radio>
					<van-radio name="2" disabled="{{detailObj.insuType!='Y'}}" bindtap="{{detailObj.insuType=='Y'?'':'healthMessage'}}">医保</van-radio>
				</van-radio-group>
			</view>
		</view> -->
        </view>
    </view>

    <view class="card">
        <view v-for="(itemName, idx) in drugArr" :key="idx">
            <view class="card_type">
                <text style="font-size:30rpx;color:rgba(51,51,51,1);">{{ itemName.locDesc }}{{ itemName.phaWin != '' ? '(' +
                    itemName.phaWin + ')' : '' }}</text>
                <!-- <view style="float:right;margin-right:20rpx" bindtap="takePhone" data-index="{{itemName}}" v-if="{{itemName.locPhone!=''}}">
				<van-icon size="40rpx" name="phone" />
			</view> -->
            </view>
            <view v-for="(item, index) in itemName.drugData" :key="index">
                <view class="border-top-before"></view>
                <view style="display: flex;flex-direction: row;">
                    <view class="top"></view>
                    <view class="card_drup">
                        <text style="font-size:28rpx;color:#333333">{{ item.medDesc }}</text>
                    </view>
                    <view style="margin:16rpx 23rpx 0 0;width:158rpx">
                        <view style="float:right">
                            <text style="font-size:24rpx;color:#999999">￥</text>
                            <text style="font-size:28rpx;">{{ item.medUnitPrice }}</text>
                        </view>
                    </view>
                </view>
                <view style="display: flex;flex-direction: row;margin:12rpx 23rpx 16rpx 50rpx">
                    <view style="width: 400rpx">
                        <text style="font-size:26rpx;">{{ item.medSpec }}</text>
                    </view>
                    <view style="width: 100% ">
                        <view style="float:right;">
                            <text style="font-size:26rpx;">x{{ item.medQty }}{{ item.medUnit }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <view v-for="(item1, index) in itemName.inspectMedData" :key="index">
                <view class="border-top-before"></view>
                <view style="display: flex;flex-direction: row;">
                    <view class="top"></view>
                    <view class="card_drup">
                        <text style="font-size:28rpx;color:#333333">{{ item1.medDesc }}</text>
                    </view>
                    <view style="margin:16rpx 23rpx 0 0;width:158rpx">
                        <view style="float:right">
                            <text style="font-size:24rpx;color:#999999">￥</text>
                            <text style="font-size:28rpx;">{{ item1.price }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="border-top-before" style="padding:20rpx 23rpx 20rpx 23rpx">
                <text>小计</text>
                <text style="float:right">¥ <text style="color:#FA541C">{{ itemName.totalPrice }}</text></text>
            </view>
            <view class="border-top-before"></view>
        </view>
        <view class="border-top-before" v-if="active == 0"></view>
        <view style="margin:20rpx 23rpx 20rpx 23rpx" v-if="active == 0">
            <text>配送费</text>
            <text style="float:right">到付</text>
        </view>
        <view class="border-top-before"></view>
        <view style="margin:20rpx 23rpx 20rpx 23rpx">
            <text>合计</text>
            <text style="float:right">¥ <text style="color:#FA541C">{{ detailObj.ordReasonPatAmt }}</text></text>
        </view>
        <view class="border-top-before"></view>
        <view>
            <view>
                <view class="row">
                    <label>备注</label>
                    <view class="row-right">
                        <textarea style="width: 100%" :value="value" rows="2" placeholder="备注信息" @input="getValue" maxlength="500" />
                    </view>
                </view>
            </view>
        </view>
    </view>

    <view class="wdc-footer-btn">
        <view class="health-pay-btn">
            <!-- insuType O只是门诊，R只是挂号，OR门诊和挂号，其它不使用医保;   insuTestFlag Y 是测试，O 是正式库测试 其它为正式使用 -->
            <!-- 测试 -->
            <block v-if="userData && (userData.insuType == 'O' || userData.insuType == 'OR') && userData.insuTestFlag == 'Y'">
                <view class="pay-css insu" @tap.stop="getAuthCode">
                    <text>医保支付</text>
                </view>
            </block>
            <!-- 测试 -->
            <block v-if="userData && (userData.insuType == 'O' || userData.insuType == 'OR') && !userData.insuTestFlag">
                <view class="pay-css insu" @tap.stop="getAuthCode">
                    <text>医保支付</text>
                </view>
            </block>
            <view class="pay-css personal" @tap="settlementPay">
                <text>自费支付</text>
            </view>
        </view>
    </view>

    <van-popup :show="show" position="bottom" @close="onClose">
        <view style="background: #ffffff;">
            <view style="padding:20rpx 24rpx 20rpx 24rpx">
                <view style="margin-bottom:20rpx">
                    <text class="address_text2">选择配送地址</text>
                    <view style="float:right">
                        <view class="cancel" @click="onClose">取消</view>
                    </view>
                </view>
                <view class="border-bottom-after::after"></view>
            </view>
            <view>
                <radio-group :value="radio" @change="onChange1">
                    <label class="addr-item" v-for="(item, index) in addressData" :key="index">
                        <radio name="addr" :value="item.id" icon-size="30rpx" :checked="radio == item.id" style="margin-top:14rpx; margin-right: 16rpx;"></radio>
                        <view class="addr-row">
                            <view>
                                <view style="width: 550rpx;">
                                    <text style="font-size: 32rpx;">{{ item.cityDesc }}{{ item.areaDesc }}{{ item.villageDesc }}{{ item.address }}</text>
                                </view>
                                <view>
                                    <text style="font-size:28rpx">{{ item.name }} {{ item.mobile }}</text>
                                </view>
                            </view>
                            <view style="display: flex; align-items: center; margin-left: 16rpx;">
                                <van-icon size="24px" name="edit" @click="updateAddress(item)" />
                            </view>
                        </view>
                    </label>
                </radio-group>
                <view style="display: flex;align-items: center;justify-content: center; padding:20rpx 0;">
                    <van-button size="small" custom-class="height:60rpx !important" round type="info" @tap="addAddress">增加配送地址</van-button>
                </view>
            </view>
        </view>
    </van-popup>
    <van-popup :show="show2" position="bottom" custom-style="height: 30%;" @close="onClose2">
        <uni-datetime-picker type="date" :border="false" :date-icon="false" :clear-icon="false" height="24px" v-model="currentDate" :start="minDate" :end="maxDate" @change="onInput" />
    </van-popup>
    <van-dialog id="van-dialog" ref="van-dialog" :closeable="false" />
</template>

<script>
    import $http from "@/utils/https";
    import Utils from "@/utils/utils";
	import { wxpay, alipay, ttpay } from '@/utils/pay'
    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'
    import VanIcon from '@/components/icon/index'
    import VanPopup from '@/components/popup/index'
    import VanTabs from '@/components/tabs/tabs.vue'
    import VanDialog from '@/components/dialog/index.vue';
    import Dialog from '@/components/dialog/dialog';
    //# ifdef MP-ALIPAYs
    import monitor from '@/utils/alipayLogger.js'
    //# endif

    let timer = null;
    const app = getApp();
    let isPayment = true;
    export default {
        components: {
            'nav-bar': NavBar,
            'van-button': VanButton,
            'van-cell-group': VanCellGroup,
            'van-cell': VanCell,
            'van-icon': VanIcon,
            'van-popup': VanPopup,
            'van-tabs': VanTabs,
            'van-dialog': VanDialog
        },
        data() {
            return {
                platform: app.globalData.platform,
                provider: app.globalData.provider,
                appId: app.globalData.appId, // 应用ID
                latitude: null, //维度
                longitude: null, //经度
                height: app.globalData.height * 2,
                navbarData: {
                    isGoHome: false,
                    isGoBack: true,
                    title: "订单详情"
                },
                tabs: ['配送到家', '到院服务'],
                // payTypeRadio: '',
                phone: "",
                active: 1,
                show: false,
                show2: false,
                radio: '',
                minHour: 6,
                maxHour: 24,
                minDate: new Date().getTime(),
                maxDate: new Date().getTime() + 259200000,
                currentDate: "",
                userData: null,
                dateShow: String,
                detailObj: Object,
                addressData: Array,
                addressObj: Object,
                value: "",
                hospDesc: String,
                hospAddress: String,
                telephone: String,
                mobile: String,
                medCardID: '',
                payTradeNum: "",
                infoByTrandNoFlag: false,
                infoByTrandNo: 0,
                drugArr: [],
                visitorData: [], // 就诊人列表数据
                isExistVisitor: false, // 是否存在就诊人
                admReasonCode: '', //操作code
            }
        },
        onLoad: function(options) {
            console.log('drstributionInfo options', options)
            const self = this;
            const userData = this.$cache.get('userData')
            if (userData && ['O', 'OR'].indexOf(userData.insuType) > -1 && ['Y', 'O'].indexOf(userData.insuTestFlag) == -1) {
                // console.log('医保提示框')
                Dialog.alert({
                    context: this,
                    title: '提示',
                    message: '医保线上支付仅支持市医保和省医保普通门诊结算，目前暂不支持慢特病门诊和跨省异地患者线上结算，为了不影响您的待遇，该类患者请到人工窗口进行结算。',
                    messageAlign: 'left'
                }).then(() => {
                    // on close
                });
            }

            this.setData({
                userData: userData,
                currentDate: new Date().getTime(),
                dateShow: this.formatTime(new Date()),
                hospDesc: userData.hospDesc,
                hospAddress: userData.hospAddress,
                telephone: userData.telephone,
                mobile: userData.mobile
            })

            //#ifdef MP-ALIPAY
            // 获取当前位置经纬度
            Utils.getLatLong().then(res => {
                this.latitude = res.latitude
                this.longitude = res.longitude
            })
            //#endif

            setTimeout(() => {
            	const orderDetailObj = self.$cache.get('orderDetailObj')
            	if (orderDetailObj) {
            		self.setData({
            			detailObj: orderDetailObj,
            			active: orderDetailObj.admTypeCode === 'W' ? 0 : 1
            		}, () => {
            			self.init(orderDetailObj.hisPatID)
            
            			self.drugQuery(); // 发药及窗口查询
            			if (orderDetailObj.addressObj) {
            				self.setData({
            					addressObj: orderDetailObj.addressObj,
            				}, function() {
            					console.log(self.addressObj)
            				})
            			}
            		});
            	} else {
            		console.log('orderDetail options', options)
            		// 获取缴费详情
            		if (options && options.detailparams) {
            			const params = {
            				hospCode: '',
            				patID: '',
            				patNo: '',
            				orderType: 'B',
            				prescribeTradeNum: ''
            			}
            			let detailparams = options.detailparams.split('-')
            			if (detailparams) {
            				params.hospCode = detailparams[0]
            				params.patID = detailparams[1]
            				params.patNo = detailparams[2]
            				params.orderType = detailparams[3]
            				params.prescribeTradeNum = detailparams[4]
            			}
            			console.log('orderDetail params', params)
            
            			if (options && options.resultCode == 'SUCCESS' && detailObj) {
            				// 医保支付授权
            				self.getAuthCode()
            			} else if (options && options.resultCode == 'SUCCESS' && !detailObj) {
            				self.orderDetail(params).then(detailObj => {
            					console.log('detailObj', detailObj)
            					self.setData({
            						detailObj: detailObj,
            						active: detailObj.admTypeCode === 'W' ? 0 : 1
            					}, () => {
            						self.init(detailObj.hisPatID).then(res => {
            							// 医保支付授权
            							self.getAuthCode()
            						})
            						self.drugQuery(); // 发药及窗口查询
            
            						if (detailObj.addressObj) {
            							self.setData({
            								addressObj: detailObj.addressObj,
            							}, function() {
            								console.log(self.addressObj)
            							})
            						}
            					})
            
            				})
            			} else if (options && options.resultCode == 'CANCEL_AUTH') {
            				my.alert({
            					title: '温馨提示',
            					content: '用户取消授权',
            					buttonText: '关闭'
            				})
            			}
            		}
            	}
            }, 100)
		},

        onShow: function(options) {
            console.log('distributionInfo onShow', options)
            const self = this
            let {
                payTradeNum,
                admReasonCode
            } = this;

            // 添加就诊人后回显时需要重新调用就诊人列表并切换就诊人到当前添加就诊人
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 1]
            console.log(prevPage.__data__)
            if (prevPage.__data__ && prevPage.__data__.hasOwnProperty('refreshData') && prevPage.__data__.refreshData == 1) {
                this.init(this.detailObj.hisPatID)
            }

            // 重新获取地址列表数据
            this.getAddressList()

            if (!isPayment) {
                isPayment = true;
            }
            // console.log('就诊号：' + payTradeNum)
            // console.log('操作类型：' + admReasonCode)
            if (app.globalData.platform == 'weixin') {
                if (payTradeNum) {
                    uni.showLoading();
                    self.getPayStatus(admReasonCode == '2' ? 'healthPay' : 'wechatPay');
                } else if (admReasonCode == '2' && app.globalData.authCode) {
                    // 如果是医保支付
                    self.settlementPay(admReasonCode)
                }
            } else {
                if (options && options.resultCode == 'SUCCESS') {
                    console.log('授权成功，再次执行授权查询接口，并执行结算')
                    // 医保支付授权
                    self.getAuthCode()
                } else if (options && options.resultCode == 'CANCEL_AUTH') {
                    my.alert({
                        title: '温馨提示',
                        content: '用户取消授权',
                        buttonText: '关闭'
                    })
                }
            }

            setTimeout(function() {
                let {
                    qrFlag
                } = self.detailObj
                let message = "支付超时，请刷新列表后重新支付"
                if (qrFlag && qrFlag === '1') {
                    message = "支付超时，请重新扫码支付"
                }
                Dialog.alert({
                    context: self,
                    title: '提示',
                    message: message,
                }).then(() => {
                    uni.navigateBack();
                });
            }, 120000);
        },

        //#ifdef MP
        onHide: function() {
        	console.log('onHide===')
        	this.$cache.remove('orderDetailObj')
        	if (timer) {
        		clearInterval(timer)
        	}
        },
        //#endif
        //#ifdef H5
        onUnload() {
        	console.log('onUnload===')
        	this.$cache.remove('orderDetailObj')
        },
        //#endif

        methods: {
            // 初始化数据
            init(hisPatID) {
                const self = this
                return new Promise((resolve, reject) => {
                    const status = [false, false]
                    // 获取就诊人列表数据
                    self.getVisitorDataList().then(() => {
                        console.log('就诊人数据', self.visitorData)
                        const resPat = self.visitorData.filter(item => item.hisPatID == hisPatID)
                        if (resPat && resPat.length > 0) {
                            self.setData({
                                isExistVisitor: true
                            })
                            self.selectedPat(resPat[0])
                        }
                        resolve()
                    }).catch(err => {
                        console.log(err)
                    })
                })
            },

            // 获取缴费详情
            orderDetail(data) {
                const self = this
                return new Promise((resolve, reject) => {
                    const paramsData = {
                        params: [{
                            hospCode: data.hospCode || '',
                            patID: data.patID || '',
                            patNo: data.patNo || '',
                            orderType: data.orderType || 'B',
                            prescribeTradeNum: data.prescribeTradeNum || ''
                        }]
                    }
                    console.log('orderDetail data', paramsData)
                    $http.post('urlS', this, {
                        code: '130997',
                        namespace: 'UPP',
                        UPPFlag: 'Y',
                        data: paramsData,
                        success(res) {
                            console.log('130997', res)
                            if (+res.errorCode == 0 && res.result) {
                                resolve(res.result)
                            }
                        },
                        error(err) {
                            reject(err)
                        }
                    })
                })
            },

            // 获取就诊人列表数据
            getVisitorDataList: function() {
                return new Promise((resolve, reject) => {
                    let data = {
                        params: []
                    }
                    $http.post("urlS", this, {
                        code: "01030001",
                        data: data,
                        success: function(res) {
                            if (+res.errorCode === 0) {
                                for (let i = 0; i < res.result.rows.length; i++) {
                                    if (res.result.rows[i].idCardNo.length == 18) {
                                        var str = res.result.rows[i].idCardNo.substr(6, 8);
                                        var simCard = res.result.rows[i].idCardNo.replace(str, '****');
                                        res.result.rows[i].NO = simCard;
                                    }
                                }
                                this.setData({
                                    visitorData: res.result.rows
                                });
                                resolve()
                            } else {
                                this.setData({
                                    visitorData: []
                                });
                                reject()
                            }
                        },
                        error(err) {
                            reject(err)
                        }
                    });
                })
            },

            // 切换就诊人
            selectedPat(value) {
                console.log('就诊人数据', value)
                let userData = this.$cache.get('userData');
                if (!(userData && userData.imUserID)) {
                    app.globalData.isLogOut = false;
                }
                if (value) {
                    this.setData({
                        mobile: value.mobile
                    })
                    const obj = {
                        ...userData,
                        idCardNo: value.idCardNo,
                        imUserID: value.imUserID,
                        patDesc: value.patName,
                        patID: value.patID,
                        hisPatNo: value.hisPatNo,
                        hisPatID: value.hisPatID,
                        mobile: value.mobile,
                        patValue: value.key,
                        patSexDesc: value.patSexDesc,
                        medCardID: value.medCardID
                    }
                    console.log(obj)
                    this.$cache.set('userData', obj);
                }
            },

            // 发药药品及窗口查询
            drugQuery: Utils.debounce(function() {
                let data = {
                    params: [{
                        payTradeNum: this.detailObj.orderType == 'P' ? this.detailObj.payTradeNum : '',
                        hospCode: this.$cache.get('userData').hisHospID,
                        userCode: "wxsf",
                        prescribeTradeNum: this.detailObj.orderType == 'P' ? '' : this.detailObj.prescribeTradeNum,
                    }]
                }
                $http.post("urlS", this, {
                    code: "130982",
                    data: data,
                    namespace: "UPP",
                    success: function(res) {
                        if (+res.errorCode === 0) {
                            this.setData({
                                drugArr: res.result.data
                            }, () => {
                                // console.log(res.result.data)
                            })
                        } else {
                            this.setData({
                                drugArr: []
                            })
                        }
                    }
                });
            }),

            // 地址列表
            getAddressList() {
                const self = this
                return new Promise((resolve, reject) => {
                    let userData = this.$cache.get('userData');
                    let data = {
                        params: [{
                            pubAccCode: userData.pubAccCode,
                            openID: userData.openID,
                        }]
                    }
                    $http.post("urlS", self, {
                        code: "01020006",
                        data: data,
                        success: function(res) {
                            if (+res.errorCode === 0) {
                                self.setData({
                                    addressData: res.result.rows,
                                    addressObj: res.result.rows[0],
                                    radio: res.result.rows[0] == undefined ? "" : res.result.rows[0].id,
                                    phone: res.result.rows[0] == undefined ? "" : res.result.rows[0].mobile
                                }, function() {
                                    console.log('接口请求回的数据addressObj', self.addressObj)
                                });
                                resolve()
                            } else {
                                self.setData({
                                    addressData: []
                                });
                            }
                        }
                    });
                })
            },

            updateAddress: Utils.debounce(function(addressObj) {
                const self = this
                // let addressObj = e.currentTarget.dataset.index
                console.log(addressObj)
                let str = JSON.stringify(addressObj)
                uni.navigateTo({
                    url: "../../../mine/addressManagement/address/address?optionType=edit&jsonStr=" + str,
                    success: (res) => {
                        // res.eventChannel.emit('detailObj', {
                        //     detailObj: self.detailObj,
                        //     addressObj: addressObj,
                        //     flag: "Y"
                        // })
                        this.$cache.set('DetailObj', {
                            detailObj: self.detailObj,
                            addressObj: addressObj,
                            flag: "Y"
                        })
                    },
                })
            }),

            addAddress: Utils.debounce(function() {
                uni.navigateTo({
                    url: "../../../mine/addressManagement/address/address",
                    success: (res) => {
                        res.eventChannel.emit('detailObj', {
                            detailObj: this.detailObj,
                            flag: "Y"
                        })
                    },
                })
            }),

            turnPay: Utils.debounce(function() {}),

            showPopup2() {
                this.setData({
                    show2: true
                });
            },

            onClose2() {
                this.setData({
                    show2: false
                });
            },

            onInput(event) {
                this.setData({
                    currentDate: event.detail,
                    dateShow: this.formatTime(new Date(event.detail))
                }, () => this.onClose2());
            },

            onChange(event) {
                console.log(event)
                this.setData({
                    active: parseInt(event.detail.name),
                });
            },

            getValue(event) {
                this.setData({
                    value: event.detail
                })
            },

            //时间格式化
            formatTime(date) {
                var year = date.getFullYear()
                var month = date.getMonth() + 1
                var day = date.getDate()
                var hour = date.getHours()
                var minute = date.getMinutes()
                //var second = date.getSeconds()
                return year + "-" + month + "-" + day + " " + hour + ":" + minute
            },

            onChange1(event) {
                console.log(event)
                const self = this
                const {
                    addressData
                } = self;
                self.setData({
                    radio: event.detail.value
                }, () => {
                    addressData.forEach((item, index) => {
                        if (item.id == event.detail.value) {
                            self.setData({
                                addressObj: item
                            })
                        }
                    })
                });
                self.onClose()
            },

            showPopup() {
                this.setData({
                    show: true
                });
            },

            onClose() {
                this.setData({
                    show: false
                });
            },

            changePhone(event) {
                this.setData({
                    phone: event.detail
                })
            },

            /**
             * 支付预结算
             */
            settlementPay: Utils.debounce(function(code) {
                console.log('settlementPay.admReasonCode', code)
                const {
                    platform,
                    appId,
                    latitude,
                    longitude
                } = this
                // console.log("isPayment", isPayment)

                // 如果是医保支付，经纬度为空重新获取后再提交
                if (platform == 'alipay' && code == '2' && (!latitude || !longitude)) {
                    Utils.getLatLong().then(res => {
                        this.latitude = res.latitude
                        this.longitude = res.longitude
                        this.settlementPay(code)
                    })
                    return
                }
                if (!isPayment) {
                    return;
                }
                let userData = this.$cache.get('userData')
                isPayment = false;
                let {
                    addressObj,
                    active,
                    detailObj,

                } = this
                let admReasonCode = typeof(code) === 'string' ? code : '1';
                var getDate = this.dateShow.split(" ")
                var orderInfo = {}
                const userCode = platform == "alipay" ? "alisf" : "wxsf"
                if (addressObj || active == 1) {
                    if (active == 0) {
                        var orderInfo = {
                            userCode,
                            hospCode: userData.hisHospID,
                            patientID: detailObj.patID ? detailObj.patID : (userData.hisPatID ? userData.hisPatID : ''),
                            admID: detailObj.admID,
                            selfPickFlag: "N",
                            receiveName: addressObj.name,
                            receivePhone: addressObj.mobile,
                            receiveProvinceDesc: addressObj.provinceDesc, //省
                            receiveCityDesc: addressObj.cityDesc, //市
                            receiveAreaDesc: addressObj.areaDesc, //区
                            receiveVillageDesc: addressObj.villageDesc, //街道
                            receiveHamletDesc: addressObj.HamletDesc,
                            receiveAdress: addressObj.address, //详细地址
                            patAddress: addressObj.provinceDesc + addressObj.cityDesc + addressObj.areaDesc + addressObj.villageDesc + addressObj.address,
                            remark: this.value
                        }
                    } else {
                        var orderInfo = {
                            userCode,
                            hospCode: userData.hisHospID,
                            patientID: detailObj.patID ? detailObj.patID : (userData.hisPatID ? userData.hisPatID : ''),
                            admID: detailObj.admID,
                            selfPickFlag: "Y",
                            receiveName: detailObj.patName ? detailObj.patName : (userData.patDesc ? userData.patDesc : ''),
                            receivePhone: this.mobile,
                            selfPickDate: getDate[0],
                            selfPickTime: getDate[1],
                            remark: this.value
                        }
                    }
                } else {
                    uni.showToast({
                        title: '请先选择地址',
                        icon: 'none',
                        duration: 2000
                    })
                    isPayment = true;
                    return
                }
                // if (this.payTypeRadio === '') {
                //   uni.showToast({
                //     title: '请选择支付类型',
                //     icon: 'none',
                //     duration: 2000
                //   })
                //   return
                // }
                let data1 = {
                    code: "99070009",
                    params: [{
                        prescribeTradeNum: detailObj.prescribeTradeNum,
                        patAmt: detailObj.ordReasonPatAmt,
                        orderAdmReasonID: detailObj.orderAdmReasonID,
                        userCode,
                        hospCode: userData.hisHospID,
                        patientID: detailObj.patID ? detailObj.patID : (userData.hisPatID ? userData.hisPatID : ''),
                        admID: detailObj.admID,
                        payWayCode: platform == "alipay" ? "ALIPAY" : "WECHAT",
                        payWayAmt: detailObj.ordReasonPatAmt,
                        orderInfo: orderInfo
                    }]
                }
                console.log('detailObj', detailObj)
                let data = {
                    params: [{
                        //#ifdef MP-ALIPAY
                        appID: appId || '', // 应用APPID
                        latitude: (latitude && longitude) ? (latitude + ',' + longitude) : '', // 当前用户所在位置经纬度
                        //#endif
                        authCode: app.globalData.authCode, // 医保支付授权码
                        cityCode: userData.cityCode, // 医保城市编码
                        channel: userData.channel, // 医保渠道号
                        prescribeTradeNum: detailObj.prescribeTradeNum,
                        totalFee: detailObj.ordReasonPatAmt,
                        ipAddress: "",
                        medicalcardid: this.medCardID,
                        payReasonID: detailObj.detail[0].admReasonID,
                        insuType: admReasonCode == '2' ? 'Y' : 'N',
                        body: detailObj.businessDesc,
                        businessType: platform == "alipay" ? "OPAliPAY" : "OPPAY",
                        patNo: detailObj.patID ? detailObj.patID : (userData.hisPatNo ? userData.hisPatNo : ''),
                        patName: detailObj.patName ? detailObj.patName : (userData.patDesc ? userData.patDesc : ''),
                        idCardNo: userData.idCardNo,
                        mobile: userData.mobile,
                        data: data1
                    }]
                }
                uni.showLoading({
                    title: '结算中,请稍后',
                    mask: true
                })
                console.log('入参', data)
                $http.post("urlS", this, {
                    code: "01050002",
                    data: data,
                    success: function(res) {
                        console.log('01050002', res)
                        uni.hideLoading();
                        isPayment = true;
                        app.globalData.authCode = '' // 清空医保授权码
                        if (+res.errorCode === 0) {
                            this.setData({
                                payAmtInt: detailObj.ordReasonPatAmt, // 订单金额
                                prescribeTradeNum: detailObj.prescribeTradeNum,
                                payTradeNum: res.result.payTradeNum ? res.result.payTradeNum : '',
                                payOrderStr: res.result.payOrderStr ? res.result.payOrderStr : ''
                            }, () => {
                                if (res.result.payFlag === 'N') {
                                    this.turnOrder('Y')
                                } else {
                                    if (admReasonCode == '2') {
                                        this.toJumpHealthPay(res.result) // 跳转医保待支付待结算详情页
                                    } else {
                                        this.unifyPay(res.result)
                                    }
                                }
                            })
                        } else {
                            setTimeout(() => {
                                uni.showToast({
                                    title: res.errorMessage,
                                    icon: 'none',
                                    duration: 2000
                                })
                            }, 300)
                        }
                    },
                    error: function(err) {
                        app.globalData.authCode = ''
                        isPayment = true
                    }
                });
            }),

            // 医保移动支付获取授权码
            getAuthCode: Utils.debounce(function(data) {
                const self = this
                const userData = this.$cache.get('userData')
                const {
                    platform,
                    detailObj
                } = this
                this.setData({
                    admReasonCode: '2'
                }, () => {
                    console.log('getAuthCode.admReasonCode', self.admReasonCode)
                    // hisHospID-hisPatID-hisPatNo-orderType-prescribeTradeNum
                    if (platform == 'alipay') {
                        const detailParams = userData.hisHospID + '-' + userData.hisPatID + '-' + userData.hisPatNo + '-' + detailObj.orderType + '-' + detailObj.prescribeTradeNum +
                            '-' + app.globalData.authCode
                        Utils.getAuthCode(app, detailParams).then(res => {
                            // 如果是医保支付
                            self.settlementPay(self.admReasonCode)
                        })
                    } else {
                        Utils.getAuthCode(app)
                    }
                })
            }),

            // 跳转到医保结算详情页
            toJumpHealthPay: Utils.debounce(function(data) {
                if (typeof data == 'object') {
                    data['flag'] = this.flag
                    data['payAmtInt'] = this.payAmtInt
                    data['payTradeNum'] = this.payTradeNum
                    data['prescribeTradeNum'] = this.prescribeTradeNum
                    data['orderStr'] = this.payOrderStr
                }
                console.log('跳转到医保结算详情页 toJumpHealthPay', data)
                uni.navigateTo({
                    url: "/pages/index/pages/videoConsultation/waitYbSettlement/index",
                    success: (res) => {
                        res.eventChannel.emit('settlmentData', {
                            settlmentData: data
                        })
                    },
                })
            }),

            // 获取支付状态
            getPayStatus(btnType) {
                let self = this;
                let userData = this.$cache.get('userData');
                let {
                    infoByTrandNo,
                    infoByTrandNoFlag,
                    flag,
                    payTradeNum,
                    payAmtInt,
                    prescribeTradeNum,
                    platform
                } = self;
                console.log('infoByTrandNo', infoByTrandNo)
                console.log('infoByTrandNoFlag', infoByTrandNoFlag)
                if (!infoByTrandNoFlag) {
                    infoByTrandNo++
                    self.setData({
                        infoByTrandNo
                    })
                    if (self.infoByTrandNo > 5) {
                        uni.hideLoading();
                        self.setData({
                            infoByTrandNo: 0
                        })
                        isPayment = true
                        return
                    }
                }
                let data = {
                    params: [{
                        hospitalCode: userData.hisHospID || '',
                        userCode: platform == "alipay" ? "alisf" : "wxsf",
                        payTradeNum: this.payTradeNum
                    }]
                }
                uni.showLoading({
                    title: '订单状态查询中',
                    mask: true
                })
                $http.post("urlS", this, {
                    code: "130980",
                    data: data,
                    namespace: "UPP",
                    success: function(res) {
                        console.log('130980', res)
                        isPayment = true;
                        if (+res.errorCode === 0) {
                            // uni.removeStorageSync('detailObj') // 清除缓存
                            uni.hideLoading();
                            this.setData({
                                infoByTrandNoFlag: true
                            }, () => {
                                // if (btnType === "wechatPay" || btnType === "aliPay") {
                                //     self.turnOrder('Y')
                                // } else if (btnType === "healthPay") {
                                //     self.turnOrder()
                                // }
                                if (["wechatPay", "healthPay", "aliPay"].indexOf(btnType) > -1) {
                                    //# ifdef MP-ALIPAY
                                    // 服务办结
                                    monitor.api({
                                        api: "门诊缴费",
                                        success: true,
                                        c1: "taSR_YL",
                                        time: Math.floor(Math.random() * 100 + 50)
                                    })
                                    //# endif
                                    uni.reLaunch({
                                        url: '/pages/index/common/paySuccess/paySuccess?payAmtInt=' + payAmtInt + '&flag=' + flag + '&payTradeNum=' + payTradeNum +
                                            '&prescribeTradeNum=' + prescribeTradeNum
                                    })
                                }
                            })
                        } else if (res.errorCode == 'UN') { // 医保支付成功，HIS保存未成功，跳转账单已付款页面
                            uni.removeStorageSync('detailObj') // 清除缓存
                            uni.switchTab({
                                url: '../../pages/tabBar/order/order?tab=1',
                            })
                        } else if (res.errorCode == 'NOTPAY') {
                            self.resetData(res.errorMessage)
                        } else if (+res.errorCode == 40004) {
                            uni.hideLoading()
                            return
                        } else {
                            if (self.infoByTrandNo == 5) {
                                self.resetData(res.errorMessage)
                            } else {
                                self.getPayStatus(btnType)
                            }
                        }
                    },
                    error: function(error) {
                        self.resetData("失败，稍后重试")
                    }
                });
            },

            resetData(errorMessage) {
                uni.hideLoading()
                isPayment = true;
                uni.showToast({
                    icon: 'none',
                    title: errorMessage
                })
                this.setData({
                    payTradeNum: '',
                    prescribeTradeNum: ''
                })
            },

            // 微信、支付宝支付调用
            unifyPay(data) {
                let self = this;
                console.log('预结算返回参数', data)
                return new Promise((resolve, reject) => {
                    const {
                        platform,
                        provider
                    } = self
                    data['provider'] = provider
                    
                    // #ifdef MP-WEIXIN || H5
                    // 微信公众号支付
                    wxpay(data)
                        .then(async (res) => {
                    		uni.showToast({
                    			title: "支付成功",
                    			success(res) {
                    				self.getPayStatus("wechatPay");
                    			}
                    		})
                    		resolve()
                    	})
                        .catch((errMsg) => {
                    		Utils.abnormalOrderDeal(data) // 取消未支付订单
                    		reject(errMsg)
                    	})
                    // #endif
                    
                    // #ifdef MP-ALIPAY 
                    // 支付宝小程序支付
                    if (platform == 'alipay') {
                        data['orderInfo'] = data.trade_no
                    }
                    alipay(data)
                    	.then(res => {
                    		if (provider == 'alipay') {
                    			console.log(provider, res.resultCode)
                    			if (res.resultCode == '9000') {
                    				uni.showToast({
                    					title: '支付成功'
                    				},() => {
                    					self.getPayStatus("aliPay");
                    				})
                    				resolve()
                    			} else if (res.resultCode == '6001') {
                    				uni.showToast({
                    					title: res.memo
                    				}, () => {
                    					Utils.abnormalOrderDeal(data) // 取消未支付订单
                    				})
                    				reject(res.memo)
                    			} else {
                    				Utils.abnormalOrderDeal(data) // 取消未支付订单
                    				reject()
                    			}
                            }
                    	}).catch(err => {
                    		isPayment = true;
                    		console.log('调用支付失败', err)
                    		Utils.abnormalOrderDeal(data) // 取消未支付订单
                    		reject(err)
                    	})
                    // #endif
                })
            },

            turnOrder: Utils.debounce(function(flag) {
                let url = '../../../tabBar/order/order'
                if (flag == 'Y') {
                    url + '?flag=Y'
                }
                uni.switchTab({
                    url: url,
                })
            }),

            toQueryPair(index, key, value) {
                if (typeof value == 'undefined') {
                    return `${key}=`
                }
                if (index == 0) {
                    return `?${key}=${value}`
                }
                return `&${key}=${value}`
            },

            // 医保支付接口报错提醒
            healthMessage() {
                let {
                    detailObj
                } = this;
                if (detailObj && ['O', 'R', 'OR'].indexOf(detailObj.insuType) == -1) {
                    uni.showToast({
                        title: "暂不支持医保支付",
                        icon: 'none',
                        duration: 2000
                    })
                    isPayment = true;
                    return;
                }
                let userData = this.$cache.get('userData');
                let data = {
                    params: [{
                        openID: userData.openID || '',
                        pubAccCode: userData.pubAccCode || '',
                        idCardNo: userData.idCardNo || '',
                        patName: userData.patDesc || '',
                        hospCode: userData.hisHospID || '',
                    }]
                }
                $http.post("urlS", this, {
                    code: "01050011",
                    data: data,
                    success: function(res) {
                        if (+res.errorCode === 0) {
                            // console.log(res)
                            if (res.result.medical_card_id) {
                                this.setData({
                                    medCardID: res.result.medical_card_id
                                }, () => {
                                    this.settlementPay("2");
                                })
                            } else {
                                uni.showToast({
                                    title: '暂不支持医保支付',
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        } else {
                            uni.showToast({
                                title: res.errorMessage,
                                icon: 'none',
                                duration: 2000
                            })
                        }
                    }
                });
            },

            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">
    .distribution-info-head {
        display: flex;
    }

    text {
        font-size: 32rpx;
        font-family: PingFang SC;
        color: #666666;
        line-height: 39rpx;
    }

    .card_address {
        background: rgba(255, 255, 255, 1);
        border-radius: 10rpx;
        margin: 0 24rpx 10rpx 24rpx;
    }

    .card_drup {
        margin: 16rpx 0 0 10rpx;
        width: 483rpx;
    }

    .foot {
        position: fixed;
        bottom: 0;
        left: 0;
        z-index: 100;
        width: 100%;
        text-align: right;
        display: flex;
    }

    .card {
        background: rgba(255, 255, 255, 1);
        border-radius: 10rpx;
        margin: 10rpx 25rpx 0 25rpx;
        margin-bottom: calc(env(safe-area-inset-bottom) + 144rpx);
    }

    .top {
        width: 10rpx;
        height: 10rpx;
        background: rgba(204, 204, 204, 1);
        border-radius: 50%;
        margin: 30rpx 0 0 32rpx
    }

    .card_type {
        margin: 20rpx 0 20rpx 25rpx;
    }

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

    .input {
        font-size: 32rpx;
    }

    .van-cell__title {
        font-size: 32rpx;
        margin-left: -10rpx;

    }

    .van-button--info {
        border: 0 !important;
        margin-top: -5rpx !important;
    }

    .time_show {
        color: #FA8C16 !important;
    }

    .card_address1 {
        background: rgba(255, 255, 255, 1);
        border-top-left-radius: 10rpx;
        border-top-right-radius: 10rpx;
        margin: 0 24rpx 10rpx 24rpx;
    }

    .cancel {
        width: 64rpx;
        font-size: 28rpx;
        padding-bottom: 7px !important;
        color: #007AFF;
    }

    .foot .paybutton {
        width: 100%;
        height: 100%;
    }

    .pay-type {
        border-radius: 10rpx 10rpx 0 0;
        font-size: 32rpx;
        color: #666;
        background-color: rgba(255, 255, 255, 1);
        padding: 20rpx 38rpx 20rpx 24rpx;

    }

    .radio {
        display: flex !important;
    }

    .radio .van-radio {
        margin-left: 30rpx;
    }

    .wdc-footer-btn {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        font-size: 32rpx;
        background: white;
    }

    .health-pay-btn {
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        padding: 30rpx;
        padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);
    }

    .health-pay-btn .pay-css {
        position: relative;
        width: 330rpx;
        height: 88rpx;
        background: #FEA935;
        border-radius: 8rpx;
        font-size: 28rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #FFFFFF;
        line-height: 40rpx;
        text-align: center;
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .health-pay-btn .pay-css:active {
        background: #e19931;
    }

    .health-pay-btn .pay-css.personal {
        background-color: #007AFF;
        margin-left: 20rpx;
    }

    .health-pay-btn .pay-css:active::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.1);
    }


    .foot .pay-css {
        position: relative;
        height: 100rpx;
        line-height: 100rpx;
        font-size: 32rpx;
        color: rgba(255, 255, 255, 1);
        background-color: #1890FFFF;
        text-align: center;
        width: 330rpx;
        flex: 1;
        margin-bottom: env(safe-area-inset-bottom);
    }

    .foot .pay-css text,
    .health-pay-btn .pay-css text {
        color: #FFFFFF;
    }

    .foot .pay-css.insu .health-pay-btn .pay-css.insu {
        background-color: #FEA935;
    }

    .addr-item {
        display: flex;
        padding: 16rpx 24rpx;
        .addr-row {
            display: flex;

            .col {
                &-2 {
                    flex: 2;
                }

                &-4 {
                    flex: 4;
                }
            }
        }
    }
</style>