<template>
	<view class="page">
		<!-- 导航栏 -->
		<navbar :title="titleMap[type]" leftClick @leftClick="$utils.navigateBack" bgColor="#DC2828" color="#fff" />

		<view class="bac"></view>

		<view class="box">
			
			<!-- 送礼 -->
			<view class="give-type" v-if="type == 'give'">
				<view class="tab-box">
					<view class="tab-item" :class="{'active': isGive === 1}" 
                    @click="isGive = 1">
						<text>单人礼包</text>
						<text class="desc">送给1位好友，可同时送多件礼品</text>
					</view>
					<view class="tab-item" :class="{'active': isGive === 2}" 
                    @click="isGive = 2">
						<text>多人礼包</text>
						<text class="desc">送给多位好友，每人1件礼品</text>
					</view>
					<view class="tab-item" :class="{'active': isGive === 3}" 
                    @click="isGive = 3">
						<text>抽奖礼包</text>
						<text class="desc">好友抽奖，中奖者获得礼品</text>
					</view>
				</view>
				<!-- <view class="tips">
					<text>支付后分享给好友收礼</text>
					<text class="guide" @click="$refs.popup.open('gift_guide')">指南</text>
				</view> -->
			</view>

            <!-- 多人礼包人数 -->
            <view class="cell-item" v-if="type == 'give' && isGive === 2">
                <view class="cell-item-left">
                    <uv-icon name="gift" size="40" color="#E3441A"></uv-icon>
                    <view class="user-name">礼包份数</view>
                </view>
                <view class="cell-item-right">
                    <view class="stepper">
                        <text class="minus" :class="{disabled: multiNum <= multiMinNum}" 
                            @click="multiNum > multiMinNum && multiNum--">-</text>
                        <text class="num">{{multiNum}}</text>
                        <text class="plus" :class="{disabled: multiNum >= multiMaxNum}"
                            @click="multiNum < multiMaxNum && multiNum++">+</text>
                    </view>
                </view>
            </view>

            <!-- 抽奖礼包说明 -->
            <view class="lucky-box" v-if="type == 'give' && isGive === 3">
                <view class="title">抽奖规则</view>
                <view class="tips-list">
                    <view class="tip-item">• 好友参与抽奖</view>
                    <view class="tip-item">• 系统随机抽取中奖者</view>
                    <view class="tip-item">• 中奖者填写地址领取礼品</view>
                </view>
            </view>

			<!-- 商品详情 -->
			<view class="product-item" v-for="item in payOrderProduct" :key="item.id">
				<view class="img-box">
					<image :src="item.image && item.image.split(',')[0]" mode="aspectFill"></image>
				</view>

				<view class="server-info">
					<view class="server-title">{{ item.name }}</view>

					<view class="texture">
						材质：{{ item.material }}
					</view>

					<view class="stepper">
						<uv-number-box button-size="60rpx" 
						inputWidth="250rpx"
						v-model="item.selectNum"
						:max="item.num"></uv-number-box>
					</view>

					<view class="sales-volume">
						<view class="desc">已售出 {{ item.payNum }}单</view>
					</view>
				</view>
			</view>

			<!-- 地址 -->
			<view @click="openAddress" class="cell-item">
				<view class="cell-item-left">
					<image src="@/pages_order/static/createOrder/address.png" mode="widthFix" class="cell-icon"></image>
					<view class="user-name">{{ address.name }}</view>
					<view class="user-address">{{ address.address }}</view>
				</view>
				<view class="cell-item-right">
					<uv-icon name="arrow-right"></uv-icon>
				</view>
			</view>

			<!-- 备注 -->
			<!-- <view class="cell-item">
				<view class="cell-item-left">
					<image src="@/pages_order/static/createOrder/coupon.png" mode="widthFix" class="cell-icon"></image>
					<view class="user-name">备注</view>
				</view>
				<view class="cell-item-right remark-input">
					<uv-textarea v-model="remark" border="none" height="40rpx" placeholder="请输入订单备注信息" :count="false" :auto-height="false" />
				</view>
			</view> -->

			<view class="cell-list">
				<uv-radio-group v-model="payMethod">
					<view style="width: 710rpx;">
						<!-- 账户余额 -->
						<view class="cell-item">
							<view class="cell-item-left">
								<image src="@/pages_order/static/createOrder/account.png" mode="widthFix" class="cell-icon">
								</image>
								<view class="user-name">账户积分</view>
								<view class="descript">(积分: {{ userInfo.money }})</view>
							</view>
							<view class="cell-item-right">
								<uv-radio activeColor="#E3441A"
								size="40rpx"
								icon-size="30rpx"
								:name="0"/>
							</view>
						</view>
						
						<!-- 微信支付 -->
						<view class="cell-item">
							<view class="cell-item-left">
								<image src="@/pages_order/static/createOrder/wx.png" mode="widthFix" class="cell-icon">
								</image>
								<view class="user-name">微信支付</view>
								<view class="descript"></view>
							</view>
							<view class="cell-item-right">
								<uv-radio 
								activeColor="#E3441A"
								size="40rpx"
								icon-size="30rpx"
								:name="1"/>
							</view>
						</view>
					</view>
				</uv-radio-group>
			</view>

			<!-- 优惠券 -->
			<!-- <view @click="openCoupon" class="cell-item">
				<view class="cell-item-left">
					<image src="@/pages_order/static/createOrder/coupon.png" mode="widthFix" class="cell-icon"></image>
					<view class="user-name">优惠券</view>
					<view class="descript">(￥{{ coupon.money || 0}})</view>
				</view>
				<view class="cell-item-right">
					<radio color="#E3441A" :value="2" :checked="coupon.id" />
				</view>
			</view> -->

			<!-- 提示 -->
			<view class="hint"
			v-if="payOrderProduct[0] && payOrderProduct[0].orderDetails">
				{{ payOrderProduct[0].orderDetails }}
			</view>

			<!-- 用户协议 -->
			<view class="agreement">
				<radio color="#E3441A" @click="agreement = !agreement" :checked="agreement" />
				本人已同意<text @click="$refs.popup.open('user_xy')">《用户使用协议》</text>
			</view>

			<!-- 下单 -->
			<view class="submit">
				<view class="price">
					<view>
						<text style="color: #000;">合计</text>
						￥<text style="font-size: 18px;
						font-weight: 600;">{{ totalPrice }}</text>元
					</view>
				</view>
				<view class="btn" @click="submit">
					立即支付
				</view>
			</view>
		</view>

		<!-- 地址选择 -->
		<uv-popup ref="addressPopup" :round="30" style="padding-bottom: 90rpx;">
			<addressList ref="addressList" height="60vh" @select="selectAddress" />
			<view class="add-btn">
				<view @click="$utils.navigateTo('/pages_order/mine/address?type=back')" class="button-submit">新增地址</view>
			</view>
		</uv-popup>

		<!-- 优惠券选择-->
		<!-- <uv-popup ref="couponPopup" :round="30">
			<couponList ref="couponList" height="60vh" @select="selectCoupon" />
		</uv-popup> -->
		
		<configPopup ref="popup"></configPopup>
		
		<!-- <kefu></kefu> -->
		
		<kefu/>

	</view>
