<template>
	<view class="create-order">
		<tui-skeleton v-if="isRequest" loadingType="2"></tui-skeleton>
		<!-- 收货地址 -->
		<view class="order-top"><cm-choose-address :addressData="addressData"></cm-choose-address></view>
		<view class="grid"></view>
		<!-- 订单列表 -->
		<view class="order-list">
			<view v-for="(shopInfo, shopInfoIndex) in goodsData" :key="shopInfoIndex">
				<view class="line"></view>
				<view class="order-section">
					<!-- 供应商 -->
					<view class="origin">
						<image class="cover" :src="shopInfo.logo"></image>
						<view class="name">{{ shopInfo.name }}</view>
					</view>
					<!-- 商品列表 -->
					<view class="goods-list">
						<!-- 商品信息 -->
						<view class="order-goods" v-for="goods in shopInfo.productList" :key="goods.productId">
							<cm-order-prodcut :goods-data="goods"></cm-order-prodcut>
						</view>
					</view>
					<!-- 合计 -->
					<!-- <view class="total-price">
                        <text>合计:</text> <text class="price">￥{{ shopInfo.shopTotalPrice | formatPrice }}</text>
                    </view> -->
					<!-- 留言 -->
					<view class="remark">
						<view class="label">留言:</view>
						<input class="control" type="text" v-model="shopInfo.note" placeholder="请输入内容" />
					</view>
				</view>
			</view>
		</view>

		<!-- 优惠券 -->
		<template v-if="receiveCouponList.length > 0">
			<view class="grid"></view>
			<cm-order-coupon-section @click="couponVisible = true" :coupon="currentCoupon"></cm-order-coupon-section>
		</template>

		<!-- 分享减免 -->
		<template v-if="reduction">
			<view class="grid"></view>
			<cm-order-share-reduce :reductionData="shareReductionData"></cm-order-share-reduce>
		</template>

		<!-- 运费 -->
		<view class="grid"></view>
		<cm-order-freight-section></cm-order-freight-section>

		<view class="grid"></view>

		<!-- 提交导航 -->
		<cm-order-submit-nav :orderInfo="submitOrderInfo" @commit="orderSubmit"></cm-order-submit-nav>

		<!-- 优惠券列表 -->
		<cm-coupon-list
			title="优惠券"
			listType="use"
			:visible="couponVisible"
			@close="closeCouponList"
			:chooseAble="true"
			:showStatus="false"
			:couponList="receiveCouponList"
			@chooseCoupon="chooseCoupon"
			@confirm="closeCouponList"
			:currentId="currentCouponUniqueId"
		></cm-coupon-list>
		<cm-loading :visible="isSubLoading" :text="loadingText"></cm-loading>
		<view class="reserved" v-if="isIphoneX"></view>
	</view>
</template>

<script>
import CmChooseAddress from '@/components/cm-module/cm-choose-address/cm-choose-address.vue'
import CmOrderProdcut from '@/components/cm-module/cm-order-prodcut/cm-order-prodcut.vue'
import CmOrderSubmitNav from '@/components/cm-module/cm-order-submit-nav/cm-order-submit-nav.vue'
import CmOrderCouponSection from '@/components/cm-module/cm-order-coupon-section/cm-order-coupon-section.vue'
import CmOrderFreightSection from '@/components/cm-module/cm-order-freight-section/cm-order-freight-section.vue'
import CmOrderShareReduce from '@/components/cm-module/cm-order-share-reduce/cm-order-share-reduce.vue'
import CmLoading from '@/components/cm-module/cm-loading/cm-loading.vue'
import CmCouponList from '@/components/cm-module/cm-coupon-list/cm-coupon-list'

import { allProdoceUseCheck, someProductUseCheck, couponSort, setCouponUniqueId } from '@/common/couponUtil.js'
import { mapGetters } from 'vuex'
import wechatPay from './mixins/wechatPay.js'

