<template>
	<view class="page">
		<!-- 收货地址 -->
		<view class="address">
			<AddressCard :data="addressInfo" v-if="addressInfo.id"></AddressCard>
			<view class="addbtn" v-else @click="selAddress()">
				+选择地址
			</view>
		</view>
		<view class="conbg">
			<!-- 商品列表 -->
			<view class="goods">
				<SubmitGoodsCard v-for="(goods, index) in goodsList" :key="index" :data="goods" :showBorderBottom="index != goodsList.length - 1"></SubmitGoodsCard>
			</view>
			<!-- 优惠信息 -->
			<SubmitDiscounts :data="priceInfo" :couponList="canUseCouponList" :usingCoupon="usingCoupon" @selCoupon="selCouponFun"></SubmitDiscounts>			
			<u-field v-model="remark" label="留言" placeholder="请输入您的留言"></u-field>
		</view>	
		<!-- 提交订单 -->
		<!-- {{priceInfo}} -->
		<selCouponPopup :priceInfo="priceInfo" ref="selCouponPopupRef" @done="confirmSelCoupon"></selCouponPopup>		
		
		<!-- 底部按钮 -->
		<SubmitOperate :data="priceInfo" @submitOrder="submitOrder"></SubmitOperate>
	</view>
</template>

<script>
import SubmitDiscounts from '@/pages-mall/components/order/submit-discounts.vue';
import SubmitGoodsCard from '@/pages-mall/components/order/submit-goods-card.vue';
import SubmitOperate from '@/pages-mall/components/order/submit-operate.vue';
import AddressCard from '@/pages/mine/components/address-card.vue';
import selCouponPopup from '@/pages-mall/components/order/sel-coupon-popup.vue';

