<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" v-if="selfGoods.length">
			<view class="title-box">
				<text class="message">{{$t('index.self-pickup-product-info')}}</text>
				<text class="price-box">
					<text class="price">{{selfGoodsPrice}}</text>
					<text class="unit">{{$t('index.yuan')}}</text>
				</text>
			</view>
			<view class="content-box">
				<view class="box" v-for="item in selfGoods" :key="item.id">
					<image class="thumb" :src="item.pictureUrl" mode="aspectFill"></image>
					<view class="content">
						<view class="name">{{item.productName}}({{item.platformProductPriceVo.availableCount}})</view>
						<view class="line">
							<text
								class="describe">({{item.brandNumber}}/{{item.manufacturer}}/{{item.specs || ''}})</text>
							<text class="price-box"><text class="price">{{item.price}}</text>
								{{$t('index.yuan')}}/{{item.unit}}</text>
						</view>
						<view class="step-box">{{item.count}}{{item.unit}}
							<!-- <step-price :max="item.platformProductPriceVo.availableCount" :value="item.count" @reduce="number=>onSelfNumberChange(number, index)" @plus="number=>onSelfNumberChange(number, index)" @input="number=>onSelfNumberChange(number, index)"></step-price> -->
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="product-box cell-box" v-if="deliverGoods.length">
			<view class="title-box">
				<text class="message">{{$t('index.delivery-product-info')}}</text>
				<text class="price-box">
					<text class="price">{{deliverGoodsPrice}}</text>
					<text class="unit">{{$t('index.yuan')}}</text>
				</text>
			</view>
			<view class="content-box">
				<view class="box" v-for="item in deliverGoods" :key="item.id">
					<image class="thumb" :src="item.pictureUrl" mode="aspectFill"></image>
					<view class="content">
						<view class="name">{{item.productName}}({{item.platformProductPriceVo.availableCount}})</view>
						<view class="line">
							<text
								class="describe">({{item.brandNumber}}/{{item.manufacturer}}/{{item.specs || ''}})</text>
							<text class="price-box"><text class="price">{{item.price}}</text>
								{{$t('index.yuan')}}/{{item.unit}}</text>
						</view>
						<view class="step-box">{{item.count}}{{item.unit}}
							<!-- <step-price :max="item.platformProductPriceVo.availableCount" :value="item.count" @reduce="number=>onDeliverNumberChange(number, index)" @plus="number=>onDeliverNumberChange(number, index)" @input="number=>onDeliverNumberChange(number, index)"></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" @click="choseDetail('/pages/invoice/index?type=chose')">
			<uni-list>
				<uni-list-item>
					<template v-slot:header>
						<text class="custom-uni-list-header">发票信息</text>
					</template>
				</uni-list-item>
				<uni-list-item  showArrow>
					<template v-slot:header>
						<view class="invoice-title">{{invoice.companyName}}</view>
						<view class="invoice-note">{{invoice.taxNum}}</view>
					</template>
				</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">{{totalPrice}}</text>
			</view>
			<button type="primary" :disabled="isSubmit" class="submit"
				@click="submitForm">{{$t('index.submit-order')}}</button>
		</view>
	</view>
</template>

