<style lang="scss" scoped>
.admin-button-com {
	margin-right: 20upx;
}
.affirm-page {
	position: relative;
	height: 100%;
	display: flex;
	flex-direction: column;

	.affirm-view {
		flex: 1;
		padding: 20px;
		background-color: #f0f2f6;

		.commodity-view {
			display: flex;
			flex-direction: column;
			.commodity-list {
				padding: 20px;
				.commodity-item {
					display: flex;
					margin-bottom: 20px;
					.item-icon {
						flex-shrink: 0;
						width: 140px;
						height: 140px;
					}
					.item-info {
						display: flex;
						flex-direction: column;
						justify-content: center;
						flex: 1;
						margin-left: 20px;
						.info-line {
							margin-bottom: 20px;
							display: flex;
							justify-content: space-between;
							align-items: flex-end;
							.item-name {
								color: #666;
								font-size: 28px;
							}
							.item-price {
								color: #333;
								font-size: 22px;
								.price {
									font-size: 32px;
									font-weight: bold;
								}
							}
							.item-type {
								color: #999;
								font-size: 24px;
							}
							.item-count {
								color: #666;
								font-size: 24px;
							}
						}
					}
				}
			}
			.summary-bar {
				padding: 0 20px;
				height: 90px;
				display: flex;

				align-items: center;
				justify-content: space-between;
				border-top: 1px solid #eeeeee;
				.operate-view {
					display: flex;

					align-items: center;
					color: #3385ff;
					font-size: 26px;
					.iconfont {
						margin-right: 20px;
						font-size: 40px;
					}
				}
				.describe-view {
					display: flex;

					align-items: center;
					color: #333;
					font-size: 24px;
					.price {
						font-weight: bold;
						font-size: 36px;
					}
				}
			}
		}

		.module-com {
			background-color: #fff;
			margin-bottom: 20px;
			border-radius: 10px;
			overflow: hidden;
      padding-top: 20rpx;
			.ghs-msg{
				padding: 0 20rpx 20rpx;
					// height: 60rpx;
				font-size: 28rpx;
				&.active{
					color: #868686;
					font-size: 24rpx;
				}
				i{color: #62ed73;font-size: 32rpx}
			}

			.member-wrap {
				.member-det {
					font-size: 24px;
					margin-left: 20px;
				}
			}
			.remark-wrap {
				align-items: flex-start;
				.remark {
					height: 240px;
				}
			}
		}
	}
	.under-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20px;
		width: 100%;
		height: 100px;
		background-color: #fff;

		box-shadow: 0px -1px 6px 0px rgba(4, 0, 0, 0.06);
		.price-view {
			display: flex;
			align-items: center;
			font-size: 24px;
			.price-title {
				color: #333;
			}
			.price-number {
				margin: 0 20px;
				color: #ff2842;
				.large {
					font-size: 40px;
				}
			}
		}
		.admin-button-com {
			width: 200px;
		}
	}
  .coupon_box{
    flex: 1;
    text-align: right;
    padding-right: 45upx;
    color: #ff2945;
  }
}
</style>

<template>
	<view class="affirm-page">
		<view class="affirm-view overscroll">
			<!-- 门店信息 -->
			<form>
				<view class="module-com">
					<view class="flex-space ghs-msg">
						{{ghsMsg.name}} {{ ghsMsg.mobile }}
						<i class="iconfont icondianhua1" @tap="toPhone(ghsMsg.mobile)"></i>
					</view>
					<view class="flex ghs-msg active">
						{{ ghsMsg.fullAddress }}
					</view>
				</view>
				<view class="module-com">
					<view class="commodity-view">
						<view class="commodity-list">
							<view
								class="commodity-item"
								v-for="(item, index) in selectList"
								:key="index"
							>
								<image class="item-icon" :src="item.cover" alt="商品图" />

								<view class="item-info">
									<view class="info-line">
										<text class="item-name">{{ item.itemName }}</text>
										<text class="item-price">
											<text class="unit">¥</text>

											<text class="price">
												{{ getSelectItemPrice(item) }}
											</text>
										</text>
									</view>
									<view class="info-line">
										<text class="item-type">{{ item.rank }}级</text>
										<text class="item-count">
											<text v-if="item.bigCount > 0 || item.smallCount > 0">{{
												`${item.bigCount}`
											}}</text>
											<text v-if="item.smallCount > 0">/</text>
											<text v-if="item.smallCount > 0">{{ `${item.smallCount}` }}</text>
										</text>
									</view>
								</view>
							</view>
						</view>
						<view class="summary-bar">
							<view class="operate-view" @click="gobackEvent">
								<text class="iconfont icongouwuche"></text>
								重选花材
							</view>
							<view class="describe-view">
								共{{ allCount.bigLength }}/{{ allCount.smallLength }}种,
								<!-- 共16扎9支， -->
								合计 ¥<text class="price">{{ allPrice }}</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 登录信息 -->
				<view class="module-com input-line-wrap">
