<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" v-if="!teaPackageTitle">{{ title }}</view>
            <view class="text-28rpx leading-40rpx text-#606266" v-if="teaPackageTitle">茶艺师套餐-{{ teaPackageTitle }}
            </view>
            <view class="mt-24rpx">
                <template>
                    <price-format color="#303133" :first-size="44" :second-size="44" :subscript-size="28"
                        :price="money"></price-format>
                </template>
            </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 @pay="Cashier.handleGetPayValue" :hidePlatformBalance="hidePlatformBalance"
                :hideStoreBalance="hideStoreBalance" :hideWechat="hideWechat" :storeMoney="storeMoney"></pay>
        </view>

        <view
            class="fixed bottom-70rpx left-0 right-0  text-#fff font-bold text-30rpx leading-42rpx mx-60rpx text-center rounded-8rpx w-630rpx">
            <wd-button custom-class='!bg-[#4C9F44] !rounded-8rpx !h-90rpx !leading-90rpx !w-630rpx'
                :disabled="isSubmitting" @click='Cashier.handleToPay'>{{ isGroupBuying ? '立即购买' : '立即预定' }}</wd-button>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { getTeaSpecialistDetails } from '@/api/tea'
import { ITeaSpecialistDetailsFields } from '@/api/types/tea'
import { prePay, balancePay, newPrePay } from '@/api/pay'
import type { IUserInfoVo } from '@/api/types/login'
import { getTeaRoomBalance, getTeaRoomOrderDetail, getTeaRoomPackageOrderDetail, getTeaRoomPackageDetail, getTeaRoomPayOrderAmount, getRenewTeaRoomPayOrderAmount } from '@/api/tea-room'
import Pay from '@/components/Pay.vue'
import { PayValue, PayValueMap, PayOrderType, PayOrderSource } from '@/utils/pay'
import { toast } from '@/utils/toast'
import { router } from '@/utils/tools'
import { OrderType } from '@/utils/order'
import { wechatPay } from '@/hooks/usePay'
import { useUserStore } from '@/store'
import { getTeaSpecialistOrderDetails } from '@/api/teaSpecialist-order'


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

