<template>
	<view class="container">
		<view class="message-box">
			<view class="title-box">
				<text class="message">{{$t('index.order-info')}}</text>
				<text class="receving" @click="recevingDetail(item.id)">对账</text>
			</view>
			<!-- 订单信息 -->
			<uni-list class="custom-uni-list">
				<uni-list-item :title="$t('index.buyer-name')" :rightText="orderInfo.buyerName"></uni-list-item>
				<uni-list-item :title="$t('index.buyer-code')" :rightText="orderInfo.buyerCode"></uni-list-item>
				<uni-list-item :title="$t('index.seller-name')" :rightText="orderInfo.sellerName"></uni-list-item>
				<uni-list-item :title="$t('index.seller-code')" :rightText="orderInfo.sellerCode"></uni-list-item>
				<uni-list-item :title="$t('index.order-type')"
					:rightText="orderInfo.creditFacilitiesTypeName"></uni-list-item>
				<uni-list-item :title="$t('index.delivery-type')"
					:rightText="orderInfo.receiveTypeName"></uni-list-item>
			</uni-list>
			<view class="title-box" style="border-top: 20rpx solid #f2f2f2;">
				<text class="message">{{$t('index.product-info')}}</text>
			</view>
			<!-- 商品信息 -->
			<view class="content-box">
				<view v-for="(item, index) in goodList">
					<view class="product-box" :key="item.id">
						<view style="width: 160rpx;height: 160rpx;background: #f6f7f8;flex: none;">
							<image v-if="item.imageUrl" style="width: 100%;height: 100%;" :src="item.imageUrl[0]" mode="aspectFit"></image>
						</view>
						<view class="content">
							<view class="name">{{item.productName}}</view>
							<view class="describe">{{$t('index.product-code')}}：{{item.productCode}}
								{{$t('index.spec')}}：{{item.varieties}}
							</view>
							<view class="describe">
								<text>数量：{{item.count}}</text>
								<text style="margin-left: 10px">单位：{{item.unit}}</text>
							</view>
							<view class="describe">
								<text>发货数量：{{ receivingInforSendmation[item.id] || 0 }}</text>
								<text style="margin-left: 10px">收货数量：{{ receivingInforReceivemation[item.id] || 0 }}</text>
							</view>
						</view>
					</view>
					<uni-list class="custom-uni-list">
						<uni-list-item v-for="(batch, key) in item.baseBatchNoList" :key="batch.no" :title="`批次号:${batch.no}`">
							<template v-slot:footer>
								<!-- <input class="custom-uni-value" v-model="batch.number" placeholder="请输入发货数量" /> -->
								<view style="flex: auto;text-align: right;">
									<step-price width="55" height="32" :min="0" :value="batch.number"
										@reduce="number=> onNumberChange(number, key, index)"
										@plus="number=> onNumberChange(number, key, index)"
										@input="number=> onNumberChange(number, key, index)"></step-price>
								</view>
							</template>
						</uni-list-item>
					</uni-list>
				</view>
			</view>
		</view>
		<view class="upload-box">
			<view class="upload-title">{{$t('index.annex-upload')}}</view>
			<view class="upload">
				<uni-file-picker limit="3" mode="grid" file-mediatype="image" @select="select">
				</uni-file-picker>
			</view>
		</view>

		<view class="upload-box" style="margin-bottom:50px">
			<uni-list class="custom-uni-list">
				<uni-list-item title="车号">
					<template v-slot:footer>
						<input class="custom-uni-value" v-model="driverForm.carNumber" placeholder="请输入车号" />
					</template>
				</uni-list-item>
				<uni-list-item title="司机名称">
					<template v-slot:footer>
						<input class="custom-uni-value" v-model="driverForm.billLadingPerson" placeholder="请输入司机名称" />
					</template>
				</uni-list-item>
				<uni-list-item title="电话">
					<template v-slot:footer>
						<input class="custom-uni-value" v-model="driverForm.phone" placeholder="请输入电话" />
					</template>
				</uni-list-item>
				<uni-list-item title="身份证">
					<template v-slot:footer>
						<input class="custom-uni-value" v-model="driverForm.cardId" placeholder="请输入身份证" />
					</template>
				</uni-list-item>
				<uni-list-item title="提货日期">
					<template v-slot:footer>
						<uni-datetime-picker type="date" style="flex: auto;text-align:right" v-model="driverForm.ladingDate">
							<view v-if="driverForm.ladingDate" class="deposit-value">{{driverForm.ladingDate}}</view>
							<view v-else style="color:#666;font-size:14px">请选择日期</view>
						</uni-datetime-picker>
					</template>
				</uni-list-item>
			</uni-list>
		</view>

		<view class="btn-box">
			<button class="btn" @click="submitReceiving">{{$t('index.sure')}}</button>
		</view>
	</view>
