<template>
    <view :style="themeColor()" class="payment-wrap">
        <view class="payment-body min-h-[100vh]">
            <!-- #ifdef MP -->
            <top-tabbar :data="topTabbarData" :scrollBool="topTabarObj.getScrollBool()" :mustFill="true" />
            <!-- #endif -->
            <view class="pt-[30rpx] sidebar-margin payment-bottom">
                <!-- 配送方式 -->
                <view class="mb-[var(--top-m)] rounded-[var(--rounded-big)] bg-white"
                    :style="{ backgroundImage: `url(${img('https://v6.site.niucloud.com/addon/shop/payment/head_bg.png')})`, backgroundSize: '100%', backgroundRepeat: 'no-repeat', backgroundPosition: 'bottom' }">
                    <view class="min-h-[140rpx] flex items-center px-[30rpx]">
                        <!-- 收货地址 -->
                        <view class="w-full" @click="toSelectAddress">
                            <view v-if="addressList.length > 0" class="pt-[20rpx] pb-[30rpx] flex items-center">
                                <image class="w-[60rpx] h-[60rpx] mr-[20rpx] flex-shrink-0"
                                    :src="img('https://v6.site.niucloud.com/addon/shop/payment/position_01.png')"
                                    mode="aspectFit" />
                                <view class="flex flex-col overflow-hidden">
                                    <text
                                        class="text-[26rpx] text-[var(--text-color-light9)] mt-[16rpx] truncate max-w-[536rpx]">{{
                                            addressData.provincialCityCountry
                                        }}</text>
                                    <text
                                        class="font-500 text-[30rpx] mt-[14rpx] text-[#333] truncate max-w-[536rpx]">{{
                                            addressData.address }}</text>
                                    <view
                                        class="flex items-center text-[26rpx] text-[var(--text-color-light6)] mt-[16rpx]">
                                        <text class="mr-[16rpx]">{{ addressData.consignee }}</text>
                                        <text>{{ addressData.phone }}</text>
                                    </view>
                                </view>
                                <text
                                    class="ml-auto nc-iconfont nc-icon-youV6xx text-[26rpx] text-[var(--text-color-light9)]"></text>
                            </view>
                            <view v-else class="flex items-center">
                                <image class="w-[26rpx] h-[30rpx] mr-[10rpx]"
                                    :src="img('https://v6.site.niucloud.com/addon/shop/payment/position_02.png')"
                                    mode="aspectFit" />
                                <text class="text-[28rpx]">添加收货地址</text>
                                <text
                                    class="nc-iconfont nc-icon-youV6xx text-[26rpx] text-[var(--text-color-light9)] ml-auto"></text>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="mb-[var(--top-m)] card-template p-[0] pb-[var(--pad-top-m)]">
                    <view class="pt-[var(--pad-top-m)] pb-[14rpx]">
                        <template v-for="(item, index) in cartList" :key="index">
                            <view class="px-[var(--pad-sidebar-m)]"
                                :class="{ 'mb-[20rpx]': (Number(index) + 1) != cartList.length }">
                                <view class="flex">
                                    <u--image radius="var(--goods-rounded-big)" width="180rpx" height="180rpx"
                                        :src="img(item.productImage)" model="aspectFill">
                                        <template #error>
                                            <image
                                                class="w-[180rpx] h-[180rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
                                                :src="img('static/resource/images/diy/shop_default.jpg')"
                                                mode="aspectFill" />
                                        </template>
                                    </u--image>
                                    <view class="flex flex-1 w-0 flex-col justify-between ml-[20rpx] py-[6rpx]">
                                        <view class="line-normal">
                                            <view class="truncate text-[#303133] text-[28rpx] leading-[32rpx]">{{
                                                item.itemName }}</view>

                                        </view>


                                        <view class="flex justify-between items-baseline">
                                            <view
                                                class="text-[var(--price-text-color)] flex items-baseline  price-font">
                                                <text class="text-[24rpx] font-500 mr-[4rpx]">￥</text>
                                                <text class="text-[40rpx] font-500">{{
                                                    parseFloat(item.memberPrice).toFixed(2).split('.')[0] }}</text>
                                                <text class="text-[24rpx] font-500">.{{
                                                    parseFloat(item.memberPrice).toFixed(2).split('.')[1] }}</text>
                                            </view>
                                            <view class="font-400 text-[28rpx] text-[#303133]">
                                                <text>x</text>
                                                <text>{{ item.productNum }}</text>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </template>

                    </view>
                    <!-- 买家留言 -->
                    <view class="bg-white flex items-center leading-[30rpx] px-[var(--pad-sidebar-m)] mt-[30rpx]"
                        @click="toLeaveMessage">
                        <view class="text-[28rpx] w-[150rpx] text-[#303133]">采购事由</view>
                        <view class="flex-1 text-[#303133] flex items-center justify-center">
                            <view class="flex-1 w-0 text-right truncate">
                                <text class="text-[28rpx]"
                                    :style="{ 'color': form.purchaseReason ? '#303133' : '#999999' }">{{
                                        form.purchaseReason ?
                                            form.purchaseReason : '请输入采购事由' }}</text>
                            </view>
                            <text
                                class="ml-auto text-[28rpx] nc-iconfont nc-icon-youV6xx  text-[var(--text-color-light9)]"></text>
                        </view>
                    </view>
                    <!-- 发票 -->
                    <view class="flex items-center text-[#303133] leading-[30rpx] mt-[30rpx] px-[var(--pad-sidebar-m)]">
                        <view class="text-[28rpx] w-[150rpx] text-[#303133]">
                            费用类型</view>
                        <view class="flex-1 w-0 text-right truncate">
                            <text class="text-[28rpx]">日常物资采购</text>
                        </view>
                    </view>

                </view>

                <view class="mb-[var(--top-m)] card-template p-[0] pb-[var(--pad-top-m)]">
                    <view
                        class="flex items-center text-[#303133] leading-[30rpx] mt-[10rpx] px-[var(--pad-sidebar-m)] pt-[30rpx]">
                        <view class="text-[28rpx] w-[150rpx] text-[#303133]">
                            订单备注</view>
                        <view class="flex-1 w-0 text-right truncate">
                            <input class="layout-two-content no-flex" placeholder="请输入订单备注"
                                placeholderClass="layout-two-input-placeholder" v-model="form.remark" />
                        </view>
                    </view>
                    <view class="flex items-center text-[#303133] leading-[30rpx] mt-[30rpx] px-[var(--pad-sidebar-m)]"
                        @click="calendarShow = true">
                        <view class="text-[28rpx] w-[150rpx] text-[#303133]">
                            配送日期</view>
                        <view class="flex-1 w-0 text-right truncate">
                            <text class="text-[28rpx]"
                                :style="{ 'color': form.deliveryDate ? '#303133' : '#999999' }">{{
                                    form.deliveryDate ? form.deliveryDate : '请选择配送日期' }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true" zIndex="10">
                <view class="flex-1 flex items-center justify-between pl-[30rpx] pr-[20rpx]">
                    <view class="flex items-baseline">
                        <text class="text-[26rpx] text-[#333] leading-[32rpx]">合计：</text>
                        <view class="inline-block">
                            <text
                                class="text-[26rpx] font-500 text-[var(--price-text-color)] price-font leading-[30rpx]">￥</text>
                            <text
                                class="text-[44rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">{{
                                    parseFloat(allMoney).toFixed(2).split('.')[0] }}</text>
                            <text
                                class="text-[26rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">.{{
                                    parseFloat(allMoney).toFixed(2).split('.')[1] }}</text>
                        </view>
                    </view>
                    <button
                        class="w-[196rpx]  h-[70rpx] font-500 text-[26rpx] leading-[70rpx] !text-[#fff] m-0  rounded-full primary-btn-bg remove-border"
                        hover-class="none" @click="create">提交订单</button>
                </view>
            </u-tabbar>
        </view>
        <!-- 地址 -->
        <com-Address-list ref="addressRef" @confirm="confirmAddress" back="/addon/shop/pages/order/payment" />
        <message-open ref="messageOpenRef" @submit="confirmMessage" :default-message="form.purchaseReason" />
        <up-calendar :minDate="minDate" :show="calendarShow" mode="single" color="var(--primary-color)"
            @confirm="calendarConfirm" @close="calendarShow = false"></up-calendar>
        <pay ref="payRef" @close="payClose" />
    </view>
</template>
<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { topTabar } from '@/utils/topTabbar'
import { redirect, img, mobileHide } from '@/utils/common'
import comAddressList from './components/address-list/address-list.vue'
import { getAddressList } from '@/app/api/member'
import { getCartGoodsList } from '@/addon/shop/api/cart'
import messageOpen from './components/message-open/message-open.vue'
import diyForm from '@/addon/components/diy-form/index.vue';
import { orderCreateCalculate, orderCreate, getLocal } from '@/addon/shop/api/order'
const topTabarObj = topTabar()
let topTabbarData = topTabarObj.setTopTabbarParam({ title: '待付款订单' })
const calendarShow: any = ref(false)
const payRef: any = ref(null)
const orderId: any = ref(null)
const addressList: any = ref([])
const addressData: any = ref({})
const addressRef = ref<any>(null)
const cartList = ref<any>([])
const minDate = ref<any>('')
const allMoney = ref<any>(0);
const createLoading = ref(false)

const form = ref<any>({
    shippingAddressId: '',
    deliveryDate: '',
    expenseType: '0',
    purchaseReason: '',
    remark: '',
    shippingFee: 0,
    // 下单方式  1为购物车下单  2为直接下单
    placeOrderType: 1,
    productShoppingCartId: []
});

onShow(() => {
    getCartGoodsListFn()
    getAddressListFn()
    getMinDate();
})

const getMinDate = () => {
    const now = new Date();
    // 1. 获取年份
    const year = now.getFullYear();
    // 2. 获取月份 (注意：需要 +1，且建议补零)
    const month = String(now.getMonth() + 1).padStart(2, '0');
    // 3. 获取日期 (建议补零)
    const day = String(now.getDate()).padStart(2, '0');
    // 4. 拼接结果
    const todayStr = `${year}-${month}-${day}`;
    minDate.value = todayStr;
}

const getCartGoodsListFn = () => {
    allMoney.value = 0;
    const cart_ids = uni.getStorageSync('orderCreateData').cart_ids
    getCartGoodsList({}).then((res: any) => {
        const data = res.rows
        cartList.value = []
        data.forEach((item: any) => {
            if (cart_ids.includes(item.shoppingCartId)) {
                form.value.productShoppingCartId.push(item.shoppingCartId)
                cartList.value.push(item)
                allMoney.value = allMoney.value + Number(item.memberPrice * item.productNum);
            }
        })
    }).catch((err) => { })
}

const getAddressListFn = () => {
    getAddressList({}).then((res: any) => {
        addressList.value = res.rows
        if (res.rows.length > 0) {
            form.value.shippingAddressId = res.rows[0].id;
            addressData.value = res.rows[0]
            addressList.value.forEach((item: any) => {
                if (item.defaultAddress == 0) {
                    form.value.shippingAddressId = item.id;
                    addressData.value = item
                }
            });
        }
    }).catch(() => {
    })
}

/**
 * 选择地址
 */
const toSelectAddress = () => {
    let data: any = {};
    data.id = form.value.shippingAddressId;
    addressRef.value.open(data);
}
const confirmAddress = (data: any) => {
    addressData.value = data
    form.value.shippingAddressId = data.id;
}

// 留言
const messageOpenRef = ref()
const toLeaveMessage = () => {
    messageOpenRef.value.open();
}

const confirmMessage = (message: string) => {
    form.value.purchaseReason = message
}

//日期
const calendarConfirm = (data: any) => {
    form.value.deliveryDate = data[0]
    calendarShow.value = false
}


/**
 * 订单创建
 */
const create = () => {
    if (!form.value.shippingAddressId) {
        uni.showToast({ title: '请选择收货人', icon: 'none' })
        return
    }
    if (!form.value.purchaseReason) {
        uni.showToast({ title: '请输入采购事由', icon: 'none' })
        return
    }
    if (!form.value.deliveryDate) {
        uni.showToast({ title: '请选择配送日期', icon: 'none' })
        return
    }
    if (createLoading.value) return
    createLoading.value = true
    orderCreate(form.value).then((res: any) => {
        orderId.value = res.data
        payRef.value?.open(res.data, `/addon/shop/pages/order/detail?order_id=${res.data}`)
    }).catch((err) => {
        createLoading.value = false
    })

}

/**
 * 支付弹窗关闭
 */
const payClose = () => {
    redirect({ url: '/addon/shop/pages/order/detail', param: { order_id: orderId }, mode: 'redirectTo' })
}
</script>


<style lang="scss" scoped>
.head-tab {
    .head-tab-item {
        .tab-image {
            left: 50%;
            transform: translateX(-50%);
        }

        &:nth-child(1).active {
            view {
                padding-right: 40rpx;
            }
        }

        &:nth-child(2) {
            .tab-image {
                width: 312rpx;
            }
        }

        &:nth-child(3).active {
            view {
                padding-left: 30rpx;
            }
        }

        &.active {
            view {
                font-weight: bold;
                color: var(--primary-color);
            }
        }

        .tab-img {
            left: 50%;
            transform: translateX(-50%);
        }

    }
}

:deep(.u-alert) {
    padding: 6rpx 16rpx !important;
    display: inline-block !important;
}

.alert-wrap {
    display: inline-block !important;

    :deep(.u-fade-enter-active) {
        display: inline-block !important;
    }
}

.text-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.line-normal {
    line-height: normal;
}

.bg-color {
    background: linear-gradient(94deg, var(--primary-help-color2) 0%, var(--primary-color) 69%), var(--primary-color);
}

.payment-bottom {
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.payment-wrap {
    background: linear-gradient(180deg, transparent 0%, transparent 80%, var(--page-bg-color) 100%);
}

.payment-body {
    --shop-payment-header-color: #F42612; // 待支付头部颜色
    --shop-payment-header-tab-color: #FEEAE9; // 待支付头部颜色
    /*  #ifdef MP  */
    background: linear-gradient(180deg, transparent 0%, transparent 10%, var(--page-bg-color) 30%);
    /*  #endif  */
    /*  #ifdef H5  */
    background: linear-gradient(180deg, transparent 0%, var(--page-bg-color) 25%);

    /*  #endif  */
    &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        z-index: -1;
        /*  #ifdef MP  */
        height: 560rpx;
        background: linear-gradient(180deg, var(--shop-payment-header-color) 20%, var(--page-bg-color) 90%), var(--page-bg-color);
        /*  #endif  */
        /*  #ifdef H5  */
        height: 360rpx;
        background: linear-gradient(180deg, var(--shop-payment-header-color) 0%, var(--page-bg-color) 90%), var(--page-bg-color);
        /*  #endif  */
    }
}
</style>
