<template>
    <view class="book-order">
        <!-- 取货地址部分 -->
        <view class="section-card">
            <view class="flex-a flex-j-b mb-20" @click="handleAddress" v-if="defaultAddr.id">
                <image src="/static/address/address.png" style="width: 40rpx; height: 40rpx"></image>
                <view class="flex-d flex-1 ml-24" style="margin-right: 90rpx">
                    <view class="flex-a flex-j-b mb-10">
                        <view :style="titleStyle">发货人：{{ defaultAddr.name }}</view>
                        <view :style="titleStyle">{{ defaultAddr.mobile }}</view>
                    </view>
                    <view :style="titleStyle">地址：{{ defaultAddr.fullAddress }}</view>
                </view>
                <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
            </view>

            <view class="flex-a flex-j-b" @click="handleAddress" v-else>
                <view class="flex-a">
                    <u-icon name="plus-circle-fill" :size="48" color="#38C148" top="2"></u-icon>
                    <view :style="titleStyle" class="ml-10 font-30">取货地址</view>
                    <text class="u-required">*</text>
                </view>

                <view class="flex-a">
                    <view :style="titleStyle" class="ml-10">请添加</view>
                    <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
                </view>
            </view>

            <view class="free-pickup mb-20 mt-20">
                <view class="pickup-title">免费上门取货</view>
                <view class="pickup-desc">书嗨将预约指定快递上门取件，邮费由书嗨承担</view>
            </view>
            <view class="flex-a flex-j-b time-card" style="padding: 0 10rpx" @click="showTimePicker = true">
                <view class="flex-a">
                    <view :style="titleStyle" class="ml-10 font-28">取件时间</view>
                    <text class="u-required">*</text>
                </view>

                <view class="flex-a">
                    <view v-if="selectedTime.day" :style="titleStyle" class="ml-10">{{ selectedTime.day }}
                        {{ selectedTime.time }}
                    </view>
                    <view v-else :style="titleStyle" class="ml-10">请选择快递上门取件时间</view>
                    <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
                </view>
            </view>

            <view class="flex-a flex-j-b time-card mt-20" style="padding: 0 10rpx" @click="showVerifyPeriodPicker = true">
                <view class="flex-a">
                    <view :style="titleStyle" class="ml-10 font-28">结算时效</view>
                    <text class="u-required">*</text>
                </view>

                <view class="flex-a">
                    <view v-if="verifyPeriodLabel" :style="titleStyle" class="ml-10">{{ verifyPeriodLabel }}</view>
                    <view v-else :style="titleStyle" class="ml-10">请选择结算时效</view>
                    <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
                </view>
            </view>
        </view>

        <!-- 快递备注部分 -->
        <view class="section-card">
            <view class="flex-a flex-j-b mb-20" @click="showExpressPicker">
                <view class="flex-a">
                    <view :style="titleStyle" class="font-28">快递备注</view>
                </view>

                <view class="flex-a">
                    <view :style="titleStyle" class="ml-10">{{ submitData.expressDelivery || "请选择" }}</view>
                    <u-icon name="arrow-right" :size="28" color="#666" top="3"></u-icon>
                </view>
            </view>
            <view class="express-desc">请从【顺丰】或【京东】中选择可正常收寄的快递，如您不选择，则由系统根据区域情况自动分配</view>
        </view>

        <!-- 书籍列表 -->
        <view class="book-list">
            <book-item v-for="book in books" :key="book.id" :book="book"></book-item>
        </view>

        <!-- 底部栏 -->
        <view class="bottom-bar">
            <view class="agreement">
                <u-checkbox v-model="agreed" shape="circle">
                    <text class="agreement-text">我已阅读并同意</text>
                    <text class="agreement-link" @click="goToAgreement">《书嗨用户协议》</text>
                </u-checkbox>
            </view>
            <view class="order-summary">
                <view class="total">
                    共<text class="price">{{ totalNum }}</text>件 预估回收价
                    <text class="price">¥{{ totalRecycleMoney }}</text>
                    <u-icon name="question-circle-fill" color="#333333" size="36" @click="showRules"></u-icon>
                </view>
                <u-button type="primary" @click="submitOrder" :custom-style="{ margin: 0,backgroundColor:'#38C148' }">提交订单</u-button>
            </view>
        </view>

        <!-- 添加快递选择器 -->
        <u-picker v-model="showPicker" mode="selector" :range="expressList" @confirm="onExpressConfirm"
            @cancel="showPicker = false" range-key="name"></u-picker>

        <pickup-time-picker :show.sync="showTimePicker" @confirm="onTimeConfirm"></pickup-time-picker>

        <verify-period-picker
            :show.sync="showVerifyPeriodPicker"
            :value="submitData.verifyPeriodDays"
            @confirm="onVerifyPeriodConfirm"
        ></verify-period-picker>

        <submit-confirm ref="submitConfirmDialog" @confirm="handleConfirmSubmit"></submit-confirm>
    </view>