</template>

<script>
	import addressList from '../components/address/addressList.vue'
	// import couponList from '@/components/couponList/couponList.vue'

	import {
		mapState
	} from 'vuex'

	export default {
		components: {
			addressList,
			// couponList
		},
		data() {
			return {
				address: {
					name: '请选择地址',
					address: '',
				},
				addressTotal: 0,
				remark: '',
				agreement: false,
				coupon: {},
				payMethod : 1,
                isGive : 0,
                type : '',
                titleMap : {
                    def : '确认订单',
                    give : '送礼清单',
                },
                multiNum: 2, // 多人礼包人数
                multiMinNum: 2, // 最小人数
                multiMaxNum: 100, // 最大人数
			}
		},
		computed: {
			totalPrice() {
				let price = 0

				this.payOrderProduct.forEach(n => {
					price += n.price * (n.selectNum || 1)
				})

				if (this.coupon.id) {
					price -= this.coupon.money
				}

				return Number(price).toFixed(2)
			},
			...mapState(['userInfo', 'payOrderProduct']),
		},
		onLoad(args) {
            this.type = args.type || 'def'
            if(this.type == 'give'){
                this.isGive = 1
            }
			this.$store.commit('getUserInfo')
		},
		onShow() {
			this.getAddressList()
			// this.getCouponList()
		},
		methods: {
			// 打开
			getAddressList() {
				// 获取地址列表
				this.$refs.addressList.getAddressList().then(res => {
					this.addressTotal = res.total
					if (this.addressTotal != 0) {
						this.address = res.records[0]
					}
				})
			},
			//获取优惠券列表
			getCouponList() {
				this.$refs.couponList.getCouponList()
			},
			// 打开选择地址
			openAddress() {
				if (this.addressTotal == 0) {
					return uni.navigateTo({
						url: '/pages_order/mine/address?type=back'
					})
				}
				this.$refs.addressPopup.open('bottom')
			},
			// 选择地址
			selectAddress(e) {
				this.address = e
				this.$refs.addressPopup.close()
			},
			// 打开优惠券选择
			openCoupon() {
				if (this.addressTotal == 0) {
					return uni.navigateTo({
						url: '/pages_order/mine/address?type=back'
					})
				}
				this.$refs.couponPopup.open('bottom')
			},
			// 选择优惠券
			selectCoupon(e) {
				//判断优惠券限制
				let {
					useMoney
				} = e
				let productTotalPrice = 0
				this.payOrderProduct.forEach(item => {
					productTotalPrice += item.price
				})
				if (productTotalPrice < useMoney) {
					return uni.showToast({
						title: `此优惠券需要满${useMoney}使用`,
						icon: "none"
					})
				}
				this.coupon = e
				this.$refs.couponPopup.close()
			},

			submit() {

				let addressId = this.address.id

				if (!addressId) {
					uni.showToast({
						title: '请选择地址',
						icon: 'none'
					})
					return
				}
				
				if (!this.agreement) {
					uni.showToast({
						title: '请先同意使用协议',
						icon: 'none'
					})
					return
				}

				let data = {}
				let api = ''

				// if(this.type != 'give'){

					let list = []
					this.payOrderProduct.forEach(n => {
						list.push({
							num: n.selectNum || 1,
							shopId: n.id,
						})
					})
					data = {
						addressId,
						payType : this.payMethod,
						list: JSON.stringify(list),
						// remark: this.remark || '', // 添加备注字段
					}
					
					api = 'createSumOrder'

					this.deleteCart(this.payOrderProduct.map(n => n.cartId).join(','))

				// } else {
					// data = {
					// 	addressId,
					// 	num: this.payOrderProduct[0].selectNum || 1,
					// 	productId: this.payOrderProduct[0].id,
					// 	payType : this.payMethod,
     //                    // isGive : this.isGive,
     //                    // memberNum : 1,
					// 	// remark: this.remark || '', // 添加备注字段
					// }
					// api = 'createOrder'
				// }
				
				if(this.coupon.id){
					data.couponId = this.coupon.id
				}
    //             if(this.isGive == 2){
				// 	data.memberNum = this.multiNum
				// }

				this.$api(api, data, res => {
					if (res.code == 200) {
						
						if(this.payMethod == 0){
							// uni.showToast({
							// 	title: '下单成功',
							// 	icon: 'none'
							// })
							this.paySuccess(res)
							return
						}
						
						uni.requestPaymentWxPay(res)
                        .then(e => {
                            uni.showToast({
                                title: '下单成功',
                                icon: 'none'
                            })

                            this.paySuccess(res)
                        }).catch(n => {
                            setTimeout(uni.redirectTo, 700, {
                                url: '/pages/index/order'
                            })
                        })
					
					}
				})
			},
            paySuccess(res){
                if(this.type == 'def'){
                    setTimeout(uni.redirectTo, 700, {
                        url: '/pages/index/order'
                    })
                }else{
                    setTimeout(uni.redirectTo, 700, {
                        url: `/pages_order/order/instantGift?id=${res.message}`
                    })
                }
            },
			// 删除购物车
			deleteCart(ids) {
				this.$api('deleteCart', {
					ids
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.page {
		overflow: auto;
		padding-bottom: 300rpx;
		.bac {
			width: 100%;
			height: 100px;
			background: $uni-color;
		}

        .give-type {
            background: #fff;
            border-radius: 20rpx;
            padding: 30rpx;
            margin-bottom: 20rpx;
            
            .tab-box {
                display: flex;
                justify-content: space-between;
                
                .tab-item {
                    width: 30%;
                    background: #F8F8F8;
                    border-radius: 20rpx;
                    padding: 20rpx;
                    text-align: center;
                    
                    text {
                        display: block;
                        
                        &.desc {
                            font-size: 24rpx;
                            color: #999;
                            margin-top: 10rpx;
                        }
                    }
                    
                    &.active {
                        background: rgba($uni-color, 0.1);
                        color: $uni-color;
                        
                        .desc {
                            color: $uni-color;
                        }
                    }
                }
            }
            
            .tips {
                margin-top: 20rpx;
                font-size: 26rpx;
                color: #999;
                display: flex;
                align-items: center;
                justify-content: space-between;
                
                .guide {
                    color: $uni-color;
                    text-decoration: underline;
                }
            }
        }

		.box {
			padding: 20rpx;
			margin-top: -150rpx;

			// 商品详情
			.product-item {
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				justify-content: space-between;
				background: white;
				border-radius: 15rpx;
				box-sizing: border-box;
				padding: 25rpx;
				margin: 20rpx 0rpx;

				.img-box {
					width: 200rpx;
					height: 200rpx;
					background: #ccc;
					border-radius: 10rpx;
					overflow: hidden;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.server-info {
					width: calc(100% - 200rpx);
					box-sizing: border-box;
					padding: 10rpx 20rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-around;

					.server-title {
						font-size: 34rpx;
					}

					.texture {
						color: #B8B8B8;
						margin: 10rpx 0rpx;
					}

					.stepper {
						margin-bottom: 10rpx;

						&::v-deep .uv-number-box__input {
							color: $uni-color !important;
							width: 200rpx !important;
						}
					}

					.sales-volume {
						display: flex;
						align-items: center;
						color: #B8B8B8;
						font-size: 26rpx;

						image {
							width: 25rpx;
							height: 25rpx;
						}

					}

				}
			}

			//cell单元格(地址)
			.cell-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: white;
				border-radius: 20rpx;
				padding: 20rpx;
				box-sizing: border-box;

				.cell-item-left {
					display: flex;
					align-items: center;
					width: 90%;

					.cell-icon {
						width: 40rpx;
					}

					.user-name,
					.user-address {
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 150rpx;
						padding-left: 20rpx;
						box-sizing: border-box;
					}

					.descript {
						color: #888888;
					}

					.user-address {
						width: calc(100% - 230rpx);
					}
				}

				.cell-item-right {
					width: 10%;
					display: flex;
					justify-content: flex-end;

					&.remark-input {
						width: 70%;
						justify-content: flex-start;
						
						&::v-deep .uv-textarea {
							width: 100%;
							padding: 0;
							background-color: transparent;
						}
						
						&::v-deep .uv-textarea__field {
							padding: 0;
							font-size: 28rpx;
						}
					}

					.stepper {
						display: flex;
						align-items: center;
						text {
							display: flex;
							align-items: center;
							justify-content: center;
							width: 44rpx;
							height: 44rpx;
							
							&.minus, &.plus {
								background: #F8F8F8;
								border-radius: 50%;
								font-size: 32rpx;
								
								&.disabled {
									color: #ccc;
								}
							}
							
							&.num {
								margin: 0 20rpx;
								color: $uni-color;
								font-size: 28rpx;
							}
						}
					}
				}
			}

			.cell-list {
				margin: 20rpx 0rpx;
				border-radius: 20rpx;
				overflow: hidden;

				.cell-item {
					border-radius: 0rpx;
				}
			}

			// 提示
			.hint {
				font-size: 26rpx;
				margin-top: 80rpx;
				color: #BFBFBF;
			}

			// 用户协议
			.agreement {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10px 0;

				.van-checkbox {
					margin-right: 5rpx;
				}

				text {
					color: $uni-color;
				}
			}

			// 下单
			.submit {
				position: fixed;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 60px;
				background-color: #fff;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.price {
					color: #F39637;
					padding: 0 20px;
				}

				.btn {
					background: $uni-color;
					color: white;
					width: 120px;
					height: 45px;
					border-radius: 23px;
					font-size: 16px;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}

		//新增地址按钮
		.add-btn {
			width: 100%;

			.button-submit {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 596rpx;
				height: 90rpx;
				background: #E3441A;
				border-radius: 46rpx;

				margin: 20rpx auto;

				font-size: 28rpx;
				font-family: PingFang SC, PingFang SC-Regular;
				font-weight: 400;
				text-align: center;
				color: #ffffff;
			}
		}
        .multi-box, .lucky-box {
            background: #fff;
            border-radius: 20rpx;
            padding: 30rpx;
            margin-bottom: 20rpx;

            .title {
                font-size: 28rpx;
                font-weight: 500;
                margin-bottom: 20rpx;
            }
        }

        .multi-box {
            .stepper {
                display: flex;
                align-items: center;
                justify-content: center;
                
                text {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 60rpx;
                    height: 60rpx;
                    
                    &.minus, &.plus {
                        background: #F8F8F8;
                        border-radius: 50%;
                        font-size: 36rpx;
                        
                        &.disabled {
                            color: #ccc;
                        }
                    }
                    
                    &.num {
                        margin: 0 40rpx;
                        color: $uni-color;
                        font-size: 32rpx;
                    }
                }
            }
        }

        .lucky-box {
            .tips-list {
                .tip-item {
                    font-size: 26rpx;
                    color: #666;
                    line-height: 2;
                }
            }
        }
	}
</style>