<template>
	<view class="ordersubmit">
		<view class="add-box" @click="chosenAddress(ds.address.id)">
			<view v-if="address.province && address.province != ''" class="add-info">
				<view class="address">{{ address.province + address.city + address.district }}</view>
				<view class="area">{{ address.detail }}</view>
				<view class="address">
					<text style="margin-right: 10px;">{{ address.name }}</text>
					<text>{{ address.mobile }}</text>
				</view>
			</view>
			<view v-else class="add-info">
				<span style="position: relative;top: 16rpx;">请选择</span>
			</view>
			<view class="arrow"><u-icon name="arrow" size="32" color="#444"></u-icon></view>
		</view>
		<view class="pay">
			<view>支付方式</view>
			<view style="text-align: right;">在线支付</view>
		</view>
		<view class="goods" v-for="(x, i) in mchs" :key="i">
			<view class="store">
				<u-icon name="shop-o" size="30" color="#232323"></u-icon>
				<text style="margin-left: 10px;">{{ x.mch.name }}</text>
			</view>
			<view class="store-list">
				<template v-if="x.goods_list.length == 1">
					<view class="goodbox" v-for="(y, yi) in x.goods_list" :key="yi">
						<image :src="y.cover_pic" mode="aspectFill" class="image" />
						<view class="goodinfo">
							<view class="name">{{ y.name }}</view>
							<view class="attr">已选择：
								<span v-for="(item,index3) in y.specificationNameList" :ket="index3">
									{{item}}
								</span>
							</view>
							<view class="price">
								<view class="left" :style="{ color: mc }">
									<text class="small">￥</text>
									<text>{{ y.goods_attr.price }}</text>
									<!-- <text class="small">.{{ y.goods_attr.price.split('.')[1] || '00' }}</text> -->
								</view>
								<view class="right">x{{ y.num }}</view>
							</view>
							<view v-if="y.address_disabled">
								<u-tag size="mini" text="不在配送范围内" type="warning" />
							</view>
						</view>
					</view>
				</template>
				<template v-else>
					<view class="goodboxmore">
						<view class="good-list">
							<view style="white-space: nowrap"><image v-for="(y, yi) in x.goods_list" :key="yi" :src="y.cover_pic" mode="aspectFill" class="item" /></view>
						</view>
						<view class="infos">
							<view class="text">共{{ x.goods_list.length }}件</view>
							<u-icon name="ellipsis" size="36" @click="showGoodListHandler(i)"></u-icon>
						</view>
					</view>
				</template>
				<view class="peisong">
					<view>配送</view>
					<view style="text-align: right; padding-right: 5px;">{{ x.delivery.send_type_name }}</view>
					<u-icon name="ellipsis" size="36" @click="showPeisongHandler(i)"></u-icon>
					<peisong :list="x.delivery.send_type_list" :index="i" @close="changeSendTypeHandler" :send-type="x.delivery.send_type" v-if="x.delivery.showDelivery"></peisong>
				</view>
				<view class="liuyan"><u-field padding="0px" label-width="80" v-model="BuyerMessage" label="留言" placeholder="建议留言前先与客服沟通确认"></u-field></view>
			</view>
		</view>
		<view class="discountbox">
			<view class="filed">
				<view class="left">优惠券</view>
				<view class="right">
					<text class="content" v-if="mchs[0].coupon.user_coupon_id == 0 && couponList.length>0">选择优惠券</text>
					<text class="content" v-else-if="couponList.length==0">暂无优惠券</text>
					<text class="content" v-else :style="{ color: mc }">已优惠{{ mchs[0].coupon.coupon_discount }}元</text>
					<u-icon name="ellipsis" size="36" v-if="couponList.length > 0" @click="showCouponHandler"></u-icon>
				</view>
			</view>
			<view class="filed" v-if="integral.can_use">
				<view class="left">积分抵扣</view>
				<view class="right">
					<text class="content" :style="{ color: secondary }">{{ `使用${integral.use_num}积分抵扣${integral.deduction_price}元` }}</text>
					<u-checkbox-group><u-checkbox v-model="userInt" :active-color="mc" @change="changeUseInt" :icon-size="28" shape="circle"></u-checkbox></u-checkbox-group>
				</view>
			</view>
			<!-- <view class="filed">
        <view class="left">积分赠送</view>
        <view class="right">
          <text class="content">100积分</text>
          <u-icon name="ellipsis" size="36"></u-icon>
        </view>
      </view>-->
		</view>
		<view class="discountbox">
			<view class="filed">
				<view class="left">商品金额</view>
				<view class="right">
					<text class="price">￥{{ goodPrice.toFixed(2) }}</text>
				</view>
			</view>
			<view class="filed">
				<view class="left">运费</view>
				<view class="right">
					<text class="price" :style="{ color: mc }">+￥{{ expressPrice.toFixed(2) }}</text>
				</view>
			</view>
			<view class="filed">
				<view class="left">优惠</view>
				<view class="right">
					<text class="price" :style="{ color: mc }">-￥{{ couponPrice.toFixed(2) }}</text>
				</view>
			</view>
			<view class="filed" v-if="integral.can_use">
				<view class="left">积分抵扣</view>
				<view class="right">
					<text class="price" :style="{ color: mc }">-￥{{ userInt ? integral.deduction_price.toFixed(2) : '0.00' }}</text>
				</view>
			</view>
		</view>
		<view class="btton-box">
			<view class="left" :style="{ color: mc }">
				<text>￥</text>
				<text class="bold">{{ ds.total_price }}</text>
				<!-- <text>.{{ ds.total_price.split('.')[1] || '00' }}</text> -->
			</view>
			<view class="right">
				<u-button
					:disabled="!address_enable"
					size="80"
					:ripple="true"
					shape="circle"
					@click="submitOrderHandler"
					:custom-style="{
						backgroundColor: mc,
						height: '80rpx',
						color: '#FFF',
						fontSize: '14px'
					}"
				>
					<u-loading mode="circle" style="margin-right: 5px;" v-if="submitOrder"></u-loading>
					提交订单
				</u-button>
			</view>
		</view>
		<coupon v-if="couponList.length > 0 && showCoupon" :list="couponList" :current="formData.list[0].user_coupon_id" @close="closeCouponHandler"></coupon>
		<view class="notOption" v-if="submitOrder"></view>
		<good-list :list="goodData" v-if="showGoodList" @close="closeGoodListHandler"></good-list>
		<payCom v-if="payBtn" :payInfo="payInfo" @closePay="closePay"></payCom>
		<u-toast ref="uToast" />
		<u-popup v-model="payExit" mode="center" :mask-close-able="false">
			<view style="background:#fff;width:500rpx">
				<view style="padding:10px 0 0 10px">提交失败</view>
				<view style="text-align:center;padding-bottom:40rpx">
					<view style="margin:80rpx 0">支付取消</view>
					<span @click="exitPay" style="padding:10rpx 50rpx;color:#fff;background:#19be6b;border-radius: 12px;">确定</span>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import payCom from '@/components/pay/pay';
