<template>
	<view class="create-order" :class="{'has-bottom': isIphoneX}">
		<!-- 收货地址 -->
		<view class="order-top">
			<cm-choose-address :addressData="addressData"></cm-choose-address>
		</view>
		<view class="grid"></view>
		<!-- 订单列表 -->
		<view class="order-list">
			<view class="order-section" v-for="(shopInfo, shopInfoIndex) in goodsData" :key="shopInfoIndex">
				<!-- 供应商 -->
				<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 class="grid"></view>
		<!-- 优惠券 -->
		<cm-order-coupon-section
			@click="couponVisible = true"
			:coupon="currentCoupon"
			v-if="receiveCouponList.length > 0"
		></cm-order-coupon-section>
		<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="currentCouponId"
		></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 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,
		CmCouponList,
		CmLoading
	},
	data() {
		return {
			// 收货地址
			addressData: {},

			productIds: '',
			params: {},
			subParams: {
				userId: 0,
				orderInfo: [], //提交的商品信息
				addressId: 0,
				cartType: 0,
				payInfo: {
					orderShouldPayFee: 0
				}
			},
			goodsData: [], // 供应商下的商品
			allPrice: 0,
			productList: [], // 商品列表
			allCount: 0,
			hanldOrder: {},
			
			// 优惠券
			couponVisible: false,
			receiveCouponList: [],
			currentCouponId: -1,
			currentCoupon: {},
			canUseCouponList: [],
			notUseCouponList: [],
			
		}
	},
	computed: {
		...mapGetters(['userId', 'isIphoneX']),
		// 选中的优惠券的金额
		couponAmount() {
			return this.currentCouponId > -1 ? this.currentCoupon.couponAmount : 0
		},
		// 优惠价格
		discountedPrice() {
			return this.couponAmount
		},
		// 支付金额
		payAllPrice() {
			const payAllPrice = this.allPrice - this.couponAmount
			return payAllPrice <= 0 ? 0 : payAllPrice
		},
		submitOrderInfo(){
			return {
				allCount: this.allCount,
				payAllPrice: this.payAllPrice,
				discountedPrice: this.discountedPrice
			}
		}
	},
	onLoad(options) {
		this.getAddressData()
		this.initOptions(options)
	},
	beforeDestroy() {
		uni.removeStorageSync('commitProductInfo')
		uni.removeStorageSync('commitCartPramsData')
	},
	methods: {
		// 初始化参数信息
		initOptions(options) {
			// 从商品详情进入
			if (options.type == 'prodcut') {
				const productInfo = uni.getStorageSync('commitProductInfo')
				this.params.productCount = productInfo.productCount
				this.params.productId = productInfo.productId
				this.params.heUserId = productInfo.heUserId || 0
				this.productIds = productInfo.productId.toString()
				this.allCount = productInfo.allCount
			} else {
				const cartPramsData = uni.getStorageSync('commitCartPramsData')
				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.currentCouponId = 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.currentCouponId)
			// 从列表中删除
			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.currentCouponId = coupon.uniqueId
			} else {
				this.currentCoupon = null
				this.currentCouponId = -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()
				})
				.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)
		    // 选中的优惠券id
		    this.subParams.couponId = this.currentCouponId === -1 ? '' : this.currentCoupon.couponId
		    this.subParams.couponShareId = this.currentCoupon ? this.currentCoupon.couponShareId : null
		    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 }
		    })
		    this.isSubLoading = true
		    this.loadingText = '正在创建订单...'
		    this.OrderService.CreatedOrderSubmit(this.subParams)
		        .then(response => {
		            const data = response.data
		            this.hanldOrder.order = response.data
		            if (parseFloat(data.payableAmount) === 0) {
		                uni.setStorageSync('orderInfo', this.hanldOrder.order)
		                uni.redirectTo({ url: '/pages/user/order/success' })
		            } else {
		                this.miniWxPayFor(data)
		            }
		        })
		        .catch(error => {
		            this.isSubLoading = false
		            this.$util.msg(error.msg, 2000)
		            this.isSubLoading = false
		        })
		},
	}
}
</script>

<style lang="scss" scoped>
.create-order {
	background: #f7f7f7;
	min-height: 100vh;
	padding-top: 136rpx;
	
	&.has-bottom{
		padding-bottom: 100rpx;
	}
	
	.order-top{
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
	}
}

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

.order-list {
	background: #fff;

	.order-section {
		padding: 38rpx 0;
		margin-top: 20rpx;
		&:first-child {
			margin-top: 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: 0 24rpx;
	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>
