<template>
	<view class="px32" style="padding-bottom: 200rpx;">
		<!-- 收货方式 -->
		<view class="bg-white br16 row u-m-t-32">
			<!-- <u-tabs
				:list="addressTabsList"
				:is-scroll="addressTabsList.length === 1"
				:current="addressTabsIndex"
				:active-color="primaryColor"
				bar-width="100"
				:bar-style="{ top: '100%' }"
				@change="changeDelivery"
			/> -->
			<!-- 快递配送 -->
			<view v-show="addressTabsList[addressTabsIndex]['sign'] === 'express'" class="u-flex p24 w-full"
				@click="onAddressExpress">
				<view>
					<u-icon name="map" size="48" class="right-icon"></u-icon>
				</view>
				<view class="u-flex flex1 u-row-between">
					<view class="ml10">
						<template v-if="address.id">
							<view class="md black bold">
								<text>{{ address.contact }}</text>
								<text class="ml10">{{ address.telephone }}</text>
							</view>
							<view class="xs black mt10">{{
								address.province +
								address.city +
								address.district +
								address.address
							}}</view>
						</template>
						<template v-else>
							<view>请选择收货地址</view>
						</template>
					</view>
					<view>
						<u-icon class="ml10" name="arrow-right" />
					</view>
				</view>
			</view>
			<!-- 门店自提 -->
			<!-- <view
				v-show="addressTabsList[addressTabsIndex]['sign'] === 'store'"
				class="receiving-card"
				@click="onAddressStore"
			>
				<u-image
					class="icon-md mr20"
					width="44"
					height="44"
					src="/static/images/icon_address.png"
					mode="scaleToFill"
				/>
				<view class="receiving-content">
					<template v-if="storeInfo.id">
						<text class="md black bold">{{ storeInfo.name }}</text>
						<text class="xs black mt10">{{ storeInfo.shop_address }}</text>
						<text class="xs muted mt10">
							<text>营业时间：</text>
							<text
								>{{ storeInfo.business_start_time }} -
								{{ storeInfo.business_end_time }}</text
							>
						</text>
					</template>
					<template v-else>
						<view>请选择门店地址</view>
					</template>
				</view>
				<u-icon name="arrow-right" />
			</view> -->
		</view>
		<view class="bg-white br16 row u-m-t-32 u-p-20">
			<order-goods :team="{ need: orderInfo.team_need }" :list="goodsLists" :delivery="delivery"
				:order_type="orderInfo.order_type" :imageWidth="186" :imageHeight="186" mode="confirm"></order-goods>
		</view>

		<view class="item row-between bg-white br16 row u-m-t-32 p24" @tap="showCoupon = true">
			<view>优惠券</view>
			<view class="row">
				<text class="text-default" v-if="orderInfo.discount_amount">-￥{{ orderInfo.discount_amount }}</text>
				<text v-else-if="usableCoupon.length" class="text-default">{{
					usableCoupon.length + '张可用'
				}}</text>
				<text v-else class="muted">无优惠券可用</text>
				<u-icon name="arrow-right" size="32" color="#999"></u-icon>

			</view>
		</view>

		<view class="bg-white br16 p24 u-m-t-32 nr row-between" @click="appointmentTime">
			<view>预约时间</view>
			<view class="row">
				<view class="u-m-r-10"> {{day}} , {{ time }}</view>
				<u-icon name="arrow-right" size="32"></u-icon>
			</view>
		</view>

		<view class="bg-white br16 p24 u-m-t-32">
			<view>
				备注
			</view>
			<view class="flex1 u-m-t-16 mask">
				<u-input v-model="userRemark" type="textarea"  maxlength="150"/>
			</view>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<!-- <view class="bg-white br16 p24 u-m-t-32 nr">
			<view class="row-between">
				<view class="row-center">
					<u-icon name="weixin-circle-fill" color="#28C445" size="80"></u-icon>
					<view class="u-m-l-16 lg">微信</view>
				</view>

				<view class="flex1 row-end">
					<u-radio-group v-model="pay.weixin">
						<u-radio shape="circle" :active-color="themeColor"></u-radio>
					</u-radio-group>
				</view>
			</view>
		</view> -->
		<!-- #endif -->

		<!-- #ifdef MP-ALIPAY -->
		<!-- <view class="bg-white br16 p24 u-m-t-32 nr">
			<view class="row-between">
				<view class="row-center">
					<u-icon name="zhifubao-circle-fill" color="#1477FE" size="80"></u-icon>
					<view class="u-m-l-16 lg">支付宝</view>
				</view>

				<view class="flex1 row-end">
					<u-radio-group v-model="pay.alipay">
						<u-radio shape="circle" :active-color="themeColor"></u-radio>
					</u-radio-group>
				</view>
			</view>
		</view> -->
		<!-- #endif -->

		<view class="fixed bg-white row-between px48 u-padding-top-20 u-padding-bottom-20">
			<view class="column u-text-center">
				<view class="row-center">
					<view class="count">共{{orderInfo.total_num}}件</view>
					<view class="u-m-l-8">合计：</view>
					<view class="primary" style="margin-top: -8rpx;">
						<price-format :price="orderInfo.order_amount" :subscriptSize="34" :firstSize="56" :secondSize="34"></price-format>
					</view>
				</view>
			</view>
			<view class="u-m-l-64 flex1">
				<u-button hover-class="none" @click="onSubmitOrder"
					:customStyle="{ height: '92rpx', backgroundColor: themeColor, color: '#fff', border: 'none', paddingTop: '8rpx' }"
					:hair-line="false" shape="circle">
					去支付
				</u-button>
			</view>
		</view>
		<u-popup v-model="showCoupon" border-radius="14" mode="bottom" closeable>
			<view class="pop-title row-between">
				<view class="title">优惠券</view>
			</view>
			<view v-if="showCoupon">
				<tabs :active="couponTabsIndex" :config="{ underLineWidth: 100 }">
					<tab :title="'可使用优惠券 (' + usableCoupon.length + ')'">
						<coupon-obj :list="usableCoupon" :type="0" @change="onSelectCoupon"
							:coupon-id="couponId"></coupon-obj>
					</tab>
					<tab :title="'不可用优惠券 (' + unusableCoupon.length + ')'">
						<coupon-obj :list="unusableCoupon" :type="1" @change="onSelectCoupon"></coupon-obj>
					</tab>
				</tabs>
			</view>
		</u-popup>
		<appointment-time v-model="timePopup" @close="timePopup = false" @update="handleSubmitTime" />
	</view>
