<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		{include file="public/head"}
		<link href="/system/frame/css/style.min.css?v=3.0.0" rel="stylesheet">
		<title>{$title|default=''}</title>
		<style>
			.flex {
				display: flex;
				justify-content: flex-start;
				align-items: center;
			}

			.no-shink {
				flex-shrink: 0;
			}

			.mar-l-10 {
				margin-left: 10px;
			}

			.mar-b-10 {
				margin-bottom: 10px;
			}

			.padd-15 {
				padding: 0 15px !important;
			}

			.shopBOx {
				margin: 15px 10px !important;
			}

			.alertBottom {
				position: fixed !important;
				bottom: 0;
				left: 0;
				padding-left: 30px !important;
				width: 100%;
				background-color: #ffffff;
			}

			.shopImg {
				width: 100px;
				height: 100px;
			}

			.clamp2 {
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
			}

			.itemStart {
				align-items: flex-start;
			}

			.flexcontent {
				justify-content: center;

			}

			.text-cente {
				text-align: center
			}

			.demo-spin-icon-load {
				animation: ani-demo-spin 1s linear infinite;
			}

			@keyframes ani-demo-spin {
				from {
					transform: rotate(0deg);
				}

				50% {
					transform: rotate(180deg);
				}

				to {
					transform: rotate(360deg);
				}
			}

			.demo-spin-col {
				height: 100px;
				position: relative;
				border: 1px solid #eee;
			}
		</style>
	</head>
	<body>
		<div class="wrapper wrapper-content">
			<div class="row">
				<div class="col-sm-12">
					<div class="ibox float-e-margins ">
						<div class="ibox-title">
							<h5>在线下单</h5>
						</div>
						<div id="store-attr" class="mp-form" v-cloak="">
							<Row class="searchBox padd-15 mar-b-10 mar-l-10" v-if="UserCard">
								<i-Col span="6">
									<div class="flex">
										<span class="no-shink">当前会员卡号：{{UserCard}} &nbsp; 会员余额：{{userData.now_money}}
											&nbsp; 消费券：{{userData.integral}} &nbsp; 手机号：{{userData.phone}}</span>
									</div>
								</i-Col>
							</Row>
							<Row class="searchBox padd-15" v-if="UserCard">
								<i-Col span="6">
									<div class="flex">
										<span class="no-shink mar-l-10">是否消费券：</span>
										<radio-group v-model="is_consumer" type="button">
											<Radio :label="1">是</Radio>
											<Radio :label="0">否</Radio>
										</radio-group>
									</div>
								</i-Col>
								<i-Col span="12">
									<div class="flex">
										<span class="no-shink mar-l-10">条形码：</span>
										<i-Input ref="code" placeholder="请扫描或输入条形码" @on-enter="getShopNum"
											v-model="shopId" type="text"></i-Input>
										<i-Button class="mar-l-10" type="primary" @click="getShopNum">添加商品</i-Button>
									</div>
								</i-Col>
							</Row>
							<Row class="searchBox padd-15" v-else>
								<i-Col span="8">
									<div class="flex">
										<span class="no-shink">会员卡号：</span>
										<i-Input ref="usercard" placeholder="请输入会员卡号" v-model="userCardInput"
											type="text" @on-enter="checkedUserCard"></i-Input>
										<i-Button class="mar-l-10" type="primary" @click="checkedUserCard">开始下单
										</i-Button>
									</div>
								</i-Col>
							</Row>
							<Row class="searchBox padd-15 shopBOx" v-if="UserCard">
								<i-Col span="24">
									<div>
										<h4 class="mar-b-10">当前商品信息</h4>
										<Row class="searchBox padd-15 mar-b-10 ">
											<i-Col span="8">
												<h4>商品信息</h4>
											</i-Col>
											<i-Col span="4">
												<h4 class="text-cente"> 商品单价</h4>
											</i-Col>
											<i-Col span="4">
												<h4 class="text-cente"> 商品总价</h4>
											</i-Col>
											<i-Col span="4">
												<h4 class="text-cente"> 商品类型</h4>
											</i-Col>
											<i-Col span="4">
												<h4 class="text-cente">
													操作 </h4>
											</i-Col>
										</Row>
										<Row type="flex" align="middle" class="searchBox padd-15 mar-b-10"
											v-for="(ls,ind) in shopList" :key="ls.id">
											<i-Col span="8">
												<div class="flex itemStart">
													<img :src="ls.image" class="shopImg">
													<div class="titleBox mar-l-10">
														<div class="clamp2" :title="ls.name">{{ls.name}}</div>
														<div>
															规格：{{ls.typeName}}
														</div>
														<div>
															数量：{{+ls.num}}
														</div>
													</div>
												</div>
											</i-Col>
											<i-Col span="4" class="text-cente">
												{{ls.price}}
											</i-Col>
											<i-Col span="4" class="text-cente">
												{{domNum(ls.price*ls.num)}}
											</i-Col>
											<i-Col span="4" class="text-cente">
												{{+ls.is_consumer==0?'普通商品':'消费券商品'}}
											</i-Col>
											<i-Col span="4">
												<div class="flex flexcontent">
													<i-Button type="error" size="small" @click="delShop(ls,ind)">删除
													</i-Button>
													<i-Button class="mar-l-10" type="success" size="small"
														@click="changeNumShop(ls,1)">增加
													</i-Button>
													<i-Button class="mar-l-10" type="warning" size="small"
														@click="changeNumShop(ls,-1)">减少
													</i-Button>
												</div>
											</i-Col>
										</Row>
									</div>
								</i-Col>
							</Row>
							<Row class="searchBox padd-15 mar-b-10 alertBottom" v-if="UserCard">
								{eq name="type" value="0"}
								<i-Col span="6">
									<div class="flex">
										<span class="no-shink">选择商家：</span>
										<i-Select name="store_id" v-model="form.store_id" style="width: 80%" filterable>
											{volist name="store" id="v" }
											<i-Option value="{$v.id}">{$v.name}（id:{$v.id}）</i-Option>
											{/volist}
										</i-Select>
									</div>
								</i-Col>
								{/eq}
								<i-Col span="6">
									<div class="flex">
										<span class="no-shink mar-l-10">支付方式：</span>
										<i-Select name="store_id" v-model="form.pay_type" default-label="微信"
											style="width: 80%" filterable>
											<!--                                    <i-Option value="alipay">支付宝</i-Option>-->
											<!--                                    <i-Option value="weixin">微信</i-Option>-->
											<i-Option value="jialie">嘉联支付</i-Option>
											-->
											<i-Option value="yue">余额</i-Option>
											<i-Option value="integral">消费券</i-Option>
											<!--                                    <i-Option value="consumer">消费券</i-Option>-->
											<i-Option value="offline">线下支付</i-Option>
										</i-Select>
									</div>
								</i-Col>
								<i-Col span="6">
									<div class="flex">
										<span class="no-shink mar-l-10">当前金额：￥{{allPayMoney}}</span>
										<i-Button class="mar-l-10" type="success" @click="submit">确认下单</i-Button>
									</div>
								</i-Col>
							</Row>
						</div>
					</div>
				</div>
			</div>
		</div>

		<script>
			mpFrame.start(function(Vue) {
				new Vue({
					data: function() {
						return {
							form: {
								store_id: '{eq name="type" value="1"}{$store.0.id}{/eq}', //商家id
								pay_type: 'offline' //支付类型
							},
							shopList: [], //当前选中的商品
							userCardInput: '', //用户输入内容
							UserCard: '', //当前选中的会员卡号
							userId: '', //当前选中的用户id
							userData: {}, //保存用户信息
							shopId: '', //当前商品条形码
							is_consumer: 0, //当前是否消费券
							lodingAddCart: false, //判断是否正在加入购物车
						}
					},
					mounted() {
						const that = this;
						//获取会员卡号焦点
						that.$nextTick(function() {
							that.$refs.usercard.focus();
						})
					},
					computed: {
						allPayMoney() {
							let money = 0;
							for (let i = 0; i < this.shopList.length; i++) {
								const item = this.shopList[i]
								money += item.price * item.num
							}
							return +(money.toFixed(2));
						}
					},
					methods: {
						// 向下取整舍弃数
						domNum: function(value) {
							return Math.floor(value*100)/100
						},
						// 修复订单
						async orderContrast() {
							// 开始处理数据
							const ind = layer.load(1,{
								shade: 0.1
							})
							const that = this;
							const userCart = (await $eb.axios.get('{:Url("lst")}' + '?uid=' + that.userId))
								.data.data.valid; //线上购物车商品
							const shopList = that.shopList; //本地购物车商品
							const errorCartList = []; //错误数据保存
							for (let i = 0; i < userCart.length; i++) {
								const uObj = userCart[i];
								for (let s = 0; s < shopList.length; s++) {
									const sObj = shopList[s];
									// 判断是否同一个商品
									if (uObj.cartId == sObj.cartId) {
										// 判断是否数据不对
										if (+uObj.cart_num < +sObj.num) {
											// 处理错误数据
											await that.changeCartShop(sObj.cartId, sObj.num)
										}
										break
									}
								}
							}
							layer.alert('修复成功')
							layer.close(ind);
						},
						//选中用户卡号
						checkedUserCard(e) {
							const that = this;
							// layer.msg('加载中请稍等。。。', {
							//   icon: 16
							//   ,shade: 0.01
							// });
							layer.load(1,{
								shade: 0.1
							})
							if (that.userCardInput.length == 12 || that.userCardInput.length == 15 || that
								.userCardInput.length == 8 || that.userCardInput.length == 11 || that
								.userCardInput == '1') {
								//初始化用户数据
								that.userId = '';
								that.userData = {}
								//请求获取用户信息
								$eb.axios.post('{:Url("getCardNo")}' + '?card_no=' + that.userCardInput).then(
									function(res) {
										console.log(res)
										const data = res.data;
										if (data.status == 200) {
											that.UserCard = that.userCardInput;
											that.userId = data.data.uid;
											that.userData = data.data.user
											that.delCartAll()
										} else {
											layer.closeAll('loading');
											layer.msg(data.msg, {
												icon: 5
											});
										}
									}).catch(function(err) {
										layer.closeAll('loading');
										console.log(err);
									})
								//设置获取焦点
							} else {
								layer.closeAll('loading');
								layer.msg('请输入8位,12位,17位卡号会员卡号,或输入1', {
									icon: 5
								});
							}
						},
						//删除购物车商品
						delShop(ls, ind) {
							const that = this;
							//询问框
							layer.confirm('是否删除当前商品？', {
								btn: ['是', '否'] //按钮
							}, function(index) {
								layer.close(index);
								//删除数组数据
								that.shopList.splice(ind, 1);
								//重新获取焦点
								that.$refs.code.focus();
								//删除购物车数据
								that.delCartShop([ls.cartId])
								layer.msg('删除成功!', {
									icon: 1
								});
							}, function(index) {
								layer.close(index);
							});
						},
						// 清空购物车
						delCartAll() {
							const that = this;
							$eb.axios.post('{:Url("clear_cart")}', {
								uid: that.userId
							}).then(function(res) {
								that.$nextTick(function() {
									that.$refs.code.focus();
								})
								layer.closeAll('loading');
								console.log(res, '购物车清空成功')
							}).catch(function(err) {
								that.delCartAll();
								console.log(err);
							})
						},
						//删除购物车数据
						delCartShop(ids) {
							const that = this;
							$eb.axios.post('{:Url("del")}', {
								ids: ids,
								uid: that.userId
							}).then(function(res) {
								console.log(res, '购物车删除成功')
							}).catch(function(err) {
								console.log(err);
							})
						},
						//增加减少数量
						changeNumShop(item, type) {
							const that = this;
							layer.prompt({
								title: '请输入需要' + (type > 0 ? '添加' : '减少') + '的数量',
								formType: 0
							}, function(pass, index) {
								layer.close(index);
								const nt = /^[0-9]*$/g; //匹配数字
								if (!nt.test(pass)) {
									console.log(nt.test(pass), '判断是否正确');
									layer.msg('请输入数字')
									return false
								}
								console.log(pass);
								if ((item.num * 1) + (pass * type) > 0) {
									//修改商品数量
									that.changeCartShop(item.cartId, (item.num * 1) + pass * type).then(
										function(data) {
											console.log(data.data.status);
											if (data.data.status == 200) {
												item.num = ((item.num * 1) + pass * type).toFixed(3);
												layer.msg('成功' + (type > 0 ? '添加' : '减少') + pass +
													'件商品')
											} else {
												layer.msg(data.data.msg);
											}
										}).catch(function(data) {
										console.log(data.data.status);
										layer.msg(data.data.msg);
									})
								} else {
									layer.msg('商品数量不可小于0')
								}
							});
						},
						//处理扫码加入商品时间 
						async getShopNum() {
							const that = this;
							if (that.lodingAddCart) {
								that.shopId = '';
								iView.Message.warning('扫码速度过快，加入失败')
								return
							}
							that.lodingAddCart = true;
							layer.load(1,{
								shade: 0.1
							})
							await that.isShopNum();
							that.lodingAddCart = false;
							layer.closeAll('loading');
							// 处理设置允许获得焦点
							that.$nextTick(function() {
								that.$refs.code.focus();
								console.log('成功');
							})
						},
						//查询商品是否有库存
						isShopNum() {
							const that = this;
							let num = 0;
							let orderId = 0;

							if (that.shopId.length == 13 && that.shopId.substr(0, 2) == '20') {
								orderId = that.shopId.substr(2, 5);
								num = (Math.floor(that.shopId.substr(7, 6) / 10) / 1000).toFixed(3);
							} else {
								orderId = that.shopId;
								num = 1
							}
							that.shopId = '';

							return new Promise((resolve, reject) => {
								$eb.axios.post('{:Url("getBarCode")}' + (orderId ? '?bar_code=' +
										orderId : ''))
									.then(function(res) {
										// console.log(res);
										const data = res.data.data;
										// console.log(data, '返回数据')
										if (that.is_consumer != data.is_consumer) {
											if (that.is_consumer == 1) {
												layer.msg('请选择消费券商品', {
													icon: 5
												})
											}
											if (that.is_consumer == 0) {
												layer.msg('请选择普通商品', {
													icon: 5
												})
											}
											resolve()
										} else {
											//添加到购物车
											that.addCart(data, num).then(() => {
												console.log('购物车加入成功');
												resolve()
											}).catch((err) => {
												console.log('购物车加入失败');
												reject()
											})
										}
									}).catch(function(err) {
										reject(err)
										console.log(err);
									})
							})
						},
						//添加购物车
						addCart(product, num = 1) {
							const that = this
							console.log('开始添加购物车');

							let pushData = {
								productId: product.product_id, //普通产品编号
								uid: this.userId,
								uniqueId: product.unique, //属性唯一值
								cartNum: num, //购物车数量
								new: 0, // 1 加入购物车直接购买  0 加入购物车
							}
							return new Promise((resolve, reject) => {
								$eb.axios.post('{:Url("add_cart")}', pushData).then(function(res) {
									console.log(res)
									const data = res.data;
									if (data.status == 200) {
										//保存购物车id
										const cartId = data.data.cartId
										//判断是否有这个商品
										const ind = that.shopList.findIndex(function(a) {
											if (a.cartId == cartId) {
												return true
											} else {
												return false
											}
										})
										//判断这个商品是否已经存在数组
										if (ind > -1) {
											that.shopList[ind].num = (+that.shopList[ind].num + (
												+num)).toFixed(3);
											resolve(true)
										} else {
											//初始化商品
											that.initShopData(product, cartId, (+num).toFixed(3))
												.then((data) => {
													resolve(true)
												}).catch((err) => {
													reject(err);
												})
										}
									} else {
										layer.msg(data.msg, {
											icon: 5
										});
										reject(data)
									}
								}).catch(function(err) {
									reject(err)
									console.log(err);
								})
							})

						},
						//初始化购物车商品
						initShopData(product, cartId, num) {
							const that = this;
							return new Promise((resolve, rejact) => {
								that.shopList = ([{
									name: product.store_name, //商品
									num: num, //购物车中的数量
									id: product.product_id, //当前商品id
									cartId: cartId, //保存购物车id
									typeName: product.suk, //商品规格名称
									unique: product.unique, //商品规格id
									image: product.image, //商品主图
									price: product.price, //商品价格
									is_consumer: product.is_consumer //商品类型
								}]).concat(that.shopList);
								// console.log(this, '初始化后this对象')
								//初始化该商品为1
								that.changeCartShop(cartId, num).then((data) => {
									resolve(data);
								}).catch((err) => {
									rejact(err);
								})
							})
						},
						//修改购物车物品数量
						changeCartShop(cartId, num) {
							const that = this;
							return new Promise(function(ok, erro) {
								$eb.axios.post('{:Url("num")}', {
									id: cartId,
									number: num,
									uid: that.userId
								}).then(function(res) {
									console.log(ok)
									ok(res)
								}).catch(function(err) {
									layer.msg('购物车加入失败请刷新页面', {
										icon: 5
									})
									erro(err)
									console.log(err);
								})
							})
						},
						submit: async function() {
							let confirmData;
							let that = this;
							// console.log(that.form.store_id, '当前门店id')
							//当前门店
							if (!that.form.store_id) {
								return layer.msg('请选择门店', {
									icon: 5
								});
							}
							if (!that.shopList.length > 0) {
								return layer.msg('请选择商品', {
									icon: 5
								});
							}
							//用于保存当前选中的商品cardid
							let pusharr = []
							for (let i = 0; i < that.shopList.length; i++) {
								pusharr.push(that.shopList[i].cartId);
							}
							layer.load(1,{
								shade: 0.1
							})
							//提交订单
							try {
								//提交数据
								let pushData = {
									cartId: pusharr.join(','),
									uid: that.userId
								}
								let res = await $eb.axios.post('{:Url("confirm")}', pushData);
								confirmData = res.data
								const orderKey = res.data.data.orderKey;
								let money = await that.computedOrder(orderKey);
								layer.closeAll('loading');
								layer.confirm('订单总金额：￥' + that.allPayMoney.toFixed(2) + '<br/> vip优惠：￥' + ((
										that.allPayMoney - money.pay_price) > 0 ? (
										that.allPayMoney - money.pay_price).toFixed(
										2) : 0) + '<br/> 实际支付：￥' + money.pay_price
									.toFixed(2), {
										btn: ['立即支付', '取消', '修复订单','查看数据'], //按钮
										yes: async function(index) {
											layer.close(index);
											try {
												//微信
												// if (that.form.pay_type == 'weixin') {
												//     let qr = await that.weixinPay();
												//     that.create(orderKey, qr)
												// }
												// 余额
												if (that.form.pay_type == 'yue') {
													that.create(orderKey)
												}
												//现金
												if (that.form.pay_type == 'offline') {
													that.create(orderKey)
												}
												// 积分
												if (that.form.pay_type == 'integral') {
													that.create(orderKey)
												}
												//支付宝
												// if (that.form.pay_type == 'alipay') {
												//     that.create(orderKey)
												// }

												if (that.form.pay_type == 'jialie') {
													let qr = await that.jialiePay();
													that.create(orderKey, qr)
												}

											} catch (e) {
												console.log(e);
											}

										},
										btn2: function(index) {
											layer.close(index);
										},
										btn3: function(index) {
											console.log('对比');
											that.orderContrast();
										},
										btn4: function(index) {
											console.log('对比2');
											layer.close(index);
											layer.alert(`错误返回数据${JSON.stringify(confirmData)}`, {icon: 0});
										},
									});
								console.log(money, '金额计算');
							} catch (e) {
								layer.closeAll('loading');
								layer.msg(e.message, {
									icon: 5
								});
								layer.alert(`错误返回数据${JSON.stringify(confirmData)}`, {icon: 0});
								console.log(e)
							}
						},
						weixinPay() {
							return new Promise(function(ok, err) {
								layer.prompt({
									title: '请输入微信付款码编号',
									formType: 0
								}, function(pass, index) {
									layer.close(index);
									ok(pass)
								});
							})
						},
						//嘉联支付验证
						jialiePay() {
							return new Promise(function(ok, err) {
								layer.prompt({
									title: '请输入付款码编号',
									formType: 0
								}, function(pass, index) {
									layer.close(index);
									ok(pass)
								});
							})
						},
						//计算订单价格
						computedOrder(key) {
							const that = this;
							return new Promise(function(ok, erro) {
								$eb.axios.post('{:Url("computedOrder")}', {
									key,
									uid: that.userId
								}).then(function(res) {
									//保存订单key
									ok(res.data.data.result)
								}).catch(function(err) {
									erro(err)
								})
							})
						},
						//创建订单
						create(key, qr) {
							let that = this;
							let data = {
								key: key,
								uid: that.userId,
								shipping_type: 2,
								store_id: that.form.store_id,
								real_name: that.userData.nickname,
								phone: that.userData.phone,
								payType: that.form.pay_type //支付方式
							};
							//判断是否需要传入code码
							if (qr) {
								data.auth_code = qr;
							}
							//提交订单
							$eb.axios.post('{:Url("create")}', data).then(function(res) {
								layer.confirm(res.data.msg + '<br/>' + '是否刷新？', {
									btn: ['刷新', '取消'] //按钮
								}, function(index) {
									//清除用户卡号信息
									that.UserCard = '';
									window.location.reload();
									//parent.$(".J_iframe:visible")[0].contentWindow.location.reload();
									layer.close(index);
								}, function(index) {
									layer.close(index);
								});
								console.log(res)
							}).catch(function(err) {

							})
						}
					},
				}).$mount(document.getElementById('store-attr'))
			})
		</script>