<!--					<tui-list-cell class="line-cell" :hover="false" :arrow="true">-->
<!--						<view class="tui-title ">客户</view>-->
<!--						<view class="tui-input" v-if="form.customId" @click="showCustomer = true">{{ form.customName }}</view>-->
<!--						<view class="tui-placeholder" style="width: 100%" v-else @click="showCustomer = true">请选择客户</view>-->
<!--					</tui-list-cell>-->
					<tui-list-cell class="line-cell" :hover="false" :arrow="false">
						<view class="tui-title ">送货</view>
						<button @click="form.sendType=1" class="admin-button-com mini-btn" :class="form.sendType==1?'blue':'default'">配送</button>
						<button @tap="form.sendType=2" class="admin-button-com mini-btn" :class="form.sendType==2?'blue':'default'">自取</button>
					</tui-list-cell>
						<!-- <appSendTime :placeholder="'默认30分钟后配送'" @alterTime="purchaseFreight(ghsMsg)" :sendDate.sync="form.sendDate" :sendTime.sync="sendTime" ></appSendTime> -->
            <appTimer :placeholder="'默认30分钟后配送'" @confirm="onConfirm" :sendTime="sendTime"></appTimer>
					<tui-list-cell class="line-cell" :hover="false" :arrow="false" v-show="form.sendType == 1">
						<view class="tui-title ">运费</view>
						<input type="number" placeholder="留空表示免运费" @input="countAllPrices" v-model="form.sendCost" placeholder-class="tui-placeholder" disabled>
					</tui-list-cell>
          <tui-list-cell class="line-cell" :hover="false" :arrow="true" @click="toCoupon">
						<view class="tui-title ">红包/抵用券</view>
						<view class="coupon_box">{{couponText}}</view>
					</tui-list-cell>
					<tui-list-cell class="line-cell" :hover="false" :arrow="false">
						<textarea style="height: 100rpx" v-model="remark" placeholder="备注..."/>
					</tui-list-cell>
          
<!--					<tui-list-cell class="line-cell" :hover="false" :arrow="false">-->
<!--						<view class="tui-title ">结算方式</view>-->
<!--						<button @tap="form.debt=1" class="admin-button-com mini-btn" :class="form.debt==1?'blue':'default'">欠款</button>-->
<!--						<button @click="form.debt=0" class="admin-button-com mini-btn" :class="form.debt==0?'blue':'default'">已收款</button>-->
<!--					</tui-list-cell>-->


<!--					<appFormSend :form.sync="form"> </appFormSend>-->
				</view>
			</form>
		</view>
		<view class="under-bar">
			<view class="price-view">
				<text class="price-title">总金额</text>
				<text class="price-number">
					¥
					<text class="large" v-if="form.sendType==1 && !couponSumText">{{ numberAdd(allPrice, Number(form.sendCost))  }}</text>
					<text class="large" v-else-if="form.sendType==1 && couponSumText">{{ allPrice + Number(form.sendCost) - Number(couponSumText)  }}</text>
					<text class="large" v-else-if="form.sendType==2 && !couponSumText">{{ allPrice}}</text>
					<text class="large" v-else-if="form.sendType==2 && couponSumText">{{ NumberSub(allPrice, Number(couponSumText))}}</text>
					<!-- <text class="large" v-else-if="!form.sendType && !couponSumText">{{ allPrice }}</text> -->
					<!-- <text class="large" v-else-if="!form.sendType && couponSumText">{{ NumberSub(allPrice, Number(couponSumText)) }}</text> -->
				</text>
			</view>
			<button class="admin-button-com blue middle" @click="affirmFormSubmit">提交</button>
		</view>
		<!-- 选择客户 -->