</template>

<script>
import { orderBuy, getOrderCoupon, getDelivery } from '@/api/order'
import { prepay, getPayway } from '@/api/app'
import { wxpay, alipay } from '@/utils/pay'
export default {
	data() {
		return {
			timePopup: false,
			pay: {
				weixin: 0,
				alipay: 0
			},
			showLoading: false, // Loading: 显示 | 隐藏
			goods: {}, // 商品信息
			// 地址Tabs列表
			addressTabsList: [
				{
					id: 1,
					sign: 'express',
					name: '快递配送'
				},
				{
					id: 2,
					sign: 'store',
					name: '门店自提'
				}
			],
			addressTabsIndex: 0, // 地址Tabs索引
			goodsLists: [], // 商品列表
			orderInfo: {}, // 订单信息
			address: {}, // 收货地址信息
			addressId: '', // 收货地址ID
			storeInfo: {}, // 门店信息
            couponId: '', // 优惠券ID
            couponTabsIndex: 0, // 优惠券Tabs索引
			usableCoupon: [], // 优惠券--可使用
			unusableCoupon: [], // 优惠券--不可用
			showCoupon: false, // 显示优惠券Popup
            userRemark: '', // 用户留言
			type: '', // 订单类型
			day: '',
			timeId: 0,
			time: ''
		}
	},

	onLoad(options) {
		const data = JSON.parse(decodeURIComponent(options.data))
		console.log("data>>>", data);
		this.goods = data.goods
        this.type = data.type

		//#ifdef MP-WEIXIN
		this.pay.weixin = 1
		//#endif

		//#ifdef MP-ALIPAY
		this.pay.alipay = 1
		//#endif

		this.getDeliveryFun()
	},

	onUnload() {
		// 取消全局监听
		uni.$off(['selectaddress', 'store'])
	},

	methods: {
		getDeliveryFun() {
			getDelivery()
			.then(({ code, data, msg }) => {
				// 请求结果判断
				if (code != 1) throw new Error(msg)
				return data
			})
			.then((data) => {
				// 快递
				if (!data.is_express) {
					this.addressTabsList = this.addressTabsList.filter(
						(item) => item.sign !== 'express'
					)
				}
				// 自提
				if (!data.is_selffetch) {
					this.addressTabsList = this.addressTabsList.filter(
						(item) => item.sign !== 'store'
					)
				}
			})
			// 页面数据初始化
			.then(() => {
				this.handleOrderMethods('info')
				this.initCouponData()
			})
			// 监听全局事件
			.then(() => {
				uni.$on('selectaddress', (params) => {
					this.addressId = params.id
					this.handleOrderMethods('info')
				})

				uni.$on('payment', (params) => {
					setTimeout(() => {
						uni.$off('payment')
                        console.log("payment>>>", 'payment');

						if (params.result) {
							uni.redirectTo({
								url: `/pages/pay_result/pay_result?id=${params.order_id}`
							})
						} else {
							uni.reLaunch({
								url: '/pages/order/order'
							})
						}
					}, 500)
				})

				uni.$on('store', (params) => {
					this.storeInfo = params
				})
			})
			.catch((err) => {
				console.log(err)
			})
		},

		appointmentTime() {
			this.timePopup = true
		},

		// 初始化优惠券数据
		initCouponData() {
			getOrderCoupon({
				goods: this.goods
			})
			.then(({ code, data, msg }) => {
				if (code != 1) throw new Error(msg)
				return data
			})
			.then((data) => {
				this.usableCoupon = data.usable
				this.unusableCoupon = data.unusable
			})
			.catch((err) => {
				console.log(err)
			})
		},

		// 选择优惠券
        onSelectCoupon(value) {
            this.couponId = value
            this.showCoupon = false
            this.handleOrderMethods('info')
        },

		// 点击订单提交
		onSubmitOrder() {
			uni.showModal({
				title: '温馨提示',
				content: '是否确认下单?',
				confirmColor: '#FF2C3C',
				success: ({ confirm }) => {
					if (!confirm) return

					this.handleOrderMethods('submit')

				}
			})
		},

		// 订单处理
		handleOrderMethods(action) {
			// 订单提交数据
			const orderFrom = {
				action,
				goods: this.goods,
				delivery_type: this.delivery,
				use_integral: this.useIntegral,
				address_id: this.addressId,
				coupon_id: this.couponId,
				bargain_launch_id: this.bargainLaunchId == -1 ? '' : this.bargainLaunchId
			}

			switch (action) {
				case 'info':
					this.initPageData(orderFrom)
					break
				case 'submit':
					this.handleOrderSubmit(orderFrom)
					break
			}
		},

		// 初始化页面数据
		async initPageData(from) {
			this.showLoading = true

			try {
				const { code, data, msg } = await orderBuy(from)

				if (code == 1) {
					this.address = data.address
					this.goodsLists = data.goods_lists
					//TODO
					if (data.selffetch_info) {
						this.storeInfo = data.selffetch_info.selffetch_shop
							? data.selffetch_info.selffetch_shop
							: {}
						this.userConsignee = data.selffetch_info.contact
						this.userMobile = data.selffetch_info.mobile
					}

					this.orderInfo = data
					this.$nextTick(() => {
						this.isFirstLoading = false
					})
				} else {
					throw new Error(msg)
				}
			} catch (err) {
				console.log(err)
				this.$toast({ title: '网络异常，请重新进入页面' })
			} finally {
				this.showLoading = false
			}
		},

		// 点击选择收货地址
		onAddressExpress() {
			uni.navigateTo({
				url: `/bundle/pages/address/address?type=${1}`
			})
		},

		// 选择预约时间
		handleSubmitTime(data) {
			this.day = data.day
			this.timeId = data.time_id
			this.time = data.time
			this.timePopup = false
		},

		// 订单提交
        async handleOrderSubmit(from) {
            this.showLoading = true
			// 判断预约时间
			if (this.day === '今天') {
				const today = new Date();
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0');
				const date = String(today.getDate()).padStart(2, '0');
				from.date = `${year}-${month}-${date}`;
			} else if (this.day === '明天') {
				const tomorrow = new Date();
				tomorrow.setDate(tomorrow.getDate() + 1);
				const year = tomorrow.getFullYear();
				const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
				const date = String(tomorrow.getDate()).padStart(2, '0');
				from.date = `${year}-${month}-${date}`;
			}
	
            from.remark = this.userRemark
            from.type = this.type
			from.time_id = this.timeId

            try {
                const { code, data, msg } = await orderBuy(from)
                if (code == 1) {
                    uni.redirectTo({
                        url: `/pages/payment/payment?from=${data.data.type}&order_id=${data.data.order_id}`
                    })
                } else {
                    throw new Error(msg)
                }
            } catch (err) {
                console.log(err)
                // this.$toast({ title: '下单异常，请重新操作' })
            } finally {
                this.showLoading = false
            }
        },
	},
	computed: {
		delivery() {
			return this.addressTabsList[this.addressTabsIndex]['id']
		}
	},
}
</script>

<style lang="scss">
.num {
	color: #4E5969;
}

.mask {
	color: #86909C;
}

.fixed {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding-bottom: env(safe-area-inset-bottom);
}

.count {
	color: #86909C;
}

.pop-title {
    height: 100rpx;
    border-bottom: 1rpx solid #f2f2f2;
}

.pop-title .title {
    margin-left: 30rpx;
    font-size: 34rpx;
    font-weight: bold;
    line-height: 36rpx;
}
</style>