export default {
	// 混入
	mixins: [wechatPay],
	components: {
		CmOrderProdcut,
		CmChooseAddress,
		CmOrderSubmitNav,
		CmOrderCouponSection,
		CmOrderFreightSection,
		CmOrderShareReduce,
		CmCouponList,
		CmLoading
	},
	data() {
		return {
			isRequest: true,

			// 收货地址
			addressData: {},

			productIds: '',
			// 初始化订单信息参数列表
			params: {},

			// 订单提交参数
			subParams: {
				userId: 0,
				orderInfo: [], //提交的商品信息
				addressId: 0,
				cartType: 0,
				payInfo: {
					orderShouldPayFee: 0
				},
				discountInfo: null
			},

			goodsData: [], // 供应商下的商品
			allPrice: 0,
			productList: [], // 商品列表
			allCount: 0,
			hanldOrder: {},

			// 优惠券
			couponVisible: false,
			receiveCouponList: [], // 已领取优惠券列表
			currentCouponUniqueId: -1, // 选中的优惠券唯一id 注意：非优惠券id，选中优惠券id通过currentCoupon.couponId获取
			currentCoupon: {}, // 选中的优惠券信息
			canUseCouponList: [], // 能够使用的优惠券列表
			notUseCouponList: [], // 暂未满足条件的优惠券列表

			// 拼团
			collageFlag: 0, //拼团标识：0不参与拼团，1参与拼团
			collageId: 0, //拼团id：参与拼团，若拼团id为空则发起拼团，不为空则与他人拼团

			// 分享抵扣
			shareReductStatus: false,
			reduction: null,
			reductionUserId: 0, //分享抵扣用户id
			shareData: {
				type: 0
			}
		}
	},
	computed: {
		...mapGetters(['userId', 'isIphoneX']),
		// 选中的优惠券的金额
		couponAmount() {
			return this.currentCoupon.couponAmount || 0
		},
		// 最终支付金额
		payAllPrice() {
			const payAllPrice = this.allPrice - this.couponAmount - this.shareReducedAmount
			return payAllPrice <= 0 ? 0 : payAllPrice
		},
		// 总优惠价格
		discountedPrice() {
			return this.couponAmount + this.shareReducedAmount
		},
		// 提交组件状态信息
		submitOrderInfo() {
			return {
				allCount: this.allCount,
				payAllPrice: this.payAllPrice,
				discountedPrice: this.discountedPrice
			}
		},
		// 优惠券，分享活动相关参数
		discountInfo() {
			return {
				//优惠券ID
				couponId: this.currentCoupon.couponId || 0,
				//优惠券分享ID
				couponShareId: this.currentCoupon.couponShareId || 0,
				//拼团标识：0不参与拼团，1参与拼团
				collageFlag: this.collageFlag,
				//拼团id：参与拼团，若拼团id为空则发起拼团，不为空则与他人拼团
				collageId: this.collageId,
				//分享抵扣用户id
				reductionUserId: this.reductionUserId
			}
		},
		// 分享减免金额
		shareReducedAmount() {
			return this.reduction && this.shareReductStatus ? this.reduction.reducedAmount : 0
		},
		// 分享减免组件状态信息
		shareReductionData() {
			return {
				status: this.shareReductStatus,
				reduction: this.reduction
			}
		}
	},
	onLoad(options) {
		this.isRequest = true
		this.getAddressData()
		this.initOptions(options)
		// this.orderPaySuccess() // 支付回调
	},
	onShow() {
		let pages = getCurrentPages()
		let currPage = pages[pages.length - 1]
		if (currPage.data.select == 'select') {
			this.isAddress = true
			let SelectData = uni.getStorageSync('selectAddress')
			this.subParams.addressId = SelectData.addressId
			this.addressData = SelectData
		} else {
			this.getAddressData()
		}
	},
	beforeDestroy() {
		uni.removeStorageSync('commitProductInfo')
		uni.removeStorageSync('commitCartPramsData')
	},
	// 分享朋友圈
	// onShareTimeline() {
	//     this.handleShare(2)
	//     // 加密
	//     const state_str = encodeURIComponent(this.$crypto.encrypt(this.shareData))
	//     return {
	//         title: '护肤上颜选，正品有好货~',
	//         query: `/pages/tabBar/index/index?state_str=${state_str}`,
	//         imageUrl: this.$Static + 'icon-index-share.jpg'
	//     }
	// },
	// 分享
	onShareAppMessage(e) {
		this.handleShare(1)
		// 加密
		const state_str = encodeURIComponent(this.$crypto.encrypt(this.shareData))
		return {
			title: '护肤上颜选，正品有好货~',
			path: `/pages/tabBar/index/index?state_str=${state_str}`,
			imageUrl: this.$Static + 'icon-index-share.jpg'
		}
	},

	methods: {
		// 支付回调执行函数
		orderPaySuccess() {
			this.$on('orderPaySuccess', () => {
				if (this.collageFlag === 1) {
					uni.redirectTo({ url: `/pages/fight-order/fight-detail?collageId=${this.collageId}` })
				} else {
					uni.redirectTo({ url: '/pages/order/success' })
				}
			})
		},
		// 分享
		handleShare(shareType) {
			if (!this.reduction) return
			const { reductionId } = this.reduction
			this.OrderService.OrderReductionShare({ reductionId, shareType, userId: this.userId })
				.then(res => {
					this.$util.msg(res.msg, 2000)
					this.reductionUserId = res.data
					this.shareReductStatus = true
				})
				.catch(err => {
					this.$util.msg(error.msg, 2000)
					this.shareReductStatus = false
				})
		},

		// 初始化参数信息
		initOptions(options) {
			// 从商品详情进入
			if (options.type == 'prodcut') {
				const productInfo = uni.getStorageSync('commitProductInfo')
				this.subParams.cartType = 2 // 从商品详情提交
				this.params.productCount = productInfo.productCount
				this.params.productId = productInfo.productId
				this.params.heUserId = productInfo.heUserId || 0
				this.params.collageFlag = this.collageFlag = productInfo.collageFlag
				this.productIds = productInfo.productId.toString()
				this.allCount = productInfo.allCount
				this.collageId = parseInt(productInfo.collageId) || 0
			} else {
				const cartPramsData = uni.getStorageSync('commitCartPramsData')
				this.subParams.cartType = 1 // 从购物车提交
				this.params.cartIds = cartPramsData.cartIds
				this.productIds = cartPramsData.productIds
				this.allCount = cartPramsData.allCount
			}

			this.params.userId = this.userId
			this.subParams.userId = this.userId
			this.getInitCrearOrder(this.params)
		},

		// 获取可用优惠券
		fetchCouponList() {
			this.CouponService.GetCouponByProductIds({ userId: this.userId, productIds: this.productIds }).then(res => {
				this.receiveCouponList = setCouponUniqueId(res.data.receiveCouponList) // 去掉重复的优惠券
				this.filterCouponList()
			})
		},

		// 对优惠券进行分类排序
		filterCouponList() {
			this.goodsData.forEach(shop => this.productList.push(...shop.productList.map(prod => prod)))
			this.canUseCouponList = [] // 可以使用的优惠券
			this.notUseCouponList = [] // 需要凑单使用的优惠券
			this.receiveCouponList.forEach(coupon => {
				if (
					coupon.noThresholdFlag === 1 ||
					(coupon.productType === 1 && allProdoceUseCheck(this.productList, coupon)) ||
					(coupon.productType === 2 && someProductUseCheck(this.productList, coupon))
				) {
					coupon.canSelect = true
					this.canUseCouponList.push(coupon)
				} else {
					coupon.canSelect = false
					this.notUseCouponList.push(coupon)
				}
			})
			// 金额高的排前面
			this.receiveCouponList = [...couponSort(this.canUseCouponList), ...couponSort(this.notUseCouponList)]
			// 当有可用优惠券时 默认选取第一个最优惠的
			if (this.canUseCouponList.length > 0) {
				this.currentCouponUniqueId = this.receiveCouponList[0].uniqueId
				this.currentCoupon = this.receiveCouponList[0] || {}
			}
			// 显示界面
			this.isRequest = false
		},

		// 处理优惠券列表
		resetCouponList() {
			// 1将当前选中的优惠券从列表中删除
			// 2将当前选中的优惠券放入最前面
			// 3返回最新的优惠券列表
			// 4查找选中优惠券的索引
			const index = this.canUseCouponList.findIndex(coupon => coupon.uniqueId === this.currentCouponUniqueId)
			// 从列表中删除
			const currentCoupon = this.canUseCouponList.splice(index, 1)
			// 重新排序 将选中的优惠券放到最前面
			this.canUseCouponList = [...currentCoupon, ...couponSort(this.canUseCouponList)]
			// 重新生成receiveCouponList
			this.receiveCouponList = [...this.canUseCouponList, ...this.notUseCouponList]
		},

		// 确认选中
		closeCouponList() {
			this.couponVisible = false
			this.resetCouponList()
		},

		// 选中优惠券
		chooseCoupon(coupon) {
			if (coupon.couponId > -1) {
				this.currentCoupon = coupon
				this.currentCouponUniqueId = coupon.uniqueId
			} else {
				this.currentCoupon = {}
				this.currentCouponUniqueId = -1
			}
			// this.couponVisible = false
		},
		//确认订单初始化信息
		getInitCrearOrder(params) {
			this.OrderService.QueryOrderConfirm(params)
				.then(res => {
					let data = res.data
					this.goodsData = this.bindRemark(data.shopList)
					console.log(this.goodsData)
					this.allPrice = data.totalPrice
					this.fetchCouponList()
					this.reduction = res.data.reduction
					this.isRequest = false
				})
				.catch(error => {
					this.$util.msg(error.msg, 2000)
				})
		},
		// 为共供应商绑定留言信息
		bindRemark(shopList) {
			return shopList.map(item => {
				item.note = ''
				return item
			})
		},
		//获取地址信息
		getAddressData() {
			this.UserService.QueryAddressList({ pageNum: 1, pageSize: 1, userId: this.userId }).then(res => {
				this.addressData = res.data.list[0]
				// 设置收货地址
				this.subParams.addressId = this.addressData.addressId
			})
		},
		orderSubmit() {
			//提交订单
			if (this.isSubLoading) return
			if (this.subParams.addressId == '') return this.$util.msg('请先添加收货地址～', 2000)
			// 优惠券，分享活动相关参数
			this.subParams.discountInfo = this.discountInfo
			// 要支付的金额
			this.subParams.payInfo.orderShouldPayFee = this.payAllPrice
			//
			// 处理商品信息及留言
			this.subParams.orderInfo = this.goodsData.map(el => {
				let productInfo = []
				el.productList.forEach(pros => {
					productInfo.push({
						productId: pros.productId,
						productNum: pros.productCount,
						heUserId: pros.heUserId
					})
				})
				return { shopId: el.shopId, note: el.note ? el.note : '', productInfo, splitCode: el.splitCode }
			})

			// 调试提交参数
			console.log(this.subParams)
			// return

			this.isSubLoading = true
			this.loadingText = '正在创建订单...'
			this.OrderService.CreatedOrderSubmit(this.subParams)
				.then(response => {
					this.isSubLoading = false
					// const data = response.data
					// this.hanldOrder.order = response.data
					// this.collageId = data.collageId
					// if (parseFloat(data.payableAmount) === 0) {
					// 	uni.setStorageSync('orderInfo', this.hanldOrder.order)
					// 	uni.redirectTo({ url: '/pages/order/success' })
					// } else {
					// 	this.miniWxPayFor(data)
					// }
					uni.redirectTo({ url: `/pages/order/order-pay?orderId=${response.data.orderId}` })
				})
				.catch(error => {
					this.$util.msg(error.msg, 2000)
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.create-order {
	background: #f7f7f7;
	min-height: 100vh;
	padding-top: 134rpx;
	padding-bottom: 100rpx;
	box-sizing: border-box;

	.order-top {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
	}
}

.grid {
	width: 100%;
	height: 20rpx;
	background: #f7f7f7;
}

.line {
	width: 702rpx;
	height: 1rpx;
	margin: 0 auto;
	background: #f7f7f7;
}

.order-list {
	background: #fff;

	.order-section {
		padding: 38rpx 0;
	}

	.goods-list {
		.order-goods {
			padding-top: 32rpx;
			&:first-child {
				padding-top: 0;
			}
		}
	}

	.origin {
		padding: 0 24rpx;
		margin-bottom: 16rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		.cover {
			width: 56rpx;
			height: 56rpx;
			border-radius: 4rpx;
		}
		.name {
			margin-left: 16rpx;
			font-size: 30rpx;
			color: #333333;
		}
	}
}

.total-price {
	padding: 24rpx;
	text-align: right;
	font-size: 26rpx;
	color: #333;
	background: #fff;

	.price {
		color: #ff457b;
	}
}

.remark {
	padding: 24rpx 24rpx 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: #fff;

	.label {
		width: 78rpx;
		font-size: 26rpx;
		color: #999999;
		margin-right: 16rpx;
	}

	.control {
		flex: 1;
		font-size: 26rpx;
		color: #333333;
		padding: 8rpx 16rpx;
		background: #f7f7f7;
		border-radius: 8rpx;
	}
}
</style>