</template>

<script>
    import bookItem from "@/pages-home/components/BookItem.vue";
    import pickupTimePicker from "@/pages-home/components/PickupTimePicker.vue";
    import VerifyPeriodPicker from "@/pages-home/components/VerifyPeriodPicker.vue";
    import SubmitConfirm from "@/pages-home/components/SubmitConfirm.vue";

    export default {
        components: {
            bookItem,
            pickupTimePicker,
            VerifyPeriodPicker,
            SubmitConfirm,
        },
        data() {
            return {
                titleStyle: {
                    "font-family": "PingFang SC",
                    "font-weight": 400,
                    color: "#333333",
                },
                agreed: false,
                books: [],

                showPicker: false,
                expressList: [],
                showTimePicker: false,
                showVerifyPeriodPicker: false,
                selectedTime: {},
                verifyPeriodLabel: "",
                defaultAddr: {},

                submitData: {
                    expressDelivery: "",
                    orderId: "",
                    addressId: "",
                    schedulePickupStartTime: "",
                    schedulePickupEndTime: "",
                    expressDelivery: "",
                    remark: "",
                    verifyPeriodDays: null,
                },
                totalNum: 0,
                totalRecycleMoney: 0,
            };
        },
        methods: {
            showRules() {
                uni.navigateTo({
                    url: '/pages-mine/pages/rules-for-sellbooks'
                })
            },
            // 结算时效选择
            onVerifyPeriodConfirm(data) {
                this.submitData.verifyPeriodDays = data.verifyPeriodDays;
                this.verifyPeriodLabel = data.label;
            },

            //时间选择
            onTimeConfirm(data) {
                this.selectedTime = data;
                //格式化提交数据的时间
                let date = this.$u.timeFormat(data.date, "yyyy-mm-dd");
                let times = data.time.split("-");

                this.submitData.schedulePickupStartTime = `${date} ${times[0]}`;
                this.submitData.schedulePickupEndTime = `${date} ${times[1]}`;
                console.log(date, this.submitData, "data");
            },

            //打开快递选择器
            showExpressPicker() {
                this.showPicker = true;
            },
            //确认选择快递
            onExpressConfirm(e) {
                if (!e.length) return;
                let item = this.expressList[e[0]];
                this.submitData.expressDelivery = item.name;
                this.showPicker = false;
            },
            //添加或者选择地址
            handleAddress() {
                uni.navigateTo({
                    url: `/pages-mine/pages/address/list?id=${this.defaultAddr.id}&isSelect=1`,
                });
            },

            submitOrder() {
                if (!this.submitData.addressId) {
                    this.$u.toast("请选择取货地址");
                    return;
                }
                if (!this.selectedTime.day) {
                    this.$u.toast("请选择取件时间");
                    return;
                }
                if (!this.submitData.verifyPeriodDays) {
                    this.$u.toast("请选择结算时效");
                    return;
                }
                if (!this.agreed) {
                    this.$u.toast("请先同意用户协议");
                    return;
                }
                // 显示确认弹窗
                this.$refs.submitConfirmDialog.openPopup();
            },

            // 确认提交订单
            handleConfirmSubmit() {
                // 处理订单提交
                uni.$u.http.post("/token/order/submitOrder", this.submitData).then((res) => {
                    if (res.code == 200) {
                        uni.navigateTo({
                            url: "/pages-home/pages/order-success",
                        });
                        uni.removeStorageSync("selectAddr");
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: "none",
                        });
                    }
                });
            },
            //获取默认地址 /api/token/user/address/getDefault
            getDefaultAddress() {
                uni.$u.http.get("/token/user/address/getDefault").then((res) => {
                    if (res.code == 200) {
                        this.defaultAddr = res.data;
                        this.submitData.addressId = this.defaultAddr.id;
                    }
                });
            },
            //获取当前用户未提交订单 /api/token/order/lastOrder
            getLastOrder() {
                uni.$u.http.get("/token/order/lastOrder").then((res) => {
                    if (res.code == 200) {
                        this.books = res.data?.orderDetailList
                            ? res.data.orderDetailList?.map((v) => {
                                v.orderId = res.data.orderId;
                                return v;
                            })
                            : [];

                        this.submitData.orderId = this.books[0].orderId;
                    }
                });
            },
            //获取预提交订单
            getPreSubmitOrder() {
                let orderId = uni.getStorageSync("orderId");
                uni.$u.http.get("/token/order/preSubmit?orderId=" + orderId).then((res) => {
                    this.submitData.orderId = orderId;
                    this.defaultAddr = res.data.defaultAddress;
                    this.submitData.addressId = this.defaultAddr.id;

                    this.books = res.data.orderDetailList;
                    this.expressList = res.data.expressTypes.map((v) => ({
                        name: v,
                    }));

                    this.totalRecycleMoney = res.data.totalRecycleMoney;
                    this.totalNum = res.data.totalNum;
                });
            },
            goToAgreement() {
                uni.navigateTo({
                    url: "/pages-home/pages/user-agreement",
                });
            },
        },
        mounted() {
            this.getPreSubmitOrder();
        },

        onShow() {
            let selectAddr = uni.getStorageSync("selectAddr");
            if (selectAddr) {
                this.defaultAddr = selectAddr;
                this.submitData.addressId = selectAddr.id;
            }

            //处理从/pages-home/pages/order-success页面返回的情况，在执行返回一级页面
            let pages = getCurrentPages();
            let currentPage = pages[pages.length - 1];
            console.log(pages, currentPage, "currentPage");
            if (currentPage.route == "pages-home/pages/order-success") {
                uni.navigateBack({
                    delta: 1,
                });
            }
        },
    };