</template>

<script>
	import {
		getOrderDetail,
		getProductBranchList,
		uploadFile,
		sendGoodsBToBuyer,
		getGoodsCountByOrderId
	} from '@/config/api.js'
	import stepPrice from '../../components/step-price/step-price.vue';
	export default {
		name: 'receivingDetail',
		components: {
			stepPrice
		},
		data() {
			return {
				orderInfo: {},
				goodList: [],
				fileIds: [],
				receivingInforSendmation: {},
				receivingInforReceivemation: {},

				driverForm: {
					carNumber: '',
					billLadingPerson: '',
					phone: '',
					cardId: '',
					ladingDate: '',
					carrierType: 1
				}
			}
		},
		methods: {
			onGetDetail(id) {
				getOrderDetail({id}).then(({
					content
				}) => {
					this.orderInfo = content
					let list = content.orderDetails;
					this.getRecordDetail(list)
				})
			},
			async getRecordDetail(list) {
				let {
					content
				} = await getProductBranchList(this.orderInfo.id)
				
				const data = list.map(item=> {
					const sendBranchNumber = content.find(row=>row.productId === item.baseProductId)
					return {
						...item,
						baseBatchNoList: sendBranchNumber ? sendBranchNumber.batchNoList.map(chunk=> {
							return {
								no: chunk,
								number: undefined
							}
						}) : []
					}
				})
				this.goodList = [...data];
				this.getGoodsCountByOrderId()
			},
			getGoodsCountByOrderId() {
				getGoodsCountByOrderId({id: this.orderInfo.id}).then(({
					content
				}) => {
					this.receivingInforSendmation = content.receive || {}
					this.receivingInforReceivemation = content.send || {}
				})
			},
			uploadImage(path) {
				return new Promise((resolve, reject) => {
					uploadFile({
						filePath: path,
						name: 'file',
						formData: { //其他需要携带的参数
							'modelType': 'default'
						}
					}).then(({
						content
					}) => {
						resolve(content)
					}).catch(err => {
						reject(err)
					})
				})
			},
			async onNumberChange(count, key, index) {
				this.goodList[index].baseBatchNoList[key]['number'] = count
			},
			// 获取上传状态
			select(e) {
				let serveList = []
				e.tempFilePaths.forEach(url => {
					serveList.push(this.uploadImage(url))
				})
				Promise.all(serveList).then(data => {
					setTimeout(() => {
						uni.showToast({
							title: this.$t('index.operate-success'),
							icon: 'none'
						});
					}, 30)
					this.fileIds = this.fileIds.concat(data.map(item => item.id))
				}).catch(err => {
					setTimeout(() => {
						uni.showToast({
							title: this.$t('index.msg-upload-err'),
							icon: 'none'
						});
					}, 30)
				})
			},
			submitReceiving() {
				console.log(this.goodList)
				const flagList = this.goodList.filter(item=> {
					const branchList = item.baseBatchNoList.filter(row=>row.number)
					return branchList.length !== 0
				})
				if(flagList.length === 0) {
					uni.showToast({ title: '请至少选择一个批次号发货！', icon: 'none' });
					return
				}
				if(!this.driverForm.carNumber) {
					uni.showToast({ title: '请输入车号', icon: 'none' });
					return
				}
				if(!this.driverForm.billLadingPerson) {
					uni.showToast({ title: '请输入司机名称', icon: 'none' });
					return
				}
				if(!this.driverForm.phone) {
					uni.showToast({ title: '请输入电话', icon: 'none' });
					return
				}
				if(!this.driverForm.cardId) {
					uni.showToast({ title: '请输入身份证', icon: 'none' });
					return
				}
				if(!this.driverForm.ladingDate) {
					uni.showToast({ title: '请选择日期', icon: 'none' });
					return
				}

				const productInfo = flagList.map(item=> {
					const branchList = item.baseBatchNoList.filter(row=>row.number)
					return {
						id: item.id,
						productCode: item.productCode,
						productName: item.productName,
						varieties: item.varieties,
						count: item.count,
						receiveGoodsCount: item.receiveGoodsCount || 0,
						sendGoodsCount: branchList.map(row=>row.number).join(','),
						sendBranchNumber: branchList.map(row=>row.no).join(',')
					}
				})

				sendGoodsBToBuyer({
					orderId: this.orderInfo.id,
					orderNumber: this.orderInfo.orderNum,
					sendFileId: this.fileIds.join(','),
					billLading: this.driverForm,
					productInfo: JSON.stringify(productInfo)
				}).then(res => {
					setTimeout(() => {
						uni.showToast({
							title: '发货成功！',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							});
						}, 1500)
					}, 30)
				})
			}
		},
		onLoad(options) {
			this.onGetDetail(options.id)
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #fff;
		min-height: 100vh;
	}

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

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

	.content-box {
		padding: 0 15px;
		/deep/ .uni-list-item__container {
			padding: 0;
		}

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

			// &:first-of-type {
			// 	border-top: 1rpx solid #D5E2F3;
			// }
			border-top: 1rpx solid #D5E2F3;

			&:not(:last-of-type) {
				border-bottom: 1rpx solid #D5E2F3;
			}

			.content {
				// flex: auto;
				// display: flex;
				// justify-content: space-between;
				margin-left: 18rpx;

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

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

				.box {
					margin-top: 10rpx;

					.branchNumber {
						font-size: 28rpx;
						color: #99A0AF;
					}

					.flex-box {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.receving {
							display: flex;
							flex: 1;
							align-items: center;
						}
					}
				}
			}
		}
	}

	.upload-box {
		border-top: 20rpx solid #F5F5F6;
		padding: 12px 15px 0;
		margin-top: 20rpx;

		.upload-title {
			font-size: 14px;
			color: #B60001;
			;
		}

		.upload {
			margin-top: 12px;
		}
	}

	.btn-box {
		padding: 40rpx 30rpx;

		.btn {
			height: 94rpx;
			line-height: 94rpx;
			background-color: #086DCA;
			font-size: 15px;
			font-weight: 500;
			color: #FFFFFF;

			&::after {
				border-radius: 0;
				border: 0;
			}

			&.carrier {
				background-color: #1AAD19;
			}
		}
	}

	.carrier-chose {
		padding: 10px 15px 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.delete-text {
			color: #B60001;
		}
	}

	.carrier-table-box {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 10px;
		box-sizing: border-box;

		&.header {
			height: 40px;
			background-color: #f5f5f5;
		}

		&.list {
			min-height: 36px;
			border-bottom: 1rpx solid #f5f5f5;
		}
	}
	.custom-uni-list {
		/deep/ .uni-list-item {
			align-items: center;
		}
		/deep/ .uni-list-item__container {
			align-items: center;
		}
	}
</style>