<!--		<AppCustomerSel :show.sync="showCustomer" @change="changeCustomerFn" />-->
	</view>
</template>

<script>
import TuiListCell from "@/components/plugin/list-cell";
import AppAvatarModule from "@/components/module/app-avatar";
import SimpleAddress from "@/components/plugin/simple-address";
import AppAreaSel from "@/components/app-area-sel";
import AppCustomerSel from "@/components/app-customer-sel";
import productMins from "@/mixins/product";
import appTimer from '@/components/app-timer'
import appFormRadioBtn from "@/components/app-formRadio-btn";
import appAddressGroup from "@/components/app-address-group";
import appFormSend from "@/components/app-form-send";
import appSendTime from "@/components/app-send-time";
const formUtil = require("@/utils/formValidation.js");
// import { createOrder } from "@/api/order/index";
import { getGhsDataApi } from "@/api/ghs/index";
import { freight,createOrder } from "@/api/purchase/index";
import { mapActions, mapGetters } from "vuex";
import { shopHouponHas } from '@/api/coupon'

export default {
	name: "BillingAffirm", // 开单确认
	components: {
		TuiListCell,
		AppAvatarModule,
		SimpleAddress,
		AppAreaSel,
    appSendTime,
		AppCustomerSel,
		appFormRadioBtn,
		appAddressGroup,
		appFormSend,
    appTimer
	},
	mixins: [productMins],
	data() {
		return {
			autoLoad: false,
			ghsMsg:'',
			sendTime:'',
			remark:'',
			form: {
				debt:1,//结算方式 1欠款订单 0正常订单
				shopId: "",
				shopName: "",
				receiveProvince: "",
				receiveCity: "",
				receiveFloor: "",
				receiveAddress: "",
				receiveLong: "",
				receiveLat: "",
				sendType: 1,
				sendSide: "2",
				sendDate: "",
				sendTime: "",
				sendCost: "",
				customId: "",
				product: "",
        couponId: '0'
			},
			// 详细地址
			// showRegion: false,
			showCustomer: false,
      couponSumText: '',
      couponText: ''
		};
	},
	onLoad(e) {
		if (!this.getMerchantInfo) {
			this.initMerchantInfo().then(data => {
				uni.setNavigationBarTitle({
					title: data.name
				});
			});
		} else {
			uni.setNavigationBarTitle({
				title: this.getMerchantInfo.name
			});
		}
    
		this.getGhsData(e.id);
	},
  onShow() {
    if(uni.getStorageSync('selectCouponInfo').couponSum) {
      this.couponSumText = uni.getStorageSync('selectCouponInfo').couponSum
      this.couponText = '-￥' + this.couponSumText
      this.form.couponId = uni.getStorageSync('selectCouponInfo').couponId
    } else {
      this.couponSumText = "0"
      this.form.couponId = '0'
       this.hasCoupon()
    }
  },
	computed: {
		...mapGetters(["getMerchantInfo", "getLoginInfo"])
	},
	methods: {
		...mapActions(["initMerchantInfo"]),
		init() {
			this._getDet();
		},
    onConfirm(val) {
      this.sendTime = val
    },
		toPhone(phone){
      let amount = this.form.sendType == 1 ? this.allPrice+Number(this.form.sendCost) : this.allPrice
			uni.makePhoneCall({
				phoneNumber: phone
			});
		},
    toCoupon() {
      let amount = this.form.sendType == 1 ? this.numberAdd(this.allPrice, Number(this.form.sendCost)) : this.allPrice
      console.log(amount)
      this.pageTo({url: '/admin/coupon/selectCouponList?price=' + amount})
    },
    // 是否有可用优惠券、红包
    hasCoupon() {
      let amount = this.form.sendType == 1 ? this.numberAdd(this.allPrice, Number(this.form.sendCost)) : this.allPrice
      shopHouponHas({amount}).then(res => {
        console.log(377, res)
        this.couponText = res.data.has ? '有红包可用' : ''
        console.log(this.couponText)
      }).catch(err => {})
    },
		getGhsData(id) {
			getGhsDataApi({id:id}).then(res => {
				this.ghsMsg = res.data;
				console.log('res.data',this.ghsMsg)
				this.purchaseFreight(this.ghsMsg);
			});
		},
		countAllPrices(e){
			this.allPrices = this.allPrices+Number(this.form.sendCost)
			console.log('e',e)
			console.log('this.form.sendCost',Number(this.form.sendCost))
			console.log('this.form.sendCost',this.form.sendCost)
			console.log('this.allPrices',this.allPrices)
		},

		// api
		_getDet() {
			let data = uni.getStorageSync("modifyShopB");
			if (this.$util.isEmpty(data)) return;
			Object.keys(this.form).forEach((i, index) => {
				// if (i != 'password') {
				this.form[i] = data[i];
				// }
			});
		},

		purchaseFreight(info) {
			const product = this.selectList.map(ele => {
				return { productId: ele.id, bigNum: ele.bigCount, smallNum: ele.smallCount,classId:ele.classId,itemId:ele.itemId };
			});
			let params = {
				ghsId: this.options.id,
				product: JSON.stringify(product),
				province: info.province,
				city:info.city,
				address:info.address,
				floor:info.floor,
				long: info.long,
				lat: info.lat,
				sendTime: this.sendTime,
			};
			freight(params).then(res => {
				this.form.sendCost = res.data.sedCost;
			});
		},
		confirmFn(options) {
			createOrder(options).then(res => {
				// this.$msg("下单成功");
				this.resetSelectInfoByType(this.pageType);
				const {
					data: { id, orderSn }
				} = res;
				let url = `/admin/billing/result?orderId=${id}&orderSn=${orderSn}`;
				uni.redirectTo({
					url: url,
					success: result => {},
					fail: () => {},
					complete: () => {}
				});
			});
		},
		affirmFormSubmit(){
			const product = this.selectList.map(ele => {
				return { productId: ele.id, bigNum: ele.bigCount, smallNum: ele.smallCount,classId:ele.classId,itemId:ele.itemId };
			});
			let parameter = {
				getType:this.form.sendType,
				sendTime:this.sendTime,
				sendCost:this.form.sendType==2?'':this.form.sendCost,
				remark:this.remark,
				product:JSON.stringify(product),
				ghsId:this.ghsMsg.id,
        couponId: this.form.couponId
			}
			let self = this;
			uni.showModal({
				title: '提示',
				content: '确认提交？',
				success: function (res) {
					if (res.confirm) {
						createOrder(parameter).then(res => {
							const {data: { orderSn,actPrice }} = res;
							self.pageTo({url: `/pagesPurchase/wechatPay?type=2&orderSn=${orderSn}&actPrice=${actPrice}`, type: 2})
              setTimeout(() => {
                uni.removeStorageSync('selectCouponInfo')
                self.resetSelectInfoByType(self.pageType);
              }, 600)
						});
					}
				}
			});
		},
    numberAdd(arg1, arg2) {
      var r1, r2, m, n;
      try {
          r1 = arg1.toString().split(".")[1].length
      } catch (e) {
          r1 = 0
      }
      try {
          r2 = arg2.toString().split(".")[1].length
      } catch (e) { 
          r2 = 0 
      } 
      m = Math.pow(10, Math.max(r1, r2))
      n = (r1 >= r2) ? r1 : r2;
      return ((arg1 * m + arg2 * m) / m).toFixed(n);
  },
  NumberSub(arg1, arg2) {
    var re1, re2, m, n;
    try {
        re1 = arg1.toString().split(".")[1].length;
    } catch (e) {
    re1 = 0;
    }
    try {
        re2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        re2 = 0;
    }
    m = Math.pow(10, Math.max(re1, re2)); 
    n = (re1 >= re2) ? re1 : re2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
		// 表单验证
		async formSubmit(e) {
			try {
				// 进行表单检查
				let formData = this.form;

				const product = this.selectList.map(ele => {
					return { productId: ele.id, bigNum: ele.bigCount, smallNum: ele.smallCount };
				});
				formData.product = JSON.stringify(product);
				if (!this.getMerchantInfo) {
					await this.initMerchantInfo();
				}
				formData.shopId = this.getMerchantInfo.id;

				console.log(9999, formData);
				// this.confirmFn(formData);
				// let rules = rules.concat(temp);
				let checkRes = formUtil.validation(formData, []);
				// 验证通过!
				if (!checkRes) {
					this.confirmFn(formData);
				} else {
					this.$msg(checkRes);
				}
			} catch (error) {
				console.log(999999, error);
			}
		},
		gobackEvent() {
			uni.navigateBack({
				delta: 1
			});
		}
	}
};
</script>