import peisong from '@/components/peisong/index';
import coupon from '@/components/coupon/index';
import goodList from '@/components/goods/order-good-list';
export default {
	components: {
		payCom,
		peisong,
		coupon,
		goodList
	},
	data() {
		return {
			address_enable:'',
			payExit: false,
			payBtn: false,
			formData: {
				list: [
					{
						mch_id: 0,
						goods_list: [],
						distance: 0,
						remark: '',
						order_form: [],
						use_integral: 0,
						user_coupon_id: 0
					}
				],
				address_id: 0
			},
			formdata: {
				// DetailList: [{ GoodsId: 31, Number: 1, SpecificationSort: '1' }, { GoodsId: 38, Number: 1, SpecificationSort: '0:0' }],
				// Use_Integral: 0,
				// User_Coupon_Id: 0,
				// DeliveryMethod: 0,
				// AddressId: 0
			},
			DeliveryMethod: '',

			pageTitle: '填写订单',
			address: {},
			mchs: [],
			mc: '',
			ds: {
				total_price: '0.00'
			},
			expressPrice: 0.0,
			goodPrice: 0.0,
			couponPrice: 0.0,
			integral: {
				can_use: false,
				use: false,
				use_num: 0,
				deduction_price: 0
			},
			secondary: '',
			userInt: false,
			loading: true,
			couponList: [],
			showCoupon: false,
			submitOrder: false,
			isLeave: false,
			goodData: [],
			showGoodList: false,
			DetailList: [],
			IsFormShoppingCart: 2,
			adressInfo: {},
			payInfo: {
				OpenId: 'ow_7I5XC1-RGwwk8QANBmWKYKmOc',
				OrderId: '',
				OrderPayType: 1,
				GoodsName: ''
			},
			ShoppingCartIdList: [],
			BuyerMessage:'',
		};
	},
	onLoad(option) {
		if (option.goods) {
			this.formData.list[0].goods_list = JSON.parse(decodeURIComponent(option.goods));
		} 
		if (option.formData) {
			this.formData = JSON.parse(decodeURIComponent(option.formData));
			this.formdata = JSON.parse(decodeURIComponent(option.formData));
		}
		if (option.IsFormShoppingCart) {
			this.IsFormShoppingCart = option.IsFormShoppingCart;
		}
		if (option.ShoppingCartIdList) {
			this.ShoppingCartIdList = JSON.parse(option.ShoppingCartIdList);
		}
		this.payInfo.OpenId=uni.getStorageSync('mall_UserInfo').OpenId;
		// else {
		//      uni.redirectTo({
		//         url: '/pages/index/index'
		//      });
		//    }
		this.initPage();
		this.mc = this.$uiConfig.mainColor;
		this.secondary = this.$uiConfig.secondary;
		
	},
	onShow() {
		this.init();

		if (this.isLeave) {
			uni.navigateBack({
				delta: 1
			});
		}
	},
	methods: {
		exitPay() {
			this.payExit = false;
			uni.redirectTo({
			  url: "/pages/order/index/index?status=0",
			});
		},
		closePay() {
			this.payBtn = false;
			this.payExit = true;
		},
		closeGoodListHandler() {
			this.goodData = [];
			this.showGoodList = false;
		},
		showGoodListHandler(i) {
			this.goodData = this.mchs[i].goods_list;
			this.showGoodList = true;
		},
		// 提交订单
		submitOrderHandler() {
			let that = this;
			if (that.adressInfo.Consignee == '') {
				this.$refs.uToast.show({
					title: '请选择收货信息！',
					type: 'warning'
				});
				return;
			}
			if (!this.submitOrder) {
				this.submitOrder = true;
				uni.requestSubscribeMessage({
					tmplIds: this.ds.template_message_list,
					complete(res) {
						console.log(res)
						that.submitOrder = false;
						let form = {};
						form.Consignee = that.adressInfo.Consignee;
						form.Mobile = that.adressInfo.Mobile;
						form.Province = that.adressInfo.Province;
						form.City = that.adressInfo.City;
						form.District = that.adressInfo.District;
						form.ShoppingAddress = that.adressInfo.ShoppingAddress;
						form.BuyerMessage = that.BuyerMessage;
						form.DeliveryMethod = that.formdata.DeliveryMethod;
						form.DetailList = that.DetailList;
						form.User_Coupon_Id = that.formdata.User_Coupon_Id;
						form.CouponMoney = that.couponPrice;
						form.FreightMoney = that.expressPrice;
						form.Income = that.ds.total_price;
						form.IsFormShoppingCart = that.IsFormShoppingCart;
						form.Use_Integral = that.formdata.Use_Integral;
						form.ShoppingCartIdList = that.ShoppingCartIdList;
						form.AnchorName = uni.getStorageSync("AnchorName")?uni.getStorageSync("AnchorName").AnchorName:''; //直播名称
						that.request2(
							{
								url: '/api/AppletOrder/SetAppletGoodsOrderInfo',
								data: form
							},
							res => {
								if (res.resultCode == 1) {
									that.payBtn = true;
									that.payInfo.OrderId = res.data.OrderId;
									that.payInfo.total_price = that.ds.total_price;
								}
								else{
									that.$refs.uToast.show({
										title: res.data.message,
										type: 'warning'
									});
								}
								uni.hideNavigationBarLoading();
							}
						);
					
					}
				});
			}
		},
		closeCouponHandler(e) {
			if (e != -1) {
				// this.formData.list.forEach(x => {
				// 	x.user_coupon_id = e;
				// });
				this.formdata.User_Coupon_Id = e;
				this.init();
			}
			this.showCoupon = false;
		},
		showCouponHandler() {
			this.showCoupon = true;
		},
		initCoupon() {
			let ProductList = [];
			this.DetailList = [];

			this.mchs.forEach(item => {
				item.goods_list.forEach(list => {
					let obj = {
						GoodsClassId: list.categoryIdList,
						GoodsPrice: list.total_price,
						ProductId: list.id
					};
					let obj1 = {
						SpecificationSort: list.goods_attr.sign_id,
						Number: list.num,
						GoodsId: list.id,
						SpecificationList: list.specificationNameList
					};
					ProductList.push(obj);
					this.DetailList.push(obj1);
				});
			});

			this.request2(
				{
					url: '/api/AppletCoupon/GetNoUseCouponList',
					data: { ProductList: ProductList }
				},
				res => {
					if (res.resultCode == 1) {
						this.couponList = res.data;
					}
				}
			);
			// let h = this.apiheader();
			// h["content-type"] = "application/x-www-form-urlencoded";
			// this.request(
			//   {
			//     url: "",
			//     data: {
			//       r: "api/order/usable-coupon-list",
			//       form_data: JSON.stringify(this.formData.list[0]),
			//     },
			//     header: h,
			//     method: "POST",
			//   },
			//   (res) => {
			//     this.couponList = res.data.list;
			//   }
			// );
		},
		changeSendTypeHandler(e) {
			let i = e.index;

			let obj = this.mchs[i];
			obj.delivery.showDelivery = false;
			this.$set(this.mchs, i, obj);
			this.$forceUpdate();
			if (e && e.val) {
				if (this.mchs[i].delivery.send_type != e.val) {
					this.formdata.DeliveryMethod = e.val;
					this.init();
				}
			}
		},
		showPeisongHandler(x) {
			let obj = this.mchs[x];
			obj.delivery.showDelivery = true;
			this.$set(this.mchs, x, obj);
			this.$forceUpdate();
		},
		chosenAddress(id) {
			uni.navigateTo({
				url: '/pages/address/address?form=ordersubmit&id=' + id
			});
		},
		changeUseInt(e) {
			this.userInt = e.value;
			// this.formData.list.forEach(x => {
			// 	x.use_integral = this.userInt ? 1 : 0;
			// 	this.formData.Use_Integral = this.userInt ? 1 : 0;
			// });
			this.formdata.Use_Integral = this.userInt ? 1 : 0;
			this.init();
		},
		initPage() {
			let currentPages = getCurrentPages();
			let u = '/' + currentPages[currentPages.length - 1].route;
			let pages = uni.getStorageSync('basedata') ? uni.getStorageSync('basedata').bar_title : [];
			pages.forEach(x => {
				if (x.value == u) {
					this.pageTitle = x.new_name ? x.new_name : x.name;
				}
			});
			uni.setNavigationBarTitle({
				title: this.pageTitle
			});
		},
		init() {
			this.loading = true;
			this.request2(
				{
					url: '/api/AppletOrder/GetAppletGoodsSettlementInfoForZY',
					data: this.formdata
				},
				res => {
					this.loading = false;
					if (res.resultCode == 1) {
						this.address = res.data.address;
						this.address_enable=res.data.address_enable;
						this.mchs = res.data.mch_list;
						this.payInfo.GoodsName = this.mchs[0].goods_list[0].name.slice(0,10);
						this.formdata.DeliveryMethod=this.mchs[0].delivery.send_type;
						this.ds = res.data;
						this.expressPrice = 0.0;
						this.goodPrice = 0.0;
						this.couponPrice = 0.0;
						if(res.data.total_price<0){
							this.ds.total_price =0
						}
						this.integral = {
							can_use: false,
							use: false,
							use_num: 0,
							deduction_price: 0
						};
						this.formatPrice();
						this.initCoupon();
						// this.formatAttr();
						this.adressInfo = {
							Consignee: this.address.name,
							Mobile: this.address.mobile,
							Province: this.address.province_id,
							City: this.address.city_id,
							District: this.address.district_id,
							ShoppingAddress: this.address.detail
						};
					}

					uni.hideNavigationBarLoading();
				}
			);
			// let h = this.apiheader();
			// h["content-type"] = "application/x-www-form-urlencoded";
			// this.request(
			//   {
			//     url: "",
			//     data: {
			//       r: "api/order/preview",
			//       form_data: JSON.stringify(this.formData),
			//     },
			//     header: h,
			//     method: "POST",
			//   },
			//   (res) => {
			//     this.address = res.data.address;
			//     this.mchs = res.data.mch_list;
			//     this.ds = res.data;
			//     this.expressPrice = 0.0;
			//     this.goodPrice = 0.0;
			//     this.couponPrice = 0.0;
			//     this.integral = {
			//       can_use: false,
			//       use: false,
			//       use_num: 0,
			//       deduction_price: 0,
			//     };
			//     this.formatPrice();
			//     this.formatAttr();
			//     this.loading = false;
			//   }
			// );
		},
		formatPrice() {
			this.mchs.forEach(x => {
				x.delivery.showDelivery = false;
				x.delivery.send_type_list.forEach(y => {
					if (y.value == x.delivery.send_type) {
						x.delivery.send_type_name = y.name;
					}
				});
				this.goodPrice += parseFloat(x.total_goods_price);
				this.expressPrice += parseFloat(x.express_price);
				this.couponPrice += parseFloat(x.coupon.coupon_discount || 0.0);
				if (x.integral.can_use) {
					this.integral.can_use = true;
					this.integral.use = false;
					this.integral.use_num += x.integral.use_num;
					this.integral.deduction_price += parseFloat(x.integral.deduction_price);
				}
			});
		},
		formatAttr() {
			this.mchs.forEach(x => {
				this.userInt = x.integral.use;
				x.goods_list.forEach(y => {
					let attrStr = '';
					y.attr_list.forEach((z, i) => {
						if (i > 0) {
							attrStr += ' ';
						}
						attrStr += z.attr_group_name + ' ' + z.attr_name;
					});
					y.attrStr = attrStr;
				});
			});
		}
	}
};
</script>