<script>
	import {
		findByIds,
		getInfoForCart,
		addCartPost,
		generateOrder,
		getIsCreditUser
	} from '@/config/api.js'
	import stepPrice from '../../components/step-price/step-price.vue';
	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',
					flag: false
				}, {
					name: this.$t('index.screen.order.financing'),
					value: 'financing',
					flag: true
				}],
				typeKey: 0,
				orderForm: {
					deliveryDate: currentDate,
					remark: '', // 备注
				},
				deliverGoods: [], // 配送商品列表
				deliverGoodsPrice: 0, // 配送商品价格
				deliverGoodsTaxrate: 0, // 配送商品税率

				selfGoods: [], // 自提商品列表
				selfGoodsPrice: 0, // 自提商品价格
				selfGoodsTaxrate: 0, // 自提商品税率
				coupon: null
			}
		},
		watch: {
			'deliverGoods': {
				deep: true,
				immediate: true,
				handler: function(newV) {
					let price = newV.map(item => {
						return item.count * item.price
					}).reduce((item, next) => {
						return item + next;
					}, 0)

					let taxrate = newV.map(item => {
						return (item.price * item.taxRate * item.count / 100)
					}).reduce((item, next) => {
						return item + next;
					}, 0)

					this.deliverGoodsTaxrate = taxrate.toFixed(2)
					this.deliverGoodsPrice = (price - taxrate).toFixed(2)
				}
			},
			'selfGoods': {
				deep: true,
				immediate: true,
				handler: function(newV) {
					let price = newV.map(item => {
						return item.count * item.price
					}).reduce((item, next) => {
						return item + next;
					}, 0)

					let taxrate = newV.map(item => {
						return (item.price * item.taxRate * item.count / 100)
					}).reduce((item, next) => {
						return item + next;
					}, 0)

					this.selfGoodsTaxrate = taxrate.toFixed(2)
					this.selfGoodsPrice = (price - taxrate).toFixed(2)
				}
			},
			'coupon': {
				deep: true,
				handler: function(newV, oldV) {
					if (oldV != null) {
						this.selfGoodsPrice = this.selfGoodsPrice + oldV.discountAmount
					}
					if (newV != null) {
						this.selfGoodsPrice = this.selfGoodsPrice - newV.discountAmount
					}
				}
			}
		},
		computed: {
			goodsPrice() {
				return (parseFloat(this.selfGoodsPrice) + parseFloat(this.deliverGoodsPrice)).toFixed(2)
			},
			taxation() {
				return (parseFloat(this.deliverGoodsTaxrate) + parseFloat(this.selfGoodsTaxrate)).toFixed(2)
			},
			totalPrice() {
				return (parseFloat(this.goodsPrice) + parseFloat(this.taxation)).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}`;
			},
			getInfoForCart() {
				getInfoForCart().then(({
					content
				}) => {
					this.invoice = content.invoice[0] || {}
					this.receive = content.receive[0] || {}
				})
			},
			choseDetail(url) {
				uni.navigateTo({
					url
				})
			},
			setIsCreditUser() {
				getIsCreditUser().then(({
					content
				}) => {
					this.isCreditFacilities = content
				})
			},
			findByIds(ids) {
				findByIds({}, {
					params: {
						ids
					}
				}).then(({
					content
				}) => {

					this.selfGoods = content.filter(item => item.platformProductPriceVo.deliveryWay === 'self')
					this.deliverGoods = content.filter(item => item.platformProductPriceVo.deliveryWay ===
						'deliver')
				})
			},
			onPickerChange(e) {
				this.typeKey = e.detail.value
			},
			onDateChange(e) {
				this.orderForm.deliveryDate = e.detail.value
			},
			onSelfNumberChange(count, index) {
				let {
					businessId,
					productName,
					productCode,
				} = this.selfGoods[index]
				let item = this.selfGoods[index]
				addCartPost({
					businessId,
					productName,
					productCode,
					sellerCode: (item.platformType == 'seller' ? item
							.sellerCode : item.supplierCode) ? item
						.platformCode : (item.platformType == 'seller') ? item
						.sellerCode : item.supplierCode,
					sellerName: (item.platformType == 'seller' ? item
							.sellerCode : item.supplierCode) ? item
						.platformName : (item.platformType == 'seller') ? item
						.sellerName : item.supplierName,
					source: (item.platformType == 'seller' ? item
						.sellerCode : item.supplierCode) ? "platformSelf" : (
						item.platformType == 'seller') ? 'onSale' : 'supplierSale',
					count
				}, {
					custom: {
						load: false
					}
				}).then(res => {
					this.selfGoods[index].count = count
				})
			},
			onDeliverNumberChange(count, index) {
				let {
					businessId,
					productName,
					productCode,
					// sellerName,
					// sellerCode,
					// source
				} = this.deliverGoods[index]
				let item = this.deliverGoods[index]
				addCartPost({
					businessId,
					productName,
					productCode,
					sellerCode: (item.platformType == 'seller' ? item
							.sellerCode : item.supplierCode) ? item
						.platformCode : (item.platformType == 'seller') ? item
						.sellerCode : item.supplierCode,
					sellerName: (item.platformType == 'seller' ? item
							.sellerCode : item.supplierCode) ? item
						.platformName : (item.platformType == 'seller') ? item
						.sellerName : item.supplierName,
					source: (item.platformType == 'seller' ? item
						.sellerCode : item.supplierCode) ? "platformSelf" : (
						item.platformType == 'seller') ? 'onSale' : 'supplierSale',
					count
				}, {
					custom: {
						load: false
					}
				}).then(res => {
					this.deliverGoods[index].count = count
				})
			},
			chooseDetail(url) {
				uni.navigateTo({
					url: url
				})
			},
			submitForm() {
				this.isSubmit = true
				let creditFacilitiesType = this.isCreditFacilities ? this.typeList[this.typeKey].value : ''
				let deliveryDate = this.orderForm.deliveryDate
				let remark = this.orderForm.remark
				let cartIds = this.selfGoods.concat(this.deliverGoods).map(item => item.id)
				let orderCouponList = []
				let keys = []
				this.selfGoods.concat(this.deliverGoods).forEach(item => {
					let key = item.sellerCode + '_' + item.platformProductPriceVo.warehouseId + '_' + item
						.platformProductPriceVo.deliveryWay
					if (keys.indexOf(key) == -1) {
						keys.push(key)
					}
				})
				keys.forEach(key => {
					orderCouponList.push({
						couponPossessId: this.coupon.id,
						groupKey: key
					})
				})
				generateOrder({
					cartIds,
					orderCouponList,
					creditFacilitiesType,
					deliveryDate,
					isCreditFacilities: this.isCreditFacilities,
					remark
				}).then(res => {
					uni.redirectTo({
						url: `/pages/paymentStatus/index?price=${this.totalPrice}`
					})
					this.isSubmit = false
				}).catch(err => {
					this.isSubmit = false
				})
			}
		},
		onLoad(option) {
			this.findByIds(option.ids)
			// this.getInfoForCart()
			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: #222;
				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: #222;
				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: 72rpx;
			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: #222;
					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 {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 20rpx;

					.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>