<template>
	<view class="container">
		<!-- <view class="address-box cell-box" @click="choseDetail('/pages/address/index?type=chose')">
			<view>
				<view class="message">
					<text class="text">{{receive.receivePerson}}</text>
					<text class="text phone">{{receive.receivePersonPhone}}</text>
					<text class="tag" v-if="receive.isDefault">默认</text>
				</view>
				<view class="address">{{receive.warehouseAddress}}</view>
			</view>
			<uni-icons type="right" color="#99A0AF" size="16"></uni-icons>
			<image class="line" src="../../static/line.png"></image>
		</view> -->

		<view class="cell-box custom-uni-list">
			<uni-list>
				<uni-list-item :title="$t('index.order-type')" showArrow v-if="isCreditFacilities">
					<template v-slot:footer>
						<view class="cell-body">
							<picker mode="selector" @change="onPickerChange" :value="typeKey" :range="typeList"
								range-key="name">
								<view class="value-font">{{typeList[typeKey].name}}</view>
							</picker>
						</view>
					</template>
				</uni-list-item>
				<uni-list-item :title="$t('index.delivery-time')" showArrow>
					<template v-slot:footer>
						<view class="cell-body">
							<picker mode="date" :value="orderForm.deliveryDate" :start="orderForm.deliveryDate"
								@change="onDateChange">
								<view class="value-font">{{orderForm.deliveryDate}}</view>
							</picker>
						</view>
					</template>
				</uni-list-item>
			</uni-list>
		</view>

		<view class="cell-box product-box">
			<view class="title-box">
				<text class="message">{{product.deliveryWayName}}{{$t('index.product-info')}}</text>
				<text class="price-box">
					<text class="price">{{totalMoney}}</text>
					<text class="unit">{{$t('index.unit.price')}}</text>
				</text>
			</view>
			<view class="content-box">
				<view v-for="(item,index) in product.platformProductPriceVos" :key="index">
					<view class="box">
						<image class="thumb" :src="item.imageUrl" mode="aspectFill"></image>
						<view class="content">
							<view class="name">{{product.name}}({{item.availableCount}})</view>
							<view class="line">
								<text
									class="describe">({{product.productVo.brandNumber}}/{{product.productVo.manufacturer}}/{{product.productVo.varieties}})</text>
								<text class="price-box"><text class="price">{{item.priceStr}}</text>
									{{$t('index.yuan')}}/{{product.productVo.unit}}</text>
							</view>
							<view class="step-box">
								<step-price :item="item" :min="0" :max="item.availableCount" :value="item.buyNum"
									@reduce="onNumberChange" @plus="onNumberChange"
									@input="onNumberChange"></step-price>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>

		<!-- <view class="product-box cell-box" v-if="product.deliveryWayName === '配送'">
			<view class="title-box">
				<text class="message">配送商品信息</text>
				<text class="price-box">
					<text class="price">{{totalPrice}}</text>
					<text class="unit">元</text>
				</text>
			</view>
			<view class="content-box">
				<view class="box">
					<image class="thumb" :src="product.imageUrl" mode="aspectFill"></image>
					<view class="content">
						<view class="name">{{product.name}}({{product.availableCount}})</view>
						<view class="line">
							<text class="describe">({{product.brandNumber}}/{{product.manufacturer}}/{{product.varieties}})</text>
							<text class="price-box"><text class="price">{{product.price}}</text> 元/吨</text>
						</view>
						<view class="step-box">
							<step-price :max="product.availableCount" :value="purchaseCount" @reduce="onNumberChange" @plus="onNumberChange" @input="onNumberChange"></step-price>
						</view>
					</view>
				</view>
			</view>
		</view> -->

		<view class="cell-box custom-uni-list">
			<uni-list>
				<uni-list-item :title="$t('index.product-total')" :rightText="'￥' + goodsPrice" />
				<uni-list-item :title="$t('index.tax-rate')" :rightText="'￥' + taxation" />
			</uni-list>
		</view>

		<view class="cell-box custom-uni-list">
			<uni-list>
				<uni-list-item @tap="chooseDetail('/pages/coupon/coupon?type=choose')"
					:title="$t('index.choose-coupons')" :right-text="coupon==null?'':coupon.name"
					show-arrow="true"></uni-list-item>
				<uni-list-item v-if="coupon!=null" :right-text="`-${coupon.discountAmount}`"></uni-list-item>
			</uni-list>
		</view>

		<view class="cell-box custom-uni-list">
			<uni-list>
				<uni-list-item :title="$t('index.remark')">
					<template v-slot:footer>
						<!-- <input class="remarks" type="text" v-model="orderForm.remark" placeholder="请输入备注"> -->
						<textarea class="remarks" v-model="orderForm.remark" auto-height
							:placeholder="$t('index.enter')+$t('index.remark')" />
					</template>
				</uni-list-item>
			</uni-list>
		</view>

		<view class="cell-box submit-box">
			<view class="total-pric">
				<text class="text">{{$t('index.should-pay-sum')}}：</text>
				<text class="unit">￥</text>
				<text class="price">{{totalMoney}}</text>
			</view>
			<button type="primary" :disabled="isSubmit" class="submit"
				@click="submitForm">{{$t('index.submit-order')}}</button>
		</view>
	</view>