<style>
button[disabled]{
	color: rgba(0,0,0,.3)!important;
	background-color: #f7f7f7!important;

}
/* @font-face {
  font-family: "oswald";
  src: url("https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/smallapp/Oswald-Regular.ttf");
} */
.ordersubmit {
	min-height: 100vh;
	padding: 0 5px;
	background: #f6f6f6;
	padding-bottom: 40px;
	font-family: 'oswald';
}

.ordersubmit .add-box {
	padding: 10px;
	background: #fff;
	display: flex;
	align-items: center;
	position: relative;
	border-radius: 10px;
	overflow: hidden;
	margin-bottom: 12px;
}
.ordersubmit .add-box .arrow {
	width: 16px;
	height: 16px;
}
.ordersubmit .add-box .add-info {
	width: 1px;
	flex: 1;
	min-height: 60px;
	display: block;
	padding: 10px 0;
}
.ordersubmit .add-box .add-info .address {
	font-size: 13px;
	color: #333;
	margin-bottom: 5px;
}
.ordersubmit .add-box .add-info .area {
	font-size: 18px;
	color: #000;
	margin-bottom: 5px;
	font-weight: 600;
}
.ordersubmit .add-box::before {
	position: absolute;
	right: 0;
	bottom: 0;
	left: 0;
	height: 2px;
	background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
	background-size: 80px;
	content: '';
}
.ordersubmit .pay {
	margin-bottom: 12px;
	background: #fff;
	border-radius: 10px;
	padding: 10px;
	align-items: center;
	height: 50px;
	color: #232323;
	display: flex;
}
.ordersubmit .pay view {
	flex: 1;
}
.ordersubmit .goods {
	padding: 20px 10px;
	margin-bottom: 12px;
	background: #fff;
	border-radius: 10px;
}
.ordersubmit .goods .store {
	color: #000;
	margin-bottom: 20px;
	display: flex;
}
.ordersubmit .goodbox {
	margin-bottom: 20px;
	display: flex;
}
.ordersubmit .goodbox .image {
	width: 200rpx;
	height: 200rpx;
	border-radius: 5px;
	margin-right: 10px;
}
.ordersubmit .goodbox .goodinfo {
	width: 1px;
	flex: 1;
}
.ordersubmit .goodbox .goodinfo .name {
	height: 18px;
	font-size: 14px;
	color: #232323;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 15px;
}
.ordersubmit .goodbox .goodinfo .attr {
	height: 16px;
	font-size: 12px;
	color: #999;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 12px;
}
.ordersubmit .goodbox .goodinfo .price {
	display: flex;
	align-items: center;
}
.ordersubmit .goodbox .goodinfo .price .left {
	font-size: 20px;
	font-family: 'oswald';
	width: 1px;
	flex: 1;
}
.ordersubmit .goodbox .goodinfo .price .left .small {
	font-size: 13px;
}
.ordersubmit .goodbox .goodinfo .price .right {
	color: #444;
	font-size: 13px;
}
.ordersubmit .goodboxmore {
	margin-bottom: 20px;
	display: flex;
}
.ordersubmit .goodboxmore .good-list {
	display: flex;
	flex: 1;
	overflow-x: auto;
}
.ordersubmit .goodboxmore .good-list .item {
	width: 70px;
	height: 70px;
	border-radius: 5px;
	margin-right: 10px;
}
.ordersubmit .goodboxmore .infos {
	display: flex;
	width: 80px;
}
.ordersubmit .goodboxmore .infos .text {
	text-align: center;
	font-size: 13px;
	width: 57px;
	margin-right: 5px;
	line-height: 70px;
}
.ordersubmit .store-list .peisong {
	margin-bottom: 20px;
	display: flex;
	align-items: center;
	color: #333;
}
.ordersubmit .store-list .peisong view {
	flex: 1;
}
.ordersubmit .store-list .peisong view:last-child {
	text-align: right;
}
.ordersubmit .discountbox {
	padding: 20px 0;
	margin-bottom: 20px;
	background: #fff;
	border-radius: 10px;
	display: block;
}
.ordersubmit .filed {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20px;
	padding: 0 10px;
}
.ordersubmit .filed:last-child {
	margin-bottom: 0;
}
.ordersubmit .filed .left,
.ordersubmit .filed .right {
	flex: 1;
	color: #232323;
}
.ordersubmit .filed .left {
	width: 120px;
}
.ordersubmit .filed .right {
	text-align: right;
	display: flex;
}
.ordersubmit .filed .right .icon {
	width: 18px;
	height: 18px;
}
.ordersubmit .filed .right .content {
	flex: 1;
	text-align: right;
	margin-right: 5px;
}
.ordersubmit .filed .right .price {
	font-size: 16px;
	flex: 1;
	text-align: right;
	font-family: 'oswald';
}
.ordersubmit .btton-box {
	height: 50px;
	display: flex;
	padding: 5px 10px;
	border-top: 1px solid #f5f5f5;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	align-items: center;
	background: #fff;
	z-index: 3;
}
.ordersubmit .notOption {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background: transparent;
	z-index: 2;
}
.ordersubmit .btton-box .left {
	font-size: 16px;
	flex: 1;
	font-family: 'oswald';
}
.ordersubmit .btton-box .left .bold {
	font-size: 24px;
}
.ordersubmit .btton-box .right {
	width: 120px;
}
</style>
