<template>
	<!-- 确认送达 -->
	<view>
		<u-navbar :title="navTitle" autoBack placeholder @leftClick="leftClick"></u-navbar>
		<view class="card_order_details">
			<view style="display: flex;align-items: center;margin-bottom: 10rpx;">
				<view class="details_title">{{getTitle(navTitle)}} <span class="line_title">*</span></view>
				<uni-datetime-picker type="datetime" :start="start" :end="end" v-model="valueTime" />
			</view>
			<view class="card_search" v-if="navTitle == '扫码装箱'">
				<view class="details_title">保温箱 <span class="line_title">*</span></view>
				<view class="card_form_item_selectil frameil" @click="incubatorChange">
					<view class="title_input_selectil" :class="incubatorName ? '' : 'hsColor'">
						{{incubatorName || '选择保温箱'}}
					</view>
					<u-icon name="arrow-down" size="18px"></u-icon>
				</view>
			</view>
			<view class="card_search">
				<view class="details_title">运单号 <span class="line_title">*</span></view>
				<view class="card_input">
					<u-input border="surround" v-model="frequencyCoding">
						<template slot="suffix">
							<u-icon name="scan" size="26" @click="sweep"></u-icon>
						</template>
					</u-input>
				</view>
				<view class="deleteCurrent" @click="removeWaybill(frequencyCoding)">
					<u-icon class="icon_current" name="backspace" height="10" size="20"></u-icon>
					<view class="title_nape">删除</view>
				</view>
			</view>
			<view v-if="selectiveType != 'signfor'">
				<view class="card_frequency">
					<view class="card_high space_between">
						<view class="card_frequency_title">已录入运单号</view>
						<view class="card_bottle">已扫<span>{{list.length}}</span></view>
					</view>
					<view style="width: 100%;" v-if="list.length > 0">
						<view class="item_coding" v-for="(item,index) in list" :key="index">
							<view class="title_coding">{{item}}</view>
							<u-icon name="close-circle-fill" color="#c0c4cc" size="20"
								@click="removeWaybill(item)"></u-icon>
						</view>
					</view>
					<view class="card_empty" v-else>
						<u-empty mode="list"></u-empty>
					</view>
				</view>
			</view>
			<view v-else>
				<view style="color: #2979ff;font-size: 30rpx;" @click="examine">查看温湿度记录</view>
				<view class="card_sign_in">
					<view class="details_title1">运单签收图片 <span class="line_title">*</span></view>
					<view>
						<u-upload :fileList="fileList1" name="1" :maxCount="1" @afterRead="afterRead"
							@delete="deletePic"></u-upload>
					</view>
				</view>
				<view class="card_sign_in">
					<view class="details_title1">随货通行单图片 <span class="line_title">*</span></view>
					<view>
						<u-upload :fileList="fileList2" name="2" :maxCount="1" @afterRead="afterRead"
							@delete="deletePic"></u-upload>
					</view>
				</view>
				<view class="card_sign_in">
					<view class="details_title1">冷链交接单图片 <span class="line_title">*</span></view>
					<view>
						<u-upload :fileList="fileList3" name="3" :maxCount="1" @afterRead="afterRead"
							@delete="deletePic"></u-upload>
					</view>
				</view>
			</view>
			<view style="width: 100%;height: 120rpx;"></view>
			<view class="card_btn">
				<u-button style="margin-bottom: 20rpx;" type="primary" :disabled="jurisdiction"
					@click="submit">提交</u-button>
			</view>
		</view>
		<u-popup :show="incubatorShow" closeable @close="close">
			<view class="card_incubator">
				<view class="head_place">选择保温箱</view>
				<view class="card_search_il">
					<u-search placeholder="请输入保温箱名称" v-model="keyword" :showAction="false"
						@change="searchChange"></u-search>
				</view>
				<view style="display: flex;flex-direction: column;" v-if="incubatorData.length > 0">
					<view class="card_title_item" :class="item.name == incubatorName ? 'color_blue' : ''"
						v-for="(item,index) in incubatorData" :key="index" @click="incubatorClick(item)">
						{{item.name}}
					</view>
				</view>
				<view style="margin-bottom: 20px;" v-else>
					<u-empty mode="list" text="暂无保温箱" marginTop="50"></u-empty>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const ENV = require('@/.env.js')
	export default {
		data() {
			return {
				frequencyCoding: '',
				navTitle: '',
				selectiveType: '',
				cmpCode: '',
				list: [],
				orderId: '',
				valueTime: this.getDateTime(new Date()),
				start: Date.now() - 10 * 24 * 3600000,
				end: Date.now() + 10 * 24 * 3600000,
				fileList1: [],
				fileList2: [],
				fileList3: [],
				keyword: '',
				incubatorShow: false,
				incubatorData: [],
				incubator: null,
				incubatorName: '',
			}
		},
		computed: {
			jurisdiction() {
				if (this.selectiveType == 'signfor') {
					if (this.fileList1.length > 0 && this.fileList2.length > 0 && this.fileList3.length > 0) {
						if (this.fileList1[0].message == '成功' && this.fileList2[0].message == '成功' && this.fileList3[0]
							.message == '成功') {
							return false
						} else {
							return true
						}
					} else {
						return true
					}
				}
			}
		},
		onLoad(receive) {
			this.navTitle = receive.title
			this.selectiveType = receive.id
		},
		methods: {
			leftClick() {
				uni.$emit('refresh');
			},
			submit() {
				this.getEntering()
				if (this.list.length > 0) {
					if (this.valueTime) {
						if (this.selectiveType == 'put') {
							// 扫码入库
							this.scanCodes('/api/waybill/warehouse-in')
						} else if (this.selectiveType == 'out') {
							// 扫码出库
							this.scanCodes('/api/waybill/warehouse-out')
						} else if (this.selectiveType == 'truck') {
							// 扫码装车
							this.scanCodes('/api/waybill/car-in')
						} else if (this.selectiveType == 'encasement') {
							// 扫码装箱
							if (this.incubator) {
								this.scanCodes('/api/waybill/cooler-box-in')
							} else {
								uni.$u.toast('请选择保温箱')
							}
						} else if (this.selectiveType == 'unload') {
							// 扫码下车
							this.scanCodes('/api/waybill/car-out')
						} else if (this.selectiveType == 'signfor') {
							if (this.fileList1.length > 0 && this.fileList2.length > 0 && this.fileList3.length > 0) {
								// 扫码签收
								this.scanCodesSignFor('/api/waybill/receipt')
							} else {
								uni.$u.toast('请完善表单')
							}
						}
					} else {
						const title = this.getTitle(this.navTitle)
						uni.$u.toast('请先选择' + title + '时间')
					}
				} else {
					uni.$u.toast('请先录入运单号')
				}
			},
			getTitle(value) {
				const title = value.split('扫码')
				const headline = title[1] + '时间'
				return headline
			},
			// 提交扫码列表
			scanCodes(url) {
				uni.showLoading();
				this.$api.post(url, {
					startTime: this.valueTime,
					waybillNoList: this.list,
					coolerBoxId: this.incubator,
				}).then(res => {
					if (res.code == 200) {
						this.frequencyCoding = ''
						this.list = []
						uni.$u.toast(res.msg)
					} else {
						uni.$u.toast(res.data.msg)
					}
					uni.hideLoading();
				}).catch(() => {
					uni.hideLoading();
				})
			},
			// 提交扫码签收列表
			scanCodesSignFor(url) {
				const signUrl = this.fileList1[0].url + ',' + this.fileList2[0].url + ',' + this.fileList3[0].url
				this.$api.post(url, {
					startTime: this.valueTime,
					waybillNo: this.frequencyCoding,
					receiptImg: signUrl,
				}).then(res => {
					if (res.code == 200) {
						this.frequencyCoding = ''
						this.fileList1 = []
						this.fileList2 = []
						this.fileList3 = []
						this.list = []
						uni.$u.toast(res.msg)
					} else {
						uni.$u.toast(res.data.msg)
					}
				})
			},
			// 扫码录入
			getEntering() {
				if (this.frequencyCoding) {
					this.list.push(this.frequencyCoding)

					function methods1(arr) {
						return Array.from(new Set(arr));
					}
					this.list = methods1(this.list)
				}
			},
			// 扫一扫
			sweep() {
				// 允许从相机和相册扫码
				uni.scanCode({
					scanType: ['barCode'],
					// scanType: ['qrCode'],
					autoZoom: false,
					success: (res) => {
						console.log(res);
						if (res.result) {
							let url = res.result;
							this.frequencyCoding = url
							this.list.push(url)

							function methods1(arr) {
								return Array.from(new Set(arr));
							}
							this.list = methods1(this.list)
						} else {
							console.log('请重新扫描');
							return false;
						}
					},
					fail: (res) => {
						console.log('未识别到二维码');
					}
				})
			},
			// 移除错误运单号
			removeWaybill(value) {
				if (this.frequencyCoding == value) {
					this.frequencyCoding = ''
				}
				const arr = deleteElementById(this.list, value)
				this.list = arr

				function deleteElementById(arr, key) {
					return arr.filter((item) => item !== key);
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '成功',
						url: result
					}))
					fileListLen++
				}
				if (event.name == '1') {
					var arr = []
					this.fileList1.forEach(item1 => {
						arr.push(item1.url)
					})
				} else if (event.name == '2') {
					var arr1 = []
					this.fileList2.forEach(item2 => {
						arr1.push(item2.url)
					})
				} else if (event.name == '3') {
					var arr2 = []
					this.fileList3.forEach(item3 => {
						arr2.push(item3.url)
					})
				}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: ENV.APP_DEV_URL + '/api/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						// formData: {
						// 	user: 'test'
						// },
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
						},
						success: (res) => {
							let state = JSON.parse(res.data)
							setTimeout(() => {
								if (state.code == 200) {
									resolve(state.data)
								}
							})
						}
					});
				})
			},
			getDateTime(date, addZero = true) {
				return `${this.getDate(date, addZero)} ${this.getTime(date, addZero)}`
			},
			getDate(date, addZero = true) {
				date = new Date(date)
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${year}-${addZero ? this.addZero(month) : month}-${addZero ? this.addZero(day) : day}`
			},
			getTime(date, addZero = true) {
				date = new Date(date)
				const hour = date.getHours()
				const minute = date.getMinutes()
				const second = date.getSeconds()
				return this.hideSecond ?
					`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}` :
					`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}:${addZero ? this.addZero(second) : second}`
			},
			addZero(num) {
				if (num < 10) {
					num = `0${num}`
				}
				return num
			},
			// 保温箱选择
			incubatorChange() {
				this.incubatorShow = true
				this.$api.get('/api/cooler-box', {
					page: 1,
					pageSize: 999,
					isBind: true,
					name: this.keyword,
				}).then(res => {
					if (res.code == 200) {
						this.incubatorData = res.data.list
					}
				})
			},
			// 选择保温箱
			incubatorClick(event) {
				this.incubator = event.id
				this.incubatorName = event.name
				this.incubatorShow = false
			},
			// 搜索
			searchChange() {
				this.incubatorData = []
				this.incubatorChange()
			},
			// 查看温湿度记录
			examine() {
				if (this.frequencyCoding) {
					uni.navigateTo({
						url: '/pages/order/humiture?waybillNo=' + this.frequencyCoding
					});
				} else {
					uni.$u.toast('请先扫描运单号')
				}
			},
			close() {
				this.incubatorShow = false
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff !important;
	}

	.card_order_details {
		margin: 10rpx 30rpx 30rpx 30rpx;
	}

	.details_title {
		position: relative;
		width: 140rpx;
		flex: none;
		color: #333;
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 10rpx;
		margin-right: 15rpx;
		padding-left: 15rpx;
	}

	.card_form_item_selectil {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 6px 9px;
		height: 52rpx;
	}

	.title_input_selectil {
		font-size: 30rpx;
		// width: 100%;
	}

	.hsColor {
		color: rgb(192, 196, 204);
	}

	.details_title1 {
		position: relative;
		width: 140rpx;
		text-align: center;
		flex: none;
		color: #333;
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 10rpx;
		margin-right: 15rpx;
		padding-left: 15rpx;
	}

	.card_time {
		width: 100%;
		border: 1rpx solid #dadbde;
		border-radius: 10rpx;
		padding: 6px 9px;
		margin-left: 10rpx;
		line-height: 48rpx;
	}

	.card_search {
		display: flex;
		align-items: center;
		margin: 20rpx 0rpx;
	}

	.card_sign_in {
		margin-top: 30rpx;
		display: flex;
	}

	.scan_title {
		font-size: 20rpx;
	}

	.card_sweep {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex: none;
	}

	.card_input {
		width: 100%;
		// margin-left: 30rpx;
	}

	.line_title {
		position: absolute;
		top: 0rpx;
		left: 0rpx;
		color: red;
	}

	.card_high {
		margin-top: 30rpx;
	}

	.card_frequency {
		display: flex;
		flex-wrap: wrap;
	}

	.card_frequency_title {
		font-size: 32rpx;
	}

	.card_bottle {
		font-size: 30rpx;

		span {
			color: red;
		}
	}

	.item_coding {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		margin-top: 10px;
		padding: 25rpx 0rpx;
		border-bottom: 2rpx solid #dfdfdf;
	}

	.title_coding {
		font-size: 30rpx;
	}

	.card_empty {
		width: 100%;
		margin-top: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.card_btn {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding-left: 30rpx;
		padding-right: 30rpx;
		padding-top: 20rpx;
		background-color: #fff;
		padding-bottom: constant(safe-area-inset-bottom); //兼容 IOS<11.2
		padding-bottom: env(safe-area-inset-bottom); //兼容 IOS>11.2
	}

	.deleteCurrent {
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
		border: 1px solid #e5e5e5;
		padding: 5rpx 0rpx 5rpx 5rpx;
		margin-left: 10rpx;
		border-radius: 8rpx;
		height: 66rpx;

		.icon_current {
			height: 15px;
		}

		.title_nape {
			margin: 0rpx 10rpx;
			display: flex;
			font-size: 20rpx;
			width: 40rpx;
		}
	}

	::v-deep .u-border {
		border-width: 1px !important;
		border-color: #e5e5e5 !important;
		border-style: solid;
	}


	.card_incubator {
		min-height: 600rpx;
		max-height: 900rpx;
	}

	.head_place {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
	}

	.card_search_il {
		margin: 20rpx;
	}

	.card_title_item {
		position: relative;
		padding: 30rpx;
		// border-bottom: 1rpx solid #dadbde;
	}

	.color_blue {
		color: #2979ff;
	}

	.card_title_item:before {
		content: " ";
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 1px;
		border-top: 1px solid #e7e6e4;
		-webkit-transform-origin: 0 0;
		transform-origin: 0 0;
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
	}

	// 伪元素1rpx边框
	.frameil {
		position: relative; //重要
	}

	.frameil::after {
		position: absolute;
		content: '';
		border: 2rpx solid #dadbde;
		width: 200%;
		height: 200%;
		top: 0;
		left: 0;
		transform: scale(0.5);
		transform-origin: 0 0;
		pointer-events: none;
		border-radius: 20rpx;
		/* 使伪元素不会阻止鼠标事件 */
	}
</style>