<template>
	<!-- 运单页面 -->
	<view>
		<u-navbar title="" autoBack placeholder>
			<view class="u-nav-slot nav_center" slot="center" @click="openCenter">
				<view style="width: calc(100% - 90rpx);">
					<u-search shape="square" :disabled="false" :showAction="false" placeholder="请输入运单号搜索"></u-search>
				</view>
			</view>
		</u-navbar>
		<view class="tab_order">
			<u-tabs :list="tableList" lineColor="#333333" lineWidth="60" :scrollable="false" :current="current"
				@change="tabClick"></u-tabs>
		</view>
		<view class="card_order_mangement" v-if="orderList.length > 0">
			<x-orderManagement ref="order" :orderList="orderList" @sendOrders="sendOrders"
				@operateSuccessfully="operateSuccessfully" @proofRenewal="proofRenewal"
				@definiteCompletion="operateSuccessfully" :key="keyId"></x-orderManagement>
			<view style="width: 50%;">
				<u-loadmore :status="loadStatus" :key="Math.random()" />
				<!-- <u-divider v-if="loadingMore" :text="loading"></u-divider> -->
			</view>
		</view>
		<u-empty mode="order" marginTop="50" v-else></u-empty>
		<u-popup :show="sendShow" closeable round="8" :closeOnClickOverlay="false" @close="close">
			<view class="card_send">
				<view class="send_title">派单</view>
				<view class="card_input_send">
					<view class="incubator_title"><span>*</span>保温箱</view>
					<view class="card_search_gray frame" @click="focus(false)">
						<span v-if="incubator.name">{{incubator.name}}</span>
						<span class="title_gray" v-else>请选择保温箱</span>
						<u-icon name="arrow-down" color="#c8c9cc" size="18"></u-icon>
					</view>
				</view>
				<view class="card_input_send">
					<view class="incubator_title"><span>*</span>冰排编号</view>
					<u-input placeholder="请输入冰排编号" border="surround" v-model="iceNumber" @blur="iceRaftBlur">
						<template slot="suffix">
							<u-icon name="scan" size="24" @click="sweep"></u-icon>
						</template>
					</u-input>
					<view class="add_card center_in" @click="addIce">
						<u-icon name="plus" size="18"></u-icon>
					</view>
				</view>
				<view class="card_frequency">
					<view class="card_high space_between">
						<view class="card_frequency_title">已扫冰排编号</view>
						<view class="card_bottle">已扫<span>{{iceList.length}}</span></view>
					</view>
					<scroll-view :scroll-top="scrollTop" scroll-y="true" class="swept_card">
						<view class="scrollView" style="width: 100%;" v-if="iceList.length > 0">
							<view class="item_coding" v-for="(item,index) in iceList" :key="index">
								<view style="display: flex;align-items: center;">
									<view class="num_index">{{index + 1}}</view>
									<view class="title_coding">{{item}}</view>
								</view>
								<u-icon name="close-circle-fill" color="#c0c4cc" size="20"
									@click="removeWaybill(item)"></u-icon>
							</view>
						</view>
					</scroll-view>
				</view>
				<view style="width: 100%;height: 120rpx;"></view>
				<view class="card_btn">
					<u-button type="primary" text="确定" @click="confirm"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const ENV = require('@/.env.js')
	export default {
		data() {
			return {
				tableList: [],
				list: [{
					name: '全部',
				}, {
					id: 3,
					name: '待配送',
				}, {
					id: 4,
					name: '配送中'
				}, {
					id: 5,
					name: '已送达'
				}, {
					id: 6,
					name: '已拒收'
				}],
				current: 0,
				userInfo: {},
				orderList: [],
				pageSize: 10,
				currentPage: 1,
				loadingMore: true,
				loading: '加载中',
				status: null,
				sendShow: false,
				incubatorValue: '',
				thermostatList: [],
				incubatorMore: true,
				Pagination: 1,
				searchShow: false,
				hintTitle: '请选择保温箱',
				currentItem: '',
				iceNumber: '',
				iceList: [],
				scrollTop: null,
				incubator: {
					id: null,
					name: '',
				},
				imageData: '',
				loadStatus: 'loadmore', //loading 、nomore
				keyId: 0,
				waybillId: null,
				classifyId: null,
			}
		},
		onUnload() {
			// console.log('页面销毁')
			this.getempty()
		},
		onShow() {
			uni.$on('success', (data) => {
				uni.$off('success')
				this.currentPage = 1
				this.orderList = []
				this.$nextTick(() => {
					this.getList()
				})
			})
			let incubator = uni.getStorageSync('incubatorValue')
			if (incubator) {
				this.incubator.id = incubator.id
				this.incubator.name = incubator.name
			}
			uni.$on('send', (data) => {
				// try {
				// } catch (error) {}
				uni.$off('send')
				this.currentPage = 1
				this.orderList = []
				this.$nextTick(() => {
					this.getList()
				})
			})
		},
		onReachBottom() {
			if (!this.loadingMore) {
				this.getList()
			}
		},
		async onLoad(value) {
			//注册监听事件签字图片
			uni.$on('sign', (data) => {
				if (this.$refs.order) {
					this.$refs.order.imageData = data.replace(/[\r\n]/g, "");
				}
				this.getUpload(data)
			})
			if (value.current) {
				this.current = Number(value.current)
			}
			var userInfo = this.$cache.getCache('userInfo')
			// console.log(userInfo, 25)
			this.userInfo = userInfo
			this.tableList = this.list
			let statusType = null
			if (this.current != 0 || this.current) {
				statusType = this.tableList[this.current].id
			}
			this.status = statusType
			this.$nextTick(() => {
				console.log(4)
				this.getList()
			})
		},
		methods: {
			openCenter() {
				uni.navigateTo({
					url: '/pages/order/orderSearch'
				});
			},
			getempty() {
				this.iceList = []
				this.incubator.id = ''
				this.incubator.name = ''
				this.iceNumber = ''
				uni.removeStorageSync('incubatorValue');
				this.Pagination = 1
				this.currentItem = ''
				this.incubatorValue = ''
				this.hintTitle = '请选择保温箱'
				this.sendShow = false
				this.incubatorMore = true
				this.thermostatList = []
			},
			// 获取司机和仓管运单列表
			getList() {
				uni.showLoading({
					title: '加载中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				})
				this.loadStatus = 'loading'
				this.loadingMore = true;
				this.$api.get('/api/waybill', {
					page: this.currentPage,
					pageSize: this.pageSize,
					status: this.status,
					assignment_status: 2,
				}).then(res => {
					if (res.code == 200) {
						const data = res.data.list
						if (this.loadingMore == true && data) {
							this.orderList = this.orderList.concat(data);
						}
						if (data.length < this.pageSize) {
							this.loadingMore = true
							this.loading = '没有更多了'
							this.loadStatus = 'nomore'
						} else {
							this.loading = '加载中'
							this.loadStatus = 'loading'
							this.loadingMore = false
							this.currentPage++
						}
					}
					uni.hideLoading();
					this.$forceUpdate()
				}).catch(() => {
					uni.hideLoading();
					this.loadingMore = true
					this.loadStatus = 'nomore'
				})
			},
			// 防拆更新
			proofRenewal() {
				this.currentPage = 1
				this.orderList = []
				this.getList()
			},
			// 派单
			sendOrders(value) {
				// console.log(value, 3333)
				this.waybillId = value.id
				this.sendShow = true
				// this.getIncubator()
			},
			// 重新获取列表
			operateSuccessfully() {
				this.currentPage = 1
				this.orderList = []
				this.getList()
			},
			// 获取保温箱
			getIncubator() {
				this.$api.get('/api/cooler-box', {
					page: this.Pagination,
					pageSize: this.pageSize,
					name: this.incubatorValue,
					status: '2',
				}).then(res => {
					if (res.code == 200) {
						const data = res.data.list
						data.forEach(item => {
							item.flag = false
						})
						if (this.incubatorMore == true) {
							this.thermostatList = this.thermostatList.concat(data);
						}
						if (data.length < this.pageSize) {
							this.incubatorMore = false
						} else {
							this.incubatorMore = true
						}
					}
				})
			},
			// 确定派单
			confirm() {
				if (this.incubator.id) {
					if (this.iceList.length > 0) {
						const arr = []
						arr.push(this.waybillId)
						this.$api.post('/api/waybill/delivery', {
							waybillIds: arr,
							coolerBoxId: this.incubator.id,
							iceRaftCode: this.iceList,
						}).then(res => {
							if (res.code == 200) {
								this.currentPage = 1
								uni.$u.toast(res.msg)
								this.sendShow = false
								this.tabClick()
							} else if (res.code == 2000) {
								let arrTitle = res.data
								let title = ' ,请将冰排' + arrTitle.toString() + '重新入库'
								uni.$u.toast(res.msg + title)
								this.sendShow = false
								this.tabClick()
							} else {
								uni.$u.toast(res.msg)
							}
						})
					} else {
						uni.$u.toast('请先扫描冰排')
					}
				} else {
					uni.$u.toast('请先选择保温箱')
				}
			},
			// 滚动加载更多
			loadMore() {
				if (this.incubatorMore) {
					this.Pagination++
					this.getIncubator()
				}
			},
			// tab运单
			tabClick(row) {
				this.loadStatus = 'loading'
				this.keyId = row.index
				this.loadingMore = true
				this.currentPage = 1
				this.orderList = []
				if (row) {
					this.status = row.id
					this.classifyId = row.id
				}
				this.getList()
				this.getempty()
			},
			close() {
				this.getempty()
			},
			// 搜索保温箱
			incubatorInput(value) {
				if (this.searchShow) {
					this.incubatorMore = true
					this.Pagination = 1
					this.thermostatList = []
					// this.getIncubator()
				}
			},
			// 鼠标聚焦
			focus() {
				uni.navigateTo({
					url: '/pages/order/Incubator'
				});
				// this.searchShow = true
				// if (this.currentItem) {
				// 	this.incubatorValue = ''
				// 	this.hintTitle = this.currentItem
				// } else {
				// 	this.hintTitle = '请选择保温箱'
				// }
			},
			// 鼠标失去焦点
			blur(value) {
				setTimeout(() => {
					this.searchShow = false
					if (this.currentItem) {
						this.incubatorValue = this.currentItem
					}
				})
			},
			// 冰排失去焦点
			iceRaftBlur(value) {
				if (value) {
					this.iceList.push(value)
					this.iceList = this.uniqueArray(this.iceList)
				}
			},
			// 选择保温箱
			selectIncubator(value) {
				this.thermostatList.forEach(item => {
					if (item.id == value.id) {
						item.flag = true
						this.incubatorValue = item.name
						this.currentItem = item.name
						this.searchShow = false
						this.getCoolerBox(item.id)
					} else {
						item.flag = false
					}
				})
			},
			// 获取保温箱内冰排
			getCoolerBox(id) {
				this.$api.get('/api/ice-raft/cooler-box', {
					coolerBoxId: id,
				}).then(res => {
					if (res.code == 200) {
						this.iceList = res.data
					}
				})
			},
			// 移除错误运单号
			removeWaybill(value) {
				if (this.iceNumber == value) {
					this.iceNumber = ''
				}
				const arr = deleteElementById(this.iceList, value)
				this.iceList = arr

				function deleteElementById(arr, key) {
					return arr.filter((item) => item !== key);
				}
			},
			// 扫一扫
			sweep() {
				// 允许从相机和相册扫码
				uni.scanCode({
					scanType: ['barCode'],
					// scanType: ['qrCode'],
					autoZoom: false,
					success: (res) => {
						// console.log(res);
						if (res.result) {
							let url = res.result;
							this.iceNumber = url
							this.iceList.push(url)

							function methods1(arr) {
								return Array.from(new Set(arr));
							}
							this.iceList = methods1(this.iceList)
						} else {
							console.log('请重新扫描');
							return false;
						}
					},
					fail: (res) => {
						console.log('未识别到二维码');
					}
				})
			},
			// 添加冰排 
			addIce() {
				if (this.iceNumber) {
					this.iceList.push(this.iceNumber)
					this.iceList = this.uniqueArray(this.iceList)
					this.$nextTick(() => {
						// 获取scroll-view的高度
						const query = uni.createSelectorQuery().in(this);
						query.select('.scrollView').boundingClientRect(data => {
							this.scrollTop = data.height;
						}).exec();
					});
					this.iceNumber = ''
				}
			},
			// 签名板
			async getUpload(file) {
				const result = await this.uploadFilePromise(file)
				if (this.$refs.order) {
					this.$refs.order.imageData = result
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: ENV.APP_DEV_URL + '/api/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
						},
						success: (res) => {
							let state = JSON.parse(res.data)
							setTimeout(() => {
								if (state.code == 200) {
									resolve(state.data)
								}
							}, 100)
						}
					});
				})
			},
			// 去重
			uniqueArray(arr) {
				return [...new Set(arr)];
			},
		}
	}
