<template>
    <view class="order_buy">
        <!-- Main Start -->
        <view class="card flex flex-col gap-[30rpx] py-[20rpx]">
            <!-- 地址卡片 -->
            <view @click="goPage('/bundle/pages/user_address/index?type=true')">
                <view class="card--header flex justify-between items-center gap-[2rpx]">
                    <template v-if="!addressSelect">
                        <view>请选择地址</view>
                    </template>
                    <template v-else>
                        <view class="title text-black font-bold">
                            {{ addressSelect.province }}
                            {{ addressSelect.city }}
                            {{ addressSelect.district }}
                            {{ addressSelect.address }}
                        </view>
                    </template>
                    <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
                </view>
                <template v-if="addressSelect">
                    <view class="text-[28rpx] text-[#666]">
                        <text class="mr-[28rpx]">{{ addressSelect.contact }}</text>
                        <text>{{ addressSelect.mobile }}</text>
                    </view>
                </template>
            </view>
            <!-- 上门时间 -->
            <view
                class="flex justify-between items-center"
                @click="
                    goPage(
                        `/bundle/pages/appoint_time/index?appointTime=${JSON.stringify(
                            appointTime
                        )}&goodsId=${orderData.goodsId}`
                    )
                "
            >
                <view class="normal text-base font-medium">上门时间</view>
                <view class="flex item-center">
                    <text class="mr-[20rpx] text-sm text-red-600 font-bold text-[#1869FF]">
                        {{ appoint }}
                    </text>
                    <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
                </view>
            </view>
        </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
                            :goodsData="converItem(orderData)"
                            :priceType="orderData.priceType"
                            :desc="orderData.unitName"
                        ></price>
                    </view>
                </view>
            </view>

            <!-- 优惠券 -->
            <!-- <view class="card flex justify-between coupon" @click="handleNavigateUseCoupon">
                <view class="coupon__title">
                    <view class="normal text-base font-medium">优惠券</view>
                    <text class="strong" v-if="isMaxCouponMoney">最大优惠</text>
                </view>
                <view class="flex">
                    <block>
                        <text class="mr-[20rpx] text-sm text-black" :class="[isCouponMoney ? 'money' : 'nomoney']">
                            {{ parseCouponMoney }}
                        </text>
                    </block>
                    <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
                </view>
            </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 flex justify-between normal text-base">
            <view class="font-medium">服务金额</view>
            <view>{{ `¥${orderData.totalPrice}` }}</view>
        </view> -->
        <!-- Main End -->

        <!-- Footer Start -->
        <view class="footer flex flex-col gap-[12rpx]">
            <view class="text-warning flex items-center gap-[8rpx]">
                <u-icon name="info-circle" size="34" color="#f9ae3d"></u-icon>
                最终价格需与服务人员当面确认，平台不代收费用
            </view>
            <view class="flex justify-between items-center">
                <!-- <view class="text-primary">
                <text class="text-base">需支付：¥</text>
                <text class="font-medium text-4xl">{{ computeOrderTotalPrice }}</text>
            </view> -->
                <view class="btn">
                    <button
                        class="custom-button-bgColor text-lg text-white leading-[80rpx] h-[80rpx]"
                        @tap="onSubmitOrder"
                    >
                        提交订单
                    </button>
                </view>
            </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="payState?.orderAmount"
            :from="payState.from"
            :redirect="payState.redirect"
            @success="handlePayResult"
            @close="handlePayResult"
            @fail="handlePayResult"
        />

        <!-- Footer End -->
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, shallowRef, unref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { apiPlaceOrder, apiInitOrder } from '@/api/order'
import Price from '@/components/price/index.vue'
import { useLockFn } from '@/hooks/useLockFn'
import { apiCouponMaxMoney } from '@/api/coupon'
import { router } from '@/utils/util'
import { OrderStatusEnum } from '@/enums/appEnums'
import { apiAddressLists } from '@/api/user'

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 addressSelect = ref<object | null>(null) // 存档用户选择的地址，默认从后台初始化中取得
const goodsForm = ref<any>({
    goods_num: '',
    id: ''
})

const payState = reactive({
    sn: '',
    orderId: '',
    from: '',
    showPay: false,
    showCheck: false,
    redirect: '/pages/order_buy/index',
    orderAmount: 0
})
const originMaxCouponMoney = ref(0) //原始最大优惠
const maxCouponMoney = ref(0) //最大优惠面额
const couponInfo = ref<any>({}) //选中优惠券信息
const availableCount = ref(0) //可用数量
const isCouponMoney = computed(() => unref(maxCouponMoney) > 0)
const isMaxCouponMoney = computed(
    () => unref(maxCouponMoney) > 0 && unref(maxCouponMoney) >= unref(originMaxCouponMoney)
)
/**
 * 1、无优惠 => 无可用 => 0
 * 2、有优惠并选择 => -￥xx元 => x元
 * 3、有优惠但无选择 => x张可用 => -1
 */
const parseCouponMoney = computed(() => {
    return unref(maxCouponMoney) === 0
        ? '无可用'
        : unref(maxCouponMoney) === -1
        ? `${unref(availableCount)}张可用`
        : `-￥${unref(maxCouponMoney).toFixed(2)}`
})
/**1、总金额：0.01 < 优惠面额：20
 * 2、总金额：21 > 优惠面额: 20
 * 3、总金额：20 = 优惠面额：20
 */