</script>

<style lang="scss">
    .book-order {
        min-height: 100vh;
        background: #f5f5f5;
        padding: 20rpx 30rpx;
        padding-bottom: calc(env(safe-area-inset-bottom) + 190rpx);
    }

    .section-card {
        background: #fff;
        margin-bottom: 20rpx;
        padding: 30rpx;
        border-radius: 10rpx;
        box-sizing: border-box;
    }

    .u-required {
        color: #ff0000;
        margin-left: 8rpx;
    }

    .mt-20 {
        margin-top: 20rpx;
    }

    .time-card {
        height: 80rpx;
        background: #f8f8f8;
        border-radius: 10rpx;
    }

    .free-pickup {
        .pickup-title {
            font-weight: bold;
            font-size: 28rpx;
            color: #333333;
            margin-bottom: 10rpx;
        }

        .pickup-desc {
            font-family: PingFang SC;
            font-weight: 400;
            font-size: 28rpx;
            color: #999999;
        }
    }

    .express-desc {
        font-size: 24rpx;
        color: #666;
        line-height: 1.4;
    }

    .bottom-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #fff;
        padding: 20rpx 30rpx;
        padding-bottom: env(safe-area-inset-bottom);

        .agreement {
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 28rpx;
            color: #333333;

            &-link {
                color: #07c160;
            }
        }

        .order-summary {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 28rpx;
            color: #999999;

            .price {
                color: #ff0000;
                margin: 0 10rpx;
            }
        }
    }
</style>
