<template>
	<view class="waybill-content content_box">
		<!-- 顶部tabs -->
		<view class="tabs-outer">
			<view class="tabs flex">
				<view :class="['tab',{'active' : tabActive==='unfinished'}]" @click="switchTab('unfinished')">未完成运单</view>
				<view :class="['tab',{'active' : tabActive==='finished'}]" @click="switchTab('finished')">已完成运单</view>
			</view>
			<view class="search-input flex_center">
				<u-search search-icon="scan" searchIconSize="60" searchIconColor="#595959" placeholderColor='#BFBFBF' color="#595959" :showAction="false" :placeholder="'请输入运单号'"
				    clearabled v-model="searchValue" @focus="onFocus" @blur='onBlur' @clickIcon="onScanQR" @search="onSearch" @clear="onSearch"/>
				<u-icon class='searchIcon' size="60" name="search" @click="onSearch"/>
			</view>
		</view>
		<!-- <button @click="onPreviewFile">文件下载</button> -->
		<!-- 接单卡片 -->
		<template v-if="tabActive==='unfinished' && acceptList.length && !isFocus">
			<view class="receive-order" v-if="orderItem.remainingQty" v-for="orderItem in acceptList" :key="orderItem.id">
				<template>
					<view class="flex_sb receive-card-header">
						<text>订单号: {{orderItem['orderCarrier.massOrder.orderNo']}}</text>
						<text>剩余货量 {{orderItem.remainingQty}}</text>
					</view>
					<view class="receive-card">
						<view class="stations">
							<view class="start-station flex_center">
								<view class="t-icon t-icon-start-sddress" />
								<text>{{orderItem['orderCarrier.massOrder.originalAddress.name']}}</text>
							</view>
							<view class="end-station flex_center" style="margin-bottom: 32rpx;">
								<view class="t-icon t-icon-end-sddress" />
								<text>{{orderItem['orderCarrier.massOrder.destinationAddress.name']}}</text>
							</view>
						</view>
						<bs-customCell label="核定装运量" :value="orderItem.capacity" labelCol="3" wrapCol="9" />
						<bs-customCell label="要求送达日期" :value="orderItem['orderCarrier.massOrder.latestArrivalTime'] || '无'" labelCol="3.5" wrapCol="8.5" />
						<view class="reciveBtn flex_center flex_cen" @click="onClick(orderItem.id)">接单</view>
						<view class="trips flex_sb flex_center">
							<view class="maxTrip flex_col"><text class="tripQty">{{orderItem.maxShipments}}</text><text>最多趟次</text></view>
							<u-line direction="col" color="#BFBFBF" length="68rpx" />
							<view class="minTrip flex_col"><text class="tripQty">{{orderItem.minShipments}}</text><text>最少趟次</text></view>
							<u-line direction="col" color="#BFBFBF" length="68rpx" />
							<view class="triped flex_col"><text class="tripQty">{{orderItem.actualShipments}}</text><text>已接趟次</text></view>
						</view>
					</view>
				</template>
			</view>
		</template>
		<!-- 运单列表 -->
		<!-- <shipmentItem v-for="item in [{id:1,shipmentStatus: 'Approved'}]" :key="item.id" :propData="item" @onReload="onReload" /> -->
		<shipmentItem v-for="item in orderList" :key="item.id" :propData="item" @onReload="onReload" />

		<!-- 空状态 -->
		<view class="emptyImg flex_col" v-if="!orderList.length && !isFocus">
			<image mode="aspectFit" src="../../static/img/empty/shipmentEmpty.png" />
			<text class="empty-text">暂时没有运单</text>
		</view>
		<!-- 反馈提示 -->
		<u-popup :show="visible" mode='center' round='24'>
			<view class="flex_col" style="width: 620rpx;height: 378rpx;align-items: center;justify-content: space-evenly">
				<view :class="['t-icon', isSuccess ? 't-icon-success' : 't-icon-fail']" style="width: 120rpx;height: 120rpx;"/>
				<view v-if="isSuccess" style="color: #434343;font-size: 36rpx;font-weight: 600;">接单成功</view>
				<view v-else class="flex_col flex_center">
					<text style="color: #434343;font-size: 36rpx;font-weight: 600;">接单失败</text>
					<text style="color: #8C8C8C;font-size: 28rpx;font-weight: 400;margin-top: 24rpx;">当前车辆已存在作业中运单</text>
				</view>
			</view>
		</u-popup>
		<!-- 搜索历史 -->
		<view class="search-content" v-if="isFocus" @touchmove.stop.prevent="onTouchMove">
			<view class="flex_sb flex_center" style="margin-bottom: 24rpx;">
				<view class="" style="font-size: 28rpx; color: #8C8C8C;">搜索历史</view>
				<image src="../../static/img/icon/trash.png" @click="clearHistory"></image>
			</view>
			<view class="search-button-group">
				<view class="search-button" v-for="(searchItem, index) in searchHistory" :key="index" @click="onSearchHistory(searchItem)">
					{{searchItem}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { shipmentOrder, findAcceptOrders, CreateShipment, ApproveShipment, DownloadFile, findFileName } from '../../api/apiList'
	import { formatGMT } from '../../utils/util'
	import { TokenPrefix } from '../../publicConfig/config.js'
	const getUserLocation = require('../../mixins/getUserLocation')
	export default {
		mixins: [getUserLocation],
		options: { styleIsolation: 'shared' },
		data() {
			return {
				visible: false,
				isSuccess: true,
				acceptList: [], //接单列表
				orderList: [], //运单列表
				tabActive: "unfinished",
				pageNum: 1, //页码
				pageSize: 20, //每页条数
				loadMore: true, //加载更多,

				searchValue: "", //搜索值
				isFocus: false,
				searchHistory: []
			}
		},
		onLoad: function() {
			const time = setInterval(() => {
				let XSRFToken = uni.getStorageSync(`${TokenPrefix}_XSRFToken`)
				if (XSRFToken) {
					this.initData()
					this.getAcceptList()
					this.initMapService() //初始化地图
					clearInterval(time)
				}
			}, 1000);
		},
		//下拉刷新
		onPullDownRefresh: function() {
			this.onReload()
		},
		//触底加载更多
		onReachBottom: function() {
			if (this.loadMore) {
				this.initData();
				this.loadMore = false
			}
		},
		methods: {

			//文件预览Demo
			async onPreviewFile(){				
				const _this = this				
				const datas = [
					// '1db64b3974d5e75b542ffc2355f13b779c64f44a.pdf', //1月地铁发票
					// '05a4ce248f5f1db8e3b7ca9cab67b0a81558e4fc.docx', //新建 DOCX 文档
					// '88023779bb81a1e222679278ad889b7a5bab491d.jpg',
					'940507a5acc6ed1771b8f411d749d20586f96ac6.pdf',
					// 'e49040bbea4989b5d2cb875352ecef298c5d8579.pptx', //3D Load模拟简要说明
					// 'b63255dfbdf00b6d91dc315c95123284ec02afdd.xlsx', //单用例导入模板 (1)
				]
				uni.showLoading({
					title: '下载中',
				})
				let files = [] //文件列表
				for (let file of datas) {
					const filePath = await DownloadFile(file, false) //获取临时文件路径
					// const res = await findFileName(file) //获取文件名,小程序可通过DownloadFile接口所返回res直接获取，无需额外调用
					// const oldFileName = res.header["Content-Disposition"].split("=")[1]; //解析文件名, 注意["Content-Disposition"]大小写
					// const fileName = decodeURIComponent(oldFileName.split("UTF-8''")[1])//解码&解码类型
					const fileType = file.split('.')[1] //截取文件名后缀，获取文件类型		
					files.push({fileId: file, filePath, fileName: 'test', fileType})
				}
				uni.hideLoading()
				uni.navigateTo({
					url: `/subpkg/previewFile/previewFile?files=${JSON.stringify(files)}`,
				})
			},

			//初始化数据
			initData() {
				const { tabActive, pageNum, pageSize } = this
				let reqData = {
					"args": {
						"pageNum": pageNum,
						"pageSize": pageSize
					}
				}
				if(this.searchValue){
					reqData.args.restrictions = [{
						"field": 'shipmentNo',
						"type": "LK", //EQ精准匹配，LK模糊匹配
						"value": this.searchValue
					}]
				}
				shipmentOrder(tabActive, reqData).then(res => {
					uni.stopPullDownRefresh()
					const data = res.data.data.datas
					if (data.length > 0) {
						data.map(item => { //格式化时间
							item.shipmentDate = formatGMT(item.shipmentDate, 'D')
							item.finishTime = formatGMT(item.finishTime, 'D')
						})
						this.orderList = this.orderList.concat(data)
						this.pageNum = pageNum + 1
						this.loadMore = true
					}
				})								                    
			},
			// tab切换
			switchTab(key) {
				if (this.tabActive !== key) {
					uni.pageScrollTo({ scrollTop: 0 })
					this.tabActive = key
					this.searchValue = ''
					this.isFocus = false
					this.onReload()
				}
			},
			// 刷新页面
			onReload() {
				this.orderList = []
				this.pageNum = 1
				this.initData()
				if(this.tabActive === 'unfinished'){
					this.onReloadAccept()
				}
			},

			onReloadAccept(){
				this.acceptList = []
				this.getAcceptList()
			},

			//获取接单列表
			getAcceptList(){
				const reqData = {"args": {"pageNum": 1, "pageSize": 1000}}
				findAcceptOrders(reqData).then(res => {
					uni.stopPullDownRefresh()
					let datas = res.data.data.datas
					datas.map(item => {
						item['orderCarrier.massOrder.latestArrivalTime'] = formatGMT(item['orderCarrier.massOrder.latestArrivalTime'], 'D')
						item.capacity = String(item.capacity)
						if(item.splitMode === 'Weight'){ //计算剩余货量
							item.remainingQty = item['orderCarrier.weight'] - item['orderCarrier.shipWeight']
						} else {
							item.remainingQty = item['orderCarrier.qty'] - item['orderCarrier.shipQty']
						}
					})
					this.acceptList = [...datas]
				})
			},

			//接单
			onClick(orderId){
				//判断是否存在
				let flag = true
				this.orderList.map( orderItem => {
					switch(orderItem.shipmentStatus){
						case 'Shipping': //运输中
						case 'Approved': //已确认
						case 'Dispatch': //已发车
						    flag = false
						    break;
						default: flag = true
					}
				})
				if(flag){
					const reaData = {"args": { "selectedIds": [orderId]}}
					CreateShipment(reaData).then(res => {
						if (res.data.messageType === 'success') {
							const shipmentId = res.data.data.id
							const bizName = res.data.data['biz_name']
							this.onvisible(true)
							if(bizName !== 'tm.MassShipment'){
								this.onApproveShipment(shipmentId)
							} else {
								this.onReload()
							}
						}
					})
				} else {
					this.onvisible(false)
				}
			},
			//确认运单
			onApproveShipment(shipmentId){
				const data = {"args": { "selectedIds": [shipmentId]}}
				ApproveShipment(data).then(res => {
					if (res.data.messageType === 'success') {
						this.onReload()
					}
				})
			},
			onvisible(value){
				this.visible = true
				this.isSuccess = value
				setTimeout(() => {
					this.visible = false
				}, 1500)
			},

			// 点击扫码
			onScanQR() {
				// #ifdef H5
				this.$jwx.scanQRCode({
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
					success: (res) => {
						const shipmentNo = res.resultStr;
						this.searchValue = shipmentNo
						this.onSearch()
					},
					fail: (err) => {
						uni.showToast({
							title: '扫码失败 !',
							icon: 'none',
							duration: 3000
						})
					}
				})
				// #endif
				// #ifndef H5
				uni.scanCode({
					success: (res) => {
						const shipmentNo = res.result;
						this.searchValue = shipmentNo
						this.onSearch()
					},
					fail: (err) => {
						uni.showToast({
							title: '扫码失败 !',
							icon: 'none',
							duration: 3000
						})
					}
				})
				// #endif
			},

			// 搜索功能
			onSearch() {
				uni.pageScrollTo({ scrollTop: 0 })
				this.isFocus = false
				this.onSetSearchHistory()
				this.onReload()
			},
			//设置搜索历史
			onSetSearchHistory(){
				let searchHistory = uni.getStorageSync('SearchHistory') || []
				if (!searchHistory.includes(this.searchValue) && this.searchValue.trim() !== '') {
					searchHistory.unshift(this.searchValue)
					if (searchHistory.length > 10) {
						searchHistory.pop()
					}
					uni.setStorageSync('SearchHistory', searchHistory)
				}
			},
			onFocus() {
				this.isFocus = true
				this.searchHistory = uni.getStorageSync('SearchHistory')
			},
			onBlur() {
				// #ifdef MP
				this.isFocus = false //H5事件捕获异常
				// #endif
			},
			clearHistory() {
				this.searchHistory = []
				uni.setStorageSync('SearchHistory', [])
			},
			onSearchHistory(searchItem) {
				this.searchValue = searchItem
				this.onSearch()
			},
			onTouchMove(){
				//防止滚动穿透
			},
		}
	}
</script>

<style lang="scss">
	.waybill-content {
		.emptyImg {
			align-items: center;

			image {
				width: 609rpx;
			}

			.empty-text {
				font-size: 28rpx;
				text-align: center;
				color: #BFBFBF;
			}
		}

		.tabs-outer {
			position: sticky;
			top: 0;
			z-index: 1;
			background: #FFFFFF;
			margin-bottom: 24rpx;

			.tabs {
				color: #8C8C8C;
				font-weight: 400;
				margin: 24rpx;
				border-radius: 40rpx;
				justify-content: space-between;
				align-items: center;
				line-height: 48rpx;

				.tab {
					flex: 1;
					padding: 14rpx 0rpx;
					border-radius: 40rpx;
					text-align: center;
				}

				.active {
					font-weight: 500;
					color: #2E75E6;
					background: rgba(46, 117, 230, .15);
					border-radius: 40rpx;
				}
			}

			//搜索相关
			.search-input {
				width: 100%;
				height: 100rpx;
				position: relative;

				/deep/.u-search__content {
					height: 80rpx;
					margin: 0 24rpx 24rpx;
					padding-right: 100rpx;
					background: #F9F9F9 !important;

					.u-search__content__input {
						border-left: 2rpx solid #D9D9D9;
						margin: 0 0 0 24rpx;
						padding-left: 24rpx;
						letter-spacing: 3rpx;
						background-color: transparent !important;
					}

					.uicon-close {
						font-size: 28rpx !important;
					}
				}

				.searchIcon, .uicon-search{
					position: absolute !important;
					right: 12px;
					top: 10% !important;
					transform: translateX(-50%);
					z-index: 1;
				}
			}
		}

		.receive-order {
			margin: 0 24rpx 24rpx;
			background: linear-gradient(180deg, #6065E3 0%, #6A8CF8 16%, #D2DCFC 100%);
			box-shadow: 1rpx 3rpx 12rpx 0rpx rgba(0, 0, 0, 0.04);
			border-radius: 25rpx;

			.receive-card-header {
				font-size: 28rpx;
				font-weight: 300;
				color: #FFFFFF;
				text-shadow: 1rpx 3rpx 12rpx rgba(0, 0, 0, 0.04);
				margin: 28rpx 24rpx;
			}

			.receive-card {
				margin: 0 8rpx 8rpx;
				padding: 16rpx;
				background: linear-gradient(180deg, #EDF1FF 0%, #FFFFFF 100%);
				box-shadow: 1rpx 3rpx 12rpx 0rpx rgba(0, 0, 0, 0.04);
				border-radius: 16rpx;

				.custom-cell-row {
					color: #8C8C8C;
					margin-top: 12rpx;
				}

				.start-station,
				.end-station {
					margin: 16rpx 0 27rpx;
					font-size: 30rpx;
					font-weight: bolder;

					.t-icon {
						margin-right: 6rpx;
					}
				}

				.reciveBtn {
					color: #FFFFFF;
					padding: 18rpx;
					margin: 32rpx 0;
					border-radius: 44rpx;
					box-shadow: 1rpx 3rpx 12rpx 0px rgba(0, 0, 0, 0.04);
					background: linear-gradient(90deg, #2E75E6 1%, #5E58EE 100%);
				}

				.trips {
					padding: 0 64rpx 24rpx;
					font-size: 28rpx;
					font-weight: 400;
					line-height: 45rpx;
					color: #8C8C8C;
					text-shadow: 1rpx 3rpx 12rpx rgba(0, 0, 0, 0.04);

					.tripQty {
						font-size: 32rpx;
						font-weight: 500;
						color: #434343;
						text-align: center;
						text-shadow: r1px 3rpx 12rpx rgba(0, 0, 0, 0.04);
					}
				}
			}
		}

		.search-content {
			position: fixed;
			top: 200rpx;
			z-index: 999;
			height: 100%;
			width: 100%;
			background-color: #FFFFFF;
			padding: 24rpx;

			image {
				width: 25rpx;
				height: 28rpx;
			}
		}

		//搜索历史
		.search-button-group {
			display: flex;
			flex-wrap: wrap;
			align-content: flex-start;
		}

		.search-button {
			border-radius: 32rpx;
			height: 64rpx;
			line-height: 48rpx;
			max-width: 180rpx;
			padding: 12rpx 24rpx;
			background-color: #F5F5F5;
			font-size: 28rpx;
			color: #434343;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			margin-bottom: 24rpx;
			margin-right: 24rpx;
		}
	}
</style>