var _self;
export default {
	components: {
		AddressCard,
		SubmitDiscounts,
		SubmitGoodsCard,
		SubmitOperate,
		selCouponPopup
	},
	data() {
		return {
			orderType:'single',// cart，购物车订单 single 详情页直接下的订单
			cartIds:'',//有的话代表是购物车订单，无 常规订单
			expresstemplate:{},
			priceInfo: {
				countPrice:0,//商品总价
				discount:0,//优惠券
				freight:0,//运费
			},
			usingCoupon:{},//使用中的优惠券信息
			// canUseCoupon:[], //可用优惠券
			// notUseCoupon:[],//不可用优惠券
			thisTimeNum:Date.now(),
			remark:'',
			addressInfo: {},
			goodsList: [],
		};
	},
	async onLoad(opt) {
		_self = this;
		if(!opt.orderInfo){
			uni.navigateBack();
			return;
		}
		if(opt.cartIds){
			this.cartIds = opt.cartIds;
		}
		let orders = JSON.parse(decodeURIComponent(opt.orderInfo));
		this.goodsList = [].concat(orders);
		
		// 获取默认地址
		await this.getDefaultAddress();
		console.log('默认地址设置成功')
		console.log('执行2222222')
		// 是否有运费模板 express_type 运费类型
		if(!this.baseConfig.express_type){
			await this.getExpressInfo();
		}
		console.log('已经有运费模板了哦')
		this.expressPipei();
		
		this.comoutedPrice();
		this.getUserCouponList();
	},
	onShow() {
		uni.$once('addressInfo',function(data){
			_self.addressInfo = data;
			_self.expressPipei();
			// TODO 下面执行刷新的方法
		})
	},
	computed: {
		couponList() {
			return this.$store.state.user.couponList;
		},
		canUseCouponList(){
			// 是否可用优惠券
			// this.priceInfo.countPrice status==2 未使用
			let coupon = this.couponList.filter(item => item.status==2&&(item.min_amount<=this.priceInfo.countPrice));
			return coupon;
		},
		// 运费模板
		baseConfig() {
			return this.$store.state.pub.baseConfig;
		},
		// 商品数量
		goodsListCountNums(){
			let nums = 0;
			this.goodsList.forEach(e=>nums+=e.nums);
			return nums;
		},
		
	},
	methods:{
		// 获取运费模板信息
		async getExpressInfo(){
			console.log('来获取运费模板信息了哦')
			await this.$u.api.getBaseInfoAjax().then(({data})=>{
				this.$store.commit('pub/commitBaseConfig',data);
				console.log('运费模板信息获取成功')
			}).catch(()=>{
				
			})
		},
		// 邮费匹配
		expressPipei(){
			// extra_express_fee
			if(!_self.addressInfo.id){
				// 没有地址
				console.log('没有地址')
				return;
			}
			if(!this.baseConfig.express_type){
				// 没有邮费模板
				console.log('没有邮费模板')
				return;
			}
			const base_express_fee = Number(this.baseConfig.base_express_fee);
			const extra_express_fee = Number(this.baseConfig.extra_express_fee);
			if(this.baseConfig.express_type=='2'){
				// 不包邮
				console.log('不包邮>>>>本书',_self.goodsListCountNums);
				this.priceInfo.freight = base_express_fee+extra_express_fee*(_self.goodsListCountNums-1);
				console.log(this.priceInfo.freight);
				return;
			}
			if(this.baseConfig.express_type=='3'){
				// 全场满x包邮
				console.log('全场满x包邮')
				if(this.priceInfo.countPrice>=this.baseConfig.min_buy_amount){
					// 价格满了，包邮
					this.priceInfo.freight = 0;
				}else{
					this.priceInfo.freight = base_express_fee+extra_express_fee*(_self.goodsListCountNums-1);
				}
				return;
			}
			if(this.baseConfig.express_type=='4'){
				// 全场满x包邮
				console.log('全场满x包邮')
				const codes = this.baseConfig.codes.split(',');
				const ucodes = this.addressInfo.addressCode.split(',')[0];
				console.log(codes,ucodes);
				if(codes.includes(ucodes)){
					// 片段是否偏远地区
					this.priceInfo.freight = base_express_fee+extra_express_fee*(_self.goodsListCountNums-1);
				}else if(this.priceInfo.countPrice>=this.baseConfig.min_buy_amount){
					this.priceInfo.freight = 0;
				}else{
					this.priceInfo.freight = base_express_fee+extra_express_fee*(_self.goodsListCountNums-1);
				}
				return;
			}
		},
		// 选择地址
		selAddress(){
			uni.navigateTo({
				url: '/pages-mine/pages/address/list?isSelect=true&isBack=true'
			});
		},
		async getDefaultAddress(){
			console.log('执行11111111111')
			await this.$u.api.getDefaultAddressAjax().then(({data})=>{
				if(!data) return
				this.addressInfo = {
					...data,
					address:data.province+data.city+data.area,
					detail_address:data.province+data.city+data.area+data.street,
				};
				
			})
		},
		// 计算总价
		comoutedPrice(){
			let price = 0;
			this.goodsList.map(item => {
				price += Number(item.selectdSku.price_selling) * item.nums
			});			
			this.priceInfo.countPrice = parseFloat(price).toFixed(2);
		},
		
		// 选择优惠券
		selCouponFun(){
			this.$refs.selCouponPopupRef.showPopup({couponList:this.couponList,usingCoupon:this.usingCoupon})
		},
		// 确认选择
		confirmSelCoupon(e){
			console.log('使用中，，',e);
			this.usingCoupon = e;
			this.priceInfo.discount = e.amount||0;
			// this.$forceUpdate();
		},
		// 提交订单
		submitOrder(){
			if(!this.addressInfo?.id){
				this.$u.toast('请选择收货地址');
				return false;
			}
			if(this.cartIds){
				// 购物车订单
				this.submitCartGoods();
				return;
			}
			// 常规订单
			this.submitGoods();
		},
		// 提交购物车商品
		submitCartGoods(){
			let json = {
				address_id:this.addressInfo.id,
				cart_ids:this.cartIds,
				remark: this.remark,
				user_coupon_id:this.usingCoupon.id,
			}
			this.$u.api.submitCartOrderAjax(json).then(({code,data})=>{
				if(code==1){
					console.log(data);
					uni.redirectTo({
						url: '/pages-mall/pages/order/pay?orderInfo='+encodeURIComponent(JSON.stringify(data))
					});
				}
			})
		},
		// 直接购买单个商品
		submitGoods(){
			const info = this.goodsList[0];
			let json = {
				goods_id: info.id,
				nums: info.nums,
				address_id: this.addressInfo.id,
				pay_type: 'wx_miniapp',
				sku_id: info.selectdSku.id,
				remark: this.remark,
				user_coupon_id:this.usingCoupon.id,
			};
			this.$u.api.submitOrderAjax(json).then(({code,data})=>{
				if(code==1){
					console.log(data);
					uni.redirectTo({
						url: '/pages-mall/pages/order/pay?orderInfo='+encodeURIComponent(JSON.stringify(data))
					});
				}
			})
		},
		getUserCouponList(){
			if(this.loading)return false;
			this.$u.api.getUserCouponListAjax(1).then(({code,data})=>{
				// this.discountsList = data.data;
				this.$store.commit('user/commitCouponList',data.data);
			}).catch(()=>{
				// this.$store.commit('user/commitCouponList');
			})
		},
		
	},
};
</script>
<style lang="scss" scoped>
.page {
	padding-top: 1rpx;
	padding-bottom: 140rpx;
}
.address{
	margin: 20rpx 0;
	padding: 0 30rpx;
	background-color: $app-theme-bg-color;
}
.goods {
	// background-color: $app-theme-bg-color;
	padding: 0 30rpx;
}
.conbg{
	background-color: #fff;
}
.addbtn{
	padding: 25rpx;
	font-size: 36rpx;
	color: $app-theme-color;
	background-color: #fff;
}
</style>