// const computeOrderTotalPrice = computed(() => {
//     return unref(orderData).totalPrice < unref(maxCouponMoney)
//         ? unref(orderData).totalPrice
//         : (unref(isCouponMoney)
//             ? unref(orderData).totalPrice - unref(maxCouponMoney)
//             : unref(orderData).totalPrice)
// })
const computeOrderTotalPrice = computed(() => {
    return unref(orderData).totalPrice < unref(maxCouponMoney)
        ? 0
        : unref(isCouponMoney)
        ? (unref(orderData).totalPrice - unref(maxCouponMoney)).toFixed(2)
        : unref(orderData).totalPrice
})

// 预约上门时间
const appoint = computed(() => {
    if (!appointTime.value.date) return '请选择时间'
    else
        return `${appointTime.value.date} ${appointTime.value.start_time}-${appointTime.value.end_time}`
})
const converItem = computed(() => item => {
    const { price, minPrice, maxPrice } = item
    return {
        ...item,
        goodsPrice: price,
        priceRange: `${minPrice}-${maxPrice}`
    }
})

/**点击优惠券跳转 */
const handleNavigateUseCoupon = () => {
    const url = '/bundle/pages/coupon_order/coupon_order'
    const selectedItem = JSON.stringify(unref(couponInfo))
    const params = `?goodsId=${unref(goodsForm).id}&goodsCategoryId=${
        unref(orderData).goodsCategoryId
    }&selectCoupon=${selectedItem}`
    router(url + params)
}
// 初始化下单数据
const initPlaceOrder = async (): Promise<void> => {
    try {
        orderData.value = await apiInitOrder({
            goodsId: goodsForm.value.id,
            goodsNum: goodsForm.value.goods_num
        })
        console.log('orderData.value', orderData.value)

        if (addressSelect.value == null) {
            addressSelect.value = orderData.value.userAddressDetailVo
        }
        addressId.value = addressSelect.value?.id
    } catch (error) {
        uni.$u.toast(error)
    }
}

// 1. 确认提交订单
const { lockFn: onSubmitOrder } = useLockFn(async () => {
    if (!addressId.value) return uni.$u.toast('请先去选择地址')
    if (unref(appointTime).end_time === '') return uni.$u.toast('请选择上门时间')
    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,
        couponId: unref(couponInfo).id,
        goodsCategoryId: unref(orderData).goodsCategoryId
    }
    try {
        const data = await apiPlaceOrder({ ...params })
        payState.orderId = data.id
        payState.from = data.from
        payState.sn = data.sn
        payState.orderAmount = data.orderAmount
        // payStatus: 0//未支付 1：已支付
        if (data.payStatus === OrderStatusEnum.PAYMENNT) {
            handlePayResult()
        } else {
            payState.showPay = true
        }
    } catch (err) {
        console.log('创建订单', err)
    }
}

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

// 跳转页面方法
const goPage = (url: string) => {
    uni.navigateTo({
        url
    })
}
// 获取优惠金额
const getCouponMaxMoney = async () => {
    try {
        const params = {
            goodsId: unref(goodsForm).id,
            goodsCategoryId: unref(orderData).goodsCategoryId
        }
        const data = await apiCouponMaxMoney(params)
        couponInfo.value = data
        maxCouponMoney.value = data.money ?? 0
        originMaxCouponMoney.value = data.money ?? 0
    } catch (error) {}
}
onShow(() => {
    apiAddressLists({ pageNo: 1, pageSize: 10 }).then(res => {
        if (res.lists.length === 0) {
            addressSelect.value = null
            initPlaceOrder()
        }
    })
    // initPlaceOrder()
})
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 => {
        addressSelect.value = event
        addressId.value = event.districtId // 获取地址id传来的参数，可以在页面加载时获取到
        initPlaceOrder()
    })
    uni.$on('selectCoupon', event => {
        const { selectedCouponInfo, availableCount: count } = event
        couponInfo.value = selectedCouponInfo
        maxCouponMoney.value = selectedCouponInfo.money ?? -1
        availableCount.value = count
    })
    // 初始化订单信息
    await initPlaceOrder()
    if (options.checkPay == 'true') {
        payState.orderId = options.order_id
        payState.from = 'order'
        payState.showCheck = true
    }
    // 获取是否有优惠
    // getCouponMaxMoney()
    uni.$on('resetAddress', event => {
        console.log(event)

        addressSelect.value = event
    })
})
</script>

<style lang="scss">
.order_buy {
    padding: 40rpx 24rpx;
    // background: linear-gradient(to bottom, $u-type-primary 200rpx, transparent 0);
    background-image: url('~@/static/images/order-detail-bg.png');
    background-size: 100% 400rpx;
    background-repeat: no-repeat;

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

        &--header {
            padding-bottom: 16rpx;
        }

        .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;
            width: 100%;
            height: 100%;
        }
    }

    .coupon {
        display: flex;
        align-items: center;
        margin: 0;
        padding: 30rpx 0 0;

        &__title {
            display: flex;
            align-items: center;

            .strong {
                margin-left: 20rpx;
                padding: 6rpx 12rpx;
                border: 1px solid #fc4c34;
                border-radius: 6px;
                font-size: 24rpx;
                color: #fc4c34;
            }
        }

        .money {
            color: #fc4c34;
        }

        .nomoney {
            color: #777;
        }
    }
}

.time-strong {
    color: #cc463d;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 120rpx !important;
    padding: 0 24rpx !important;
}

.address {
    color: #e14343;
    font-size: 32rpx;
}
</style>