</script>

<style lang="scss">
	.nav_center {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding-right: 30rpx;
		width: 100%;
	}

	.tab_order {
		background-color: #fff;
	}

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

	.card_send {
		padding: 20rpx;
		min-height: 600rpx;
	}

	.send_title {
		text-align: center;
		margin: 10px;
	}

	.card_input_send {
		position: relative;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.card_thermostat {
		position: absolute;
		bottom: 100rpx;
		background-color: #fff;
		width: 100%;
		border-radius: 8rpx;
		border: 2rpx solid #E4E7ED;
		background-color: #FFF;
		box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, .1);
		z-index: 2024;
	}

	.popper_arrow {
		position: absolute;
		bottom: -6px;
		left: 50%;
		margin-right: 3px;
		border-top-color: #ebeef5;
		border-bottom-width: 0;
		border-width: 6px;
		filter: drop-shadow(0 2px 12px rgba(0, 0, 0, .03));
	}

	.popper_arrow::after {
		position: absolute;
		display: block;
		width: 0;
		height: 0;
		border-color: transparent;
		border-style: solid;
		bottom: -6px;
		margin-left: -6px;
		border-top-color: #fff;
		border-bottom-width: 0;
		content: " ";
		border-width: 6px;
	}

	.incubator_title {
		width: 150rpx;
		margin-right: 10rpx;
		font-size: 30rpx;

		span {
			color: red;
		}
	}

	.add_card {
		margin-left: 10rpx;
		width: 50rpx;
		height: 46rpx;
		border-radius: 8rpx;
		padding: 6px 9px;
		border: 1px solid #dadbde;
	}

	.card_btn {
		position: absolute;
		bottom: 20rpx;
		left: 30rpx;
		right: 30rpx;
		padding: 20rpx 0rpx;
	}

	.scroll-view {
		transition: max-height 1s ease-out;
		max-height: 0;
		overflow: hidden;
	}

	.is-fold {
		max-height: 600rpx;
	}

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

	.nomatchingData {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
		color: #c8c9cc;
	}

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

	.swept_card {
		padding: 0rpx 20rpx;
		width: calc(100% - 40rpx);
		max-height: 600rpx;
		// overflow-y: auto;
	}

	.card_high {
		margin-bottom: 20rpx;
	}

	.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%;
		padding: 20rpx 0rpx;
	}

	.num_index {
		font-size: 30rpx;
		margin-right: 10rpx;
	}

	.title_coding {
		font-size: 30rpx;
	}


	.card_search_gray {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		flex: 1;
		padding: 12rpx 18rpx;
		border-radius: 8rpx;
		line-height: 48rpx;
	}

	.title_gray {
		font-size: 30rpx;
		color: #c8c9cc;
	}

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

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