<route lang="jsonc" type="page">
{
    "needLogin": true,
    "layout": "default",
    "style": {
        "navigationStyle": "custom"
    }
}
</route>
<template>
    <view>
        <view>
			<navbar title="收银台" custom-class='!bg-[#F6F7F8]' :leftArrow="false"></navbar>
		</view> 

        <!-- 支付信息 -->
        <view class="mt-56rpx text-center">
            <view class="text-28rpx leading-40rpx text-#606266">顾客打赏-{{ info.name }}</view>
            <view class="mt-24rpx">
                <price-format color="#303133" :first-size="44" :second-size="44" :subscript-size="28" :price="money"></price-format>
            </view>
            <view class="mt-12rpx flex items-center justify-center">
                <view class="text-24rpx leading-34rpx text-#606266">
                    支付剩余时间           
                </view>             
                <wd-count-down :time="time" custom-class="!text-[#606266] !text-24rpx !leading-34rpx" />
            </view>
        </view>

        <!-- 支付方式 -->
        <view class="bg-white rounded-16rpx px-30rpx py-34rpx mx-30rpx mt-84rpx">
            <view class="font-400 text-32rpx leading-44rpx text-#303133 border-b border-b-solid border-b-#F6F7F8 pb-16rpx mb-32rpx">支付方式</view>
            <!-- pay 组件 -->
            <pay hide-store-balance @pay="Cashier.handleGetPayValue"></pay>
        </view>

        <view
            class="fixed bottom-70rpx left-0 right-0 bg-#4C9F44 text-#fff font-bold text-30rpx leading-42rpx mx-60rpx h-90rpx leading-90rpx text-center rounded-8rpx" 
            @click="Cashier.handleToPay">立即支付
        </view>
    </view>
</template>

<script lang="ts" setup>
    import Pay from '@/components/Pay.vue'
    import { getTeaSpecialistDetails, getTeaSpecialistOrderDetails, teaSpecialistPrepay, teaSpecialistPay } from '@/api/tea'
    import { ITeaSpecialistDetailsFields } from '@/api/types/tea'
    import { toast } from '@/utils/toast'
	import { router } from '@/utils/tools'
    import { payTipTeaSpecialist } from '@/api/pay'
	import { useUserStore } from '@/store'
    import type {IUserInfoVo } from '@/api/types/login'

    // 用户信息
	const userInfo = ref<IUserInfoVo>(null)

    // 支付倒计时取消
    const time = ref<number>(30 * 60 * 60 * 1000)

    // 支付金额
    const money = ref<number>(0)
    
    // 茶艺师详情
    const id = ref<number>(0)
    const info = reactive<ITeaSpecialistDetailsFields>({ 
        id: 0,
        name: '',
        star: 0,
        image: '',
        reservation_num: 0,
        distance: 0,
        speed: 0,
        real: { gender: 1, both: 18, height: 165, weight: 53, interests: '爱好茶艺，喜欢旅游，把爱好当工作' },
        teamasterlabel: [],
        teamasterLevel: [],
        price: 0,
        fare_price: 0,
        collect: 0,
        up_status: 0,
        textarea: []
    })

    // 支付方式
    const pay = ref<number>(0)

    // 订单
    const orderId = ref<number>(0)
    const order = ref<{}>(null)
    const result = ref<string>('')
    const from = ref<string>('')
    
    onLoad(async (args) => {
        const userStore = useUserStore()
        userInfo.value = userStore.userInfo 

        from.value = args.from || ''

        if (args.from == 'tip' && args.teaSpecialistId && args.money) {
            // 这边处理打赏金额
            id.value = Number(args.teaSpecialistId)
            money.value = Number(args.money)
            Cashier.handleGetTeaSpecialistDetails(id.value, Number(userInfo.value.id))
        } else if (args.from == 'order' && args.teaSpecialistId && args.orderId) {
            // 获取订单详情
            orderId.value = Number(args.orderId)
            Cashier.handleGetOrderDetails()
        } else {
            toast.info('参数错误')
            return
        }

        console.log('页面加载')
    })

    onUnload(() => {
        switch(result.value) {
            case 'success': 
                uni.$emit('payment', { result: true, orderId: orderId.value })
                break;
            case 'fail':
            default: uni.$emit('payment', { result: false, orderId: orderId.value })
        }
    })

    const Cashier = {
        // 获取茶艺师详情
        handleGetTeaSpecialistDetails: async (id: number, user_id: number) => {
            const res = await getTeaSpecialistDetails({
                id,
                latitude: uni.getStorageSync('latitude'),
                longitude: uni.getStorageSync('longitude'),
                user_id
            })
            // 将返回的数据合并到 reactive 对象中
            Object.assign(info, res.teamaster || {})
        },

        // 获取订单详情
        handleGetOrderDetails: async () => {
            // 获取订单详情接口
            const res = await getTeaSpecialistOrderDetails({id: orderId.value})
            order.value = res
            money.value = Number(res.details.order_amount)
        },

        // 获取支付方式
        handleGetPayValue: (value: number) => {
            pay.value = value
        },

        // 去支付
        handleToPay: async () => {
            console.log("🚀 ~ pay.value :", pay.value )
            if (pay.value == null || pay.value == undefined) {
                toast.info('请选择支付方式')
                return
            }

            if (from.value == 'tip') {
                payTipTeaSpecialist({
                    id: id.value,
                    tip_price: money.value,
                    pay_type: pay.value
                }).then(res => {
                    router.navigateTo('/pages/notice/reserve?type=tipSuccess')
                    console.log("🚀 ~ res:", res)
                })
            } else if (from.value == 'order') {
                try {
                    // 预支付
                    const res1 = await teaSpecialistPrepay({
                        order_id: orderId.value,
                        from: 'balance',
                        pay_way: pay.value,
                        order_source: 2 //订单来源：1-小程序;2-h5;3app
                    })

                    // 支付
                    const res2 = await teaSpecialistPay({
                       id: res1.pay_id
                    })
                    result.value = 'success'
                } catch (error) {
                    result.value = 'fail'
                }
                
                setTimeout(() => {
                    uni.navigateBack({delta: 1})
                }, 500);
            }
 
          
        }
    }
</script>


<style lang="scss" scoped>
    page {
		background-color: $cz-page-background;
	}
</style>
