<template>
    <view class="order_buy">
        <!-- 地址卡片 -->
        <view class="card" @click="goPage('/bundle/pages/user_address/index?type=true')">
            <view class="card--header flex justify-between">
                <template v-if="!orderData.userAddressDetailVo">
                    <view class="title pt-[20rpx]">请选择地址</view>
                </template>
                <template v-else>
                    <view class="title"
                        >{{ orderData.userAddressDetailVo?.contact }}
                        {{ orderData.userAddressDetailVo?.mobile }}</view
                    >
                </template>

                <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
            </view>
            <template v-if="orderData.userAddressDetailVo">
                <view class="text-sm text-muted">
                    {{ orderData.userAddressDetailVo.province }}
                    {{ orderData.userAddressDetailVo.city }}
                    {{ orderData.userAddressDetailVo.district }}
                    {{ orderData.userAddressDetailVo.address }}
                </view>
            </template>
        </view>

        <!-- 商品卡片 -->
        <view class="card">
            <view class="goods-item">
                <u-image
                    :src="orderData.imageUrl"
                    width="160"
                    height="160"
                    border-radius="4"
                ></u-image>
                <view class="ml-[20rpx] mt-[4rpx]">
                    <view class="flex justify-between title">
                        <view class="goods-item--name truncate">{{ orderData.goodsName }}</view>
                        <text class="num">x{{ goodsForm.goods_num }}</text>
                    </view>
                    <view class="mt-[24rpx]">
                        <price :price="orderData.goodsPrice" :desc="orderData.unitName"></price>
                    </view>
                </view>
            </view>
        </view>

        <!-- 上门时间 -->
        <view
            class="card flex justify-between"
            @click="
                goPage(
                    `/bundle/pages/appoint_time/index?appointTime=${JSON.stringify(appointTime)}`
                )
            "
        >
            <view class="normal text-base font-medium">上门时间</view>
            <view class="flex">
                <text class="mr-[20rpx] text-sm text-black">{{ appoint }}</text>
                <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
            </view>
        </view>

        <!-- 备注 -->
        <view class="card">
            <view class="normal text-lg font-medium">备注</view>
            <view class="mt-[10rpx]">
                <u-input
                    v-model="userRemark"
                    type="textarea"
                    placeholder="请填写您的特殊需求"
                    height="124"
                />
            </view>
        </view>

        <!-- 服务金额 -->
        <view class="card">
            <view class="flex justify-between normal text-base">
                <view class="font-medium">服务金额</view>
                <view>{{ `¥${orderData.totalPrice}` }}</view>
            </view>
			<!-- todo -->
            <!-- <view class="mt-4 flex justify-between normal text-base">
                <view class="font-medium">服务金额</view>
                <view @tap="showCoupons = true">
                    <span class="rounded-full bg-primary py-1 px-2 mr-2 text-white">3张可用</span>
                    <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
                </view>
            </view> -->
        </view>

        <view class="footer flex justify-between items-center">
            <view class="text-primary">
                <text class="text-base">需支付：¥</text>
                <text class="font-medium text-4xl">{{ orderData.totalPrice }}</text>
            </view>
            <view class="btn">
                <button
                    class="bg-primary text-lg text-white leading-[80rpx] h-[80rpx]"
                    @tap="onSubmitOrder"
                >
                    提交订单
                </button>
            </view>
        </view>

        <!-- Component 页面状态 -->
        <!-- <page-status ref="pageRef"></page-status> -->

        <!-- Component 支付 -->
        <payment
            v-if="payState.showPay || payState.showCheck"
            ref="paymentRef"
            v-model:show="payState.showPay"
            v-model:show-check="payState.showCheck"
            :order-id="payState.orderId"
            :order_amount="orderData?.totalPrice"
            :from="payState.from"
            :redirect="payState.redirect"
            @success="handlePayResult"
            @close="handlePayResult"
            @fail="handlePayResult"
        />

        <u-popup
            v-model="showCoupons"
            mode="bottom"
            border-radius="14"
            :closeable="false"
            :safe-area-inset-bottom="true"
        >
            <view class="coupons">
                <view class="coupons-header">
                    <text class="mx-auto">选择优惠券</text>
                    <u-icon name="close" color="#666666" @tap="showCoupons = false" />
                </view>

                <view class="coupons-main">
                    <scroll-view :scroll-y="true" style="height: 700rpx; touch-action: none">
                        <view
                            class="coupons-item"
                            v-for="item in [1, 2, 3, 2, 3, 2, 3, 2, 3]"
                            :key="item"
                        >
                            <coupon-card
                                :item="item"
                                :showBtn="false"
                                :showSelect="true"
                                v-model="selectCoupon"
                            />
                        </view>
                        <view class="text-center text-xs py-6 text-[#999]">
                            以下此订单暂不适用
                        </view>
                        <view
                            class="coupons-item-mask"
                            v-for="item in [1, 2, 3, 2, 3, 2, 3, 2, 3]"
                            :key="item"
                        >
                            <coupon-card :item="item" :showBtn="false" :status="0" />
                        </view>
                        <u-empty
                            v-if="![1, 2, 3].length"
                            text="暂无优惠券"
                            src="/static/images/empty/coupon_icon.png"
                            :icon-size="180"
                        />
                    </scroll-view>
                </view>

                <view class="coupons-footer px-4 pb-1">
                    <button
                        class="bg-primary text-lg text-white leading-[80rpx] h-[80rpx] rounded-full"
                        @tap="onSubmitOrder"
                    >
                        确定
                    </button>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, shallowRef } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { apiPlaceOrder, apiInitOrder } from '@/api/order'