// 支付倒计时取消
const time = ref<number>(3 * 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 hideWechat = ref<boolean>(false)
const hidePlatformBalance = ref<boolean>(false)
const hideStoreBalance = ref<boolean>(false)

// 订单
const orderId = ref<number>(0)
const order = ref<{}>(null)
const result = ref<string>('')
const from = ref<string>('')

// 支付标题
const title = ref<string>('')

// 门店ID
const storeId = ref<number>(0)
const storeMoney = ref<number>(0)
const comboId = ref<number>(0) // 套餐ID

// 一键续订支付
const renew = ref<string>('')

// 购买套餐支付
const isGroupBuying = ref<number>(0)
const groupCouponId = ref<number>(0)

// 只有在续订茶艺师下才有这个renewOrderId
const renewOrderId = ref<number>(0)
// 预约茶艺师支付
const reserveTeaSpecialist = ref<boolean>(false)
const teaSpecialistOrderAmount = ref<number>(0) // 茶艺师订单金额

// 茶艺师套餐标题
const teaPackageTitle = ref<string>('')

// 防止重复提交
const isSubmitting = ref(false)

onLoad(async (args: any) => {
    // 订单
    orderId.value = Number(args.orderId)
    comboId.value = Number(args.cmoboId) || 0

    // 茶艺师套餐
    teaPackageTitle.value = args.teaPackageTitle || ''

    // 套餐购买
    groupCouponId.value = Number(args.groupCouponId) || 0
    isGroupBuying.value = Number(args.isGroupBuying) || 0
    console.log("🚀 ~ isGroupBuying.value:", isGroupBuying.value)

    // 一键续订
    renew.value = args?.renew || ''

    // 获取门店余额
    if (args.storeId) {
        storeId.value = Number(args.storeId)
        const balance = await getTeaRoomBalance({ store_id: storeId.value })
        storeMoney.value = Number(balance.data.money) || 0
    }

    // 设置支付来源标题
    from.value = args.from || ''
    if (from.value === OrderType.TeaRoomOrder) {
        // 茶室订单：预定、套餐团购两种方式
        if (args.name && isGroupBuying.value == 0) {
            title.value = renew.value ? `茶室续订-${args.name}` : `茶室预定-${args.name}`
        } else {
            title.value = `茶室套餐购买-${args.name}`
            hideStoreBalance.value = true // 隐藏门店余额支付
        }
    } else if (from.value === OrderType.TeaSpecialist) {
        // 预约茶艺师
        renewOrderId.value = args.renewOrderId
        teaSpecialistOrderAmount.value = Number(args.teaSpecialistOrderAmount) || 0
        reserveTeaSpecialist.value = true
        if (renewOrderId.value > 0) {
            title.value = `续订茶艺师-${args.teaSpecialistName || ''}`
        } else {
            title.value = `预订茶艺师-${args.teaSpecialistName || ''}`
        }

        hideStoreBalance.value = true // 隐藏门店余额支付
    }

    // 用户信息
    const userStore = useUserStore()
    userInfo.value = userStore.userInfo

    // 获取订单详情
    if (args.from == OrderType.TeaRoomOrder && args.orderId) {
        // 获取订单详情
        if (isGroupBuying.value == 0) {
            // 茶室预约订单走这个接口，续订的不需要
            if (renew.value) {
                Cashier.handleGetRenewOrderDetails()
            } else {
                Cashier.handleGetOrderDetails()
            }
        } else {
            Cashier.handleGetRoomPackageDetails(args.money)
        }
    } else if (args.from == OrderType.TeaSpecialist && args.orderId) {
        // 获取预定茶艺师订单详情
        Cashier.handleGetTeaSpecialistOrderDetails()
    }
})

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 = {
    /**获取茶艺师订单详情
     * 
     * @param id 
     * @param user_id 
     */
    handleGetTeaSpecialistOrderDetails: async () => {
        const res = await getTeaSpecialistOrderDetails({
            id: orderId.value
        })
        order.value = res
        if (teaSpecialistOrderAmount.value > 0) {
            money.value = teaSpecialistOrderAmount.value
        } else {
            money.value = Number(res.order_amount)
        }
    },

    /**
     * 获取预定茶室订单详情
     */
    handleGetOrderDetails: async () => {
        // 获取订单详情接口
        // const res = await getTeaRoomOrderDetail({
        //     id: orderId.value,
        //     latitude: uni.getStorageSync('latitude') || import.meta.env.VITE_DEFAULT_LATITUDE,
        //     longitude: uni.getStorageSync('longitude') || import.meta.env.VITE_DEFAULT_LONGITUDE,
        // })
        const res = await getTeaRoomPayOrderAmount({
            id: orderId.value,
            pay_way: pay.value || PayValue.PlatformBalance
        })
        console.log("🚀 ~ getTeaRoomPayOrderAmount res:", res)
        order.value = res
        money.value = Number(res.details.order_amount)
    },

    /**
     * 获取茶室续订订单详情
     */
    handleGetRenewOrderDetails: async () => {
        const res = await getRenewTeaRoomPayOrderAmount({
            id: orderId.value,
            pay_way: pay.value || PayValue.PlatformBalance
        })
        console.log("🚀 ~ getRenewTeaRoomPayOrderAmount res:", res)
        order.value = res
        money.value = Number(res.details.order_amount)
    },

    /**
     * 获取茶室套餐订单详情(改为args传过来金额)
     * @param value 
     */
    handleGetRoomPackageDetails: async (m: number) => {
        // const res = await getTeaRoomPackageDetail({
        //     id: comboId.value
        // })
        money.value = m
    },

    /**
     * 获取支付方式
     * @param value 支付value
     */
    handleGetPayValue: (value: number) => {
        pay.value = value

        // 茶室订单：为了获取不同支付方式下的订单金额
        if (from.value == OrderType.TeaRoomOrder && orderId.value && isGroupBuying.value == 0) {
            if (renew.value) {
                // 续订订单
                Cashier.handleGetRenewOrderDetails()
            } else {
                // 正常茶室订单
                Cashier.handleGetOrderDetails()
            }
        }
    },

    /**
     * 支付
     */
    handleToPay: async () => {
        if (isSubmitting.value) return

        if (pay.value == null || pay.value == undefined) {
            toast.info('请选择支付方式')
            return
        }

        isSubmitting.value = true

        if (from.value == OrderType.TeaRoomOrder) {
            // 预支付-茶室订单
            uni.showLoading({ title: '支付中...' })
            try {
                // 预支付
                const res = await prePay({
                    from: PayValueMap[pay.value],
                    order_id: orderId.value,
                    pay_way: pay.value,
                    order_source: PayOrderSource.MINI, //订单来源：1-小程序; 2-h5; 3app
                    order_type: Cashier.handleGetOrderType(), // 0为茶艺师 1为茶室包间 2为茶室套餐
                    store_id: storeId.value || 0
                })

                // 余额支付(平台余额、门店余额)
                if (pay.value == PayValue.PlatformBalance || pay.value == PayValue.StoreBalance) {
                    await balancePay({
                        id: res.pay,
                        store_id: storeId.value || 0,
                        pay_way: pay.value,
                    })

                    uni.hideLoading()
                    result.value = 'success'

                    isSubmitting.value = false
                    router.navigateBack(1, 500)
                } else if (pay.value == PayValue.WeChatPay) {
                    // 微信支付
                    console.log("🚀 ~ res.pay:", res.pay)
                    if (res.pay_type && res.pay_type == 1) {
                        toast.success('支付成功')
                        result.value = 'success'
                        isSubmitting.value = false
                        router.navigateBack(1, 500)
                        return
                    } else {
                        wechatPay(res.pay.config).then((res) => {
                            console.log("🚀 ~ res:", res)
                            uni.hideLoading()
                            if (res === 'success') {
                                toast.success('支付成功')
                                result.value = 'success'
                            } else if (res === 'cancel') {
                                toast.info('已取消支付')
                                result.value = 'fail'
                            } else {
                                toast.info('支付失败，请重试')
                                result.value = 'fail'
                            }

                            isSubmitting.value = false
                            router.navigateBack(1, 500)
                            return
                        }).catch((e) => {
                            console.log("🚀 ~ error:", e)
                            uni.hideLoading()
                            toast.info('支付失败，请重试')
                            return
                        })
                    }
                }
            } catch (error) {
                isSubmitting.value = false
                uni.hideLoading()
                result.value = 'fail'
                router.navigateBack(1, 500)
                return
            }
        } else if (from.value == OrderType.TeaSpecialist) {
            // 预支付-茶艺师订单
            uni.showLoading({ title: '支付中...' })
            try {
                // 预支付
                const res = await newPrePay({
                    from: PayValueMap[pay.value],
                    order_id: renewOrderId.value > 0 ? renewOrderId.value : orderId.value, //如果是续单的话，则用续单的订单ID
                    pay_way: pay.value,
                    order_source: PayOrderSource.MINI, //订单来源：1-小程序; 2-h5; 3app
                    order_type: renewOrderId.value > 0 ? PayOrderType.RenewTeaSpecialist : PayOrderType.TeaSpecialis, // 茶艺师订单
                })

                // 余额支付(平台余额)
                if (pay.value == PayValue.PlatformBalance && res) {

                    uni.hideLoading()
                    result.value = 'success'

                    isSubmitting.value = false
                    router.navigateBack(1, 500)
                } else if (pay.value == PayValue.WeChatPay) {
                    if (res.order_amount && Number(res.order_amount) == 0) {
                        toast.success('支付成功')
                        result.value = 'success'
                        isSubmitting.value = false
                        router.navigateBack(1, 500)
                        return
                    } else {
                        // 微信支付
                        wechatPay(res.config).then((res) => {
                            uni.hideLoading()
                            if (res === 'success') {
                                toast.success('支付成功')
                                result.value = 'success'
                            } else if (res === 'cancel') {
                                toast.info('已取消支付')
                                result.value = 'fail'
                            } else {
                                toast.info('支付失败，请重试')
                                result.value = 'fail'
                            }

                            isSubmitting.value = false
                            router.navigateBack(1, 500)
                            return
                        }).catch((e) => {
                            console.log("🚀 ~ error:", e)
                            uni.hideLoading()
                            toast.info('支付失败，请重试')
                            return
                        })
                    }
                }
            } catch (error) {
                isSubmitting.value = false
                uni.hideLoading()
                result.value = 'fail'
                router.navigateBack(1, 500)
                return
            }
        }
    },

    /**
     * 订单类型
     */
    handleGetOrderType: () => {
        if (isGroupBuying.value) {
            // 购买团购套餐
            return PayOrderType.BuyCombo
        } else if (renew.value) {
            // 续订包间
            return PayOrderType.RenewRoom
        } else if (reserveTeaSpecialist.value) {
            // 预约茶艺师
            return PayOrderType.TeaSpecialis
        } else {
            // 默认是购买茶室
            return PayOrderType.TeaRoom
        }
    }
}
</script>


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