</template>

<script>
	import {
		getSearchById,
		getIsCreditUser,
		submitOrder,
		getBuyerList
	} from '@/config/api.js'
	import stepPrice from '../../components/step-price/step-price.vue';
	let productId = null;
	export default {
		name: 'detail',
		components: {
			stepPrice
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				isCreditFacilities: true, // 是否融资客户
				isSubmit: false,
				typeList: [{
					name: this.$t('index.screen.order.commonly'),
					value: 'commonly'
				}, {
					name: this.$t('index.screen.order.financing'),
					value: 'financing'
				}],
				typeKey: 0,
				orderForm: {
					type: '',
					deliveryDate: currentDate,
					remark: '', // 备注
				},
				goodsPrice: 0, // 商品价格
				taxation: 0, // 商品税费
				product: {
					productVo: {
						brandNumber: 0,
					},
					platformProductPriceVos: []
				}, // 商品详情
				priceVo: {}, // 价格详情
				skuNums: [],
				submits: [], // 提交订单信息,
				type: 'self',
				cartList: [],
				totalMoney: 0,
				list: [], // 已选中商品
				coupon: null
			}
		},
		watch: {
			'cartList': {
				deep: true,
				immediate: true,
				handler: function(newV) {
					let total = 0
					this.submits.splice(0, this.submits.length)
					for (let j = 0; j < newV.length; j++) {
						let item = newV[j]
						let count = Number(item.buyNum)

						let salePrice = 0
						if (count > 0) {
							let specsId;
							for (let i = 0; i < item.productTieredPricings.length; i++) {
								let priceItem = item.productTieredPricings[i]
								if (count > Number(priceItem.minBatchNum) && (count <= Number(priceItem
										.maxBatchNum) || priceItem.maxBatchNum == undefined)) {
									salePrice = Number(priceItem.salePrice)
									this.product.platformProductPriceVos[j].priceStr = salePrice.toFixed(2)
									specsId = priceItem.priceId
								}
								// 如果匹配不到则取最后一条
								if (salePrice == 0 && i == item.productTieredPricings.length - 1) {
									salePrice = Number(priceItem.salePrice)
									specsId = priceItem.priceId
								}
							}
							this.submits.push({
								productId,
								count: count,
								offerPrice: salePrice,
								specsId: specsId,
								warehouseId: item.warehouseId,
								deliveryWay: item.deliveryWay
							})
						}
						total += count * salePrice

					}
					this.taxation = (total * this.product.taxRate / 100).toFixed(2)
					this.goodsPrice = (total - this.taxation).toFixed(2)
					if (this.coupon != null) {
						total = total - this.coupon.discountAmount
					}
					this.totalMoney = total.toFixed(2)
				}
			},
			'coupon': {
				deep: true,
				handler: function(newV, oldV) {
					if (oldV != null) {
						this.totalMoney = (this.totalMoney + oldV.discountAmount).toFixed(2)
					}
					if (newV != null) {
						this.totalMoney = (this.totalMoney - newV.discountAmount).toFixed(2)
					}
				}
			}
		},
		methods: {
			getDate(type) {
				const dateTime = new Date().getTime() + 24 * 60 * 60 * 1000;
				const date = new Date(dateTime);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			getFormData(platformId, platformType) {
				getSearchById({
					id: productId,
					platformType
				}).then(({
					content
				}) => {
					console.log(this.list)
					// 初始化商品购买数量
					content.platformProductPriceVos.forEach(item => {
						this.list.forEach(product => {
							if (product.specsId == item.id) {
								item.buyNum = product.count
							}
							if (item.buyNum == undefined) {
								item.buyNum = 0
							}
						})
					})
					if (this.list.length == 0) {
						content.platformProductPriceVos.forEach(item => {
							if (item.isDefaultPrice == true) {
								item.buyNum = 1
							} else {
								item.buyNum = 0
							}
						})
					}
					let priceVos = []
					content.platformProductPriceVos.forEach(item => {
						if (item.buyNum != 0) {
							priceVos.push(item)
						}
					})
					content.platformProductPriceVos = priceVos
					this.cartList = [...priceVos]
					this.product = content
				})
			},
			setIsCreditUser() {
				getIsCreditUser().then(({
					content
				}) => {
					this.isCreditFacilities = content
				})
			},
			onPickerChange(e) {
				this.typeKey = e.detail.value
			},
			onDateChange(e) {
				this.orderForm.deliveryDate = e.detail.value
			},
			onNumberChange(number, item) {
				item.buyNum = Math.floor(number)
				for (let i = 0; i < this.cartList.length; i++) {
					let product = this.cartList[i]
					if (product.id == item.id) {
						this.cartList.splice(i, 1)
						break
					}
				}
				this.cartList.push(item)
			},

			submitForm() {
				this.isSubmit = true
				let creditFacilitiesType = this.isCreditFacilities ? this.typeList[this.typeKey].value : ''
				let deliveryDate = this.orderForm.deliveryDate
				let remark = this.orderForm.remark
				let orderCouponList = []
				if (this.coupon != null) {
					let groups = []
					this.submits.forEach(item => {
						let code;
						if (this.product.platformType == 'supplier') {
							code = this.product.productVo.supplierCode
						} else {
							code = this.product.productVo.sellerCode
						}
						let key = code + '_' + item.warehouseId + '_' + item
							.deliveryWay
						if (groups.indexOf(key) == -1) {
							groups.push(key)
						}
					})
					groups.forEach(item => {
						orderCouponList.push({
							couponPossessId: this.coupon.id,
							groupKey: item
						})
					})

				}
				console.log(orderCouponList)


				submitOrder({
					creditFacilitiesType,
					deliveryDate,
					isCreditFacilities: this.isCreditFacilities,
					recordDetail: this.submits,
					remark,
					orderCouponList,
					type: this.type
				}).then(res => {
					uni.redirectTo({
						url: `/pages/paymentStatus/index?price=${this.totalMoney}`
					})
					this.isSubmit = false
				}).catch(err => {
					this.isSubmit = false
				})
			},
			chooseDetail(url) {
				uni.navigateTo({
					url: url
				})
			}
		},
		onLoad(option) {
			if (option.skuNums) {
				this.skuNums = option.skuNums.split(",")
			}
			if (option.list) {
				this.list = JSON.parse(option.list)
			}
			this.type = option.platformType == 'operator' ? 'self' : (option.platformType == 'seller' ? 'seller' :
				'supplier')
			this.orderForm.type = this.typeList[this.typeKey].value
			this.deliveryWayName = option.deliveryWayName
			productId = option.id
			this.getFormData(option.platformId, option.platformType)
			this.setIsCreditUser()
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		overflow: hidden;

		.remarks {
			flex: auto;
			font-size: 28rpx;
			text-align: right;
		}

		.cell-box {
			margin-top: 20rpx;
			box-shadow: 0px 1px 8px 0px rgba(22, 119, 255, 0.08);

			// .invoice-title {
			// 	font-size: 28rpx;
			// 	color: #B60001;
			// 	line-height: 1;
			// }

			// .invoice-note {
			// 	font-size: 12px;
			// 	color: #99A0AF;
			// 	line-height: 1;
			// 	margin-top: 20rpx;
			// }
		}

		.cell-body {
			flex: auto;
			text-align: right;

			.value-font {
				color: #333333;
				font-size: 28rpx;
			}
		}

		// .custom-uni-list-header {
		// 	font-size: 14px;
		// 	color: #99A0AF;
		// }
	}

	// .address-box {
	// 	padding: 30rpx 20rpx 30rpx 30rpx;
	// 	display: flex;
	// 	justify-content: space-between;
	// 	align-items: center;
	// 	background-color: #FFFFFF;
	// 	position: relative;

	// 	.message {
	// 		display: flex;
	// 		align-items: center;
	// 		line-height: 1;

	// 		.text {
	// 			font-size: 28rpx;
	// 			color: #B60001;

	// 			&.phone {
	// 				margin-left: 30rpx;
	// 			}
	// 		}

	// 		.tag {
	// 			padding: 3px 16rpx;
	// 			color: #DE0000;
	// 			border: 1rpx solid #DE0000;
	// 			border-radius: 5px;
	// 			font-size: 12px;
	// 			line-height: 1;
	// 			margin-left: 20rpx;
	// 		}
	// 	}

	// 	.address {
	// 		font-size: 12px;
	// 		color: #99A0AF;
	// 		line-height: 1;
	// 		margin-top: 16rpx;
	// 	}

	// 	.line {
	// 		position: absolute;
	// 		left: 0;
	// 		bottom: 0;
	// 		right: 0;
	// 		width: 100%;
	// 		height: 2px;
	// 		z-index: 1;
	// 	}
	// }
	.product-box {
		background-color: #FFFFFF;

		.title-box {
			height: 110rpx;
			padding: 0 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.message {
				font-size: 12px;
				color: #99A0AF;
			}

			.price-box {
				line-height: 1;
				vertical-align: middle;

				.unit {
					color: #B60001;
					font-size: 12px;
				}

				.price {
					font-size: 40rpx;
					color: #B60001;
					margin-right: 2px;
				}
			}
		}
	}

	.content-box {
		background-color: #fff;
		padding: 0 15px;

		.box {
			display: flex;
			padding: 20rpx 0;
			border-top: 1rpx solid #D5E2F3;

			.thumb {
				flex: none;
				width: 120rpx;
				height: 120rpx;
				background-color: #CBE1FF;
				border-radius: 10rpx;
			}

			.content {
				flex: auto;
				margin-left: 18rpx;

				.name {
					font-size: 28rpx;
					color: #222;
					// line-height: 1;
				}

				.line {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 16rpx;

					.describe {
						font-size: 12px;
						color: #99A0AF;
						line-height: 1;
					}

					.price-box {
						color: #B60001;
						line-height: 1;
						font-size: 12px;

						.price {
							font-size: 28rpx;
						}
					}
				}

				.step-box {
					margin-top: 20rpx;
					text-align: right;
				}
			}
		}

	}

	.submit-box {
		padding: 0 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 120rpx;
		background-color: #fff;

		.total-pric {
			vertical-align: middle;

			.text {
				font-size: 28rpx;
				color: #B60001;
			}

			.unit {
				font-size: 12px;
				color: #B60001;
			}

			.price {
				font-size: 40rpx;
				color: #B60001;
			}
		}

		.submit {
			height: 80rpx;
			background-color: #B60001;
			border-radius: 40rpx;
			text-align: center;
			line-height: 80rpx;
			color: #fff;
			font-size: 28rpx;
			margin: 0;
		}
	}
</style>