import Price from '@/components/price/index.vue'
import { useLockFn } from '@/hooks/useLockFn'

const paymentRef = shallowRef()
const orderData = ref<any>({
    userAddressDetailVo: {}
})
const appointTime = ref<any>({
    year: '',
    date: '',
    start_time: '',
    end_time: ''
})
const userRemark = ref<string | null>('')
const addressId = ref<number | string | null>('')
const goodsForm = ref<any>({
    goods_num: '',
    id: ''
})

const payState = reactive({
    orderId: '',
    from: '',
    showPay: false,
    showCheck: false,
    redirect: '/pages/order_buy/index'
})

// 预约上门时间
const appoint = computed(() => {
    if (!appointTime.value.date) return '请选择时间'
    return `${appointTime.value.date} ${appointTime.value.start_time}-${appointTime.value.end_time}`
})

// 优惠券弹窗
const showCoupons = ref(false)
const selectCoupon = ref(0)

// 初始化下单数据
const initPlaceOrder = async (): Promise<void> => {
    try {
        orderData.value = await apiInitOrder({
            goodsId: goodsForm.value.id,
            goodsNum: goodsForm.value.goods_num
        })
        addressId.value = orderData.value.userAddressDetailVo?.id
    } catch (error) {
        uni.$u.toast(error)
    }
}

// 1. 确认提交订单
const { lockFn: onSubmitOrder } = useLockFn(async () => {
    const modal: any = await uni.showModal({
        title: '温馨提示',
        content: '是否确认下单?'
    })
    if (!modal.confirm) return
    handlePlaceOrder()
})

// 2. 下单处理
const handlePlaceOrder = async (): Promise<void> => {
    if (!addressId.value) return uni.$u.toast('请先去选择地址')
    if (orderData.value.totalPrice <= 0) return uni.$u.toast('订单金额需大于0')
    const params = {
        appointTimeStart:
            Date.parse(
                `${appointTime.value.year}/${appointTime.value.date.replace(/-/g, '/')} ${
                    appointTime.value.start_time
                }`
            ) / 1000,
        appointTimeEnd:
            Date.parse(
                `${appointTime.value.year}/${appointTime.value.date.replace(/-/g, '/')} ${
                    appointTime.value.end_time
                }`
            ) / 1000,
        goodsId: goodsForm.value.id,
        orderAmount: orderData.value.totalPrice,
        orderTerminal: 1,
        orderType: 1, // 普通订单
        payWay: 1, // 临时
        staffId: 1, // 临时
        totalAmount: orderData.value.totalPrice,
        totalNum: goodsForm.value.goods_num,
        userRemark: userRemark.value,
        addressId: addressId.value
    }
    try {
        const data = await apiPlaceOrder({ ...params })
        payState.orderId = data.id
        payState.from = 'order'
        payState.showPay = true
    } catch (err) {
        console.log('创建订单', err)
    }
}

const handlePayResult = async () => {
    payState.showPay = false
    payState.showCheck = false
    uni.redirectTo({
        url: `/pages/order/index?type=0`
    })
}

// 跳转页面方法
const goPage = (url: string) => {
    uni.navigateTo({
        url
    })
}

onLoad(async (options: any) => {
    const parseObj = JSON.parse(decodeURIComponent(options.params))
    // 获取商品详情传来的参数
    const { goodsData, appointData } = parseObj
    goodsForm.value = goodsData
    appointTime.value = appointData
    // 监听上门时间选择
    uni.$on('appointTime', (event) => {
        appointTime.value = event
    })
    uni.$on('address', (event) => {
		orderData.value.userAddressDetailVo = event
		addressId.value = event.id
		return
    })
    // 初始化订单信息
    await initPlaceOrder()
    if (options.checkPay == 'true') {
        payState.orderId = options.order_id
        payState.from = 'order'
        payState.showCheck = true
    }
})
</script>

<style lang="scss">
.order_buy {
    padding: 40rpx 24rpx;
    background: linear-gradient(to bottom, #f36161 200rpx, transparent 0);

    .card {
        padding: 24rpx;
        margin-bottom: 20rpx;
        background-color: #fff;
        border-radius: 10rpx;

        &--header {
            padding-bottom: 20rpx;
        }
        .title {
            color: rgba(16, 16, 16, 1);
            font-size: 32rpx;
            .num {
                font-size: 28rpx;
                color: #666;
            }
        }
    }

    .goods-item {
        display: flex;
        &--name {
            width: 430rpx;

            // line-1
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }

    .footer {
        left: 0;
        bottom: 0;
        width: 100%;
        position: fixed;
        padding: 20rpx 30rpx;
        background-color: #ffffff;
        box-shadow: 2rpx 2rpx 22rpx rgba($color: #000000, $alpha: 0.2);
        padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);

        .btn {
            width: 320rpx;
            height: 100%;
        }
    }
}
.coupons {
    background-color: #f6f6f6;

    &-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 100rpx;
        padding: 0 30rpx;
        font-weight: 500;
        font-size: 28rpx;
        background-color: #ffffff;
    }

    &-main {
        padding: 20rpx;

        .coupons-item {
            &:nth-child(n + 2) {
                margin-top: 20rpx;
            }
        }
    }
}
</style>
