<template>
	<view class="loadDischarg content_box">
		<!-- #ifdef H5 -->
		<view id="reader" v-if="showReader"></view>
		<!-- #endif -->
		<template v-if="!showReader">
			<shipmentBriefInfo />
			<!-- 扫码装、卸货 -->
			<template v-if="isScanOrder">
				<view class="scanQR flex_center flex_sb">
					<bs-autoInput placeholder="右侧扫码或输入单号" autoApi='/api/query/choice.tm.TransitType/action/auto_choice'
						@onSearch='onSearch' disabled style='flex-grow: 1' />
					<u-icon name="scan" color="#3070FF" size="48" @click="onScanQR" />
				</view>
				<!-- 订单列表 -->
				<view class="order-list">
					<text class="orderQty font_bolder">
						总计：{{orderList.length}}单 {{total.totalQty}}件 {{total.totalWeight}}千克 {{total.totalVolume}}方
					</text>
					<view class="oeder-detail routine_radius_card">
						<view class="order-item" v-for="(item,index) in orderList" :key="index">
							<!-- <u-swipe-action>
								<u-swipe-action-item :options='swipeOption' @click="onDeleteOrder" :name="item">								
								</u-swipe-action-item>
							</u-swipe-action> -->
							<u-row>
								<u-col span="10">
									<bs-customCell label="订单号 :" :value="item.orderNo" labelCol="3" wrapCol="9" />
									<bs-customCell label="货量 :" labelCol="2" wrapCol="10">
										<view slot="value" class="cargoQty">
											<text class="piece">{{item.orderQty}}件</text>
											<text class="ton">{{item.orderWeight}}千克</text>
											<text class="DCube">{{item.orderVolume}}方</text>
										</view>
									</bs-customCell>
								</u-col>
								<view class="flex_center" style="padding-left: 20rpx; border-left: 2rpx solid #E5E5E5">
									<view class="t-icon t-icon-delete" @click="onDeleteOrder(item)" />
								</view>
							</u-row>
						</view>
					</view>
				</view>
			</template>
			<!-- 装、卸货完成显示 -->
			<view class="mainNode-list" v-if="action==='loadFinish' || action==='unloadFinish' || isScanOrder">
				<bs-customRowCell
					:title="action==='loadFinish' || action==='scanOrderLoad' || action==='scanOrderShipLoad' ? '装货状态' : '卸货状态'">
					<view slot="value" @click="onVisible">
						<u-input border="none" readonly inputAlign="left" :value="viewEnums[currentSelect]" />
					</view>
					<u-icon slot="rightIcon" name="arrow-right" size="40" @click="onVisible" />
				</bs-customRowCell>
				<!-- 铅封号 -->
				<template v-if="(action==='loadFinish' || action==='scanOrderLoad' || action==='scanOrderShipLoad') && shipmentMode !== 'MS'">
					<u-line color="#E5E5E5" margin="20rpx 0" />
					<bs-customRowCell title="铅封号">
						<u-input slot="value" name="carSeal" border="none" inputAlign="left" placeholder="输入铅封号"
							v-model="carSeal" holdKeyboard />
					</bs-customRowCell>
				</template>
			</view>
			<!-- 拒收、放弃装货显示 -->
			<template v-if="action==='unloadRefuse' || action==='loadAbort'">
				<view class="reject-sign">
					<bs-customRowCell>
						<view slot="title" class="font_bolder">
							<text style="color: #EB2F48">*</text>
							<text>{{action==='unloadRefuse'?'拒收':'放弃'}}原因</text>
						</view>
						<view slot="value" @click="onVisible">
							<text class="placeholder" v-if="!viewEnums[currentSelect]">
								{{`选择${action==='unloadRefuse'?'拒收':'放弃装货'}原因`}}
							</text>
							{{viewEnums[currentSelect]}}
						</view>
						<u-icon slot="rightIcon" name="arrow-right" size="40" @click="onVisible" />
					</bs-customRowCell>
				</view>
			</template>
			<!-- 数量装货 -->
			<view class="massLoad">
				<bs-customRowCell title="数量装货" v-if="action==='loadQty'">
					<u-input slot="value" type='number' name="loadQty" border="none" inputAlign="left" placeholder="输入装货数量"
						v-model="loadQty" holdKeyboard />
				</bs-customRowCell>			
				<bs-customRowCell title="数量卸货" v-if="action==='unloadQty'">
					<u-input slot="value" type='number' name="unloadQty" border="none" inputAlign="left" placeholder="输入卸货数量"
						v-model="unloadQty" holdKeyboard />
				</bs-customRowCell>
			</view>
			<!-- 拒收、放弃装货不显示 上传图片、备注 -->
			<view class="base-content" v-if="action!=='unloadRefuse'">
				<!-- 上传图片 -->
				<view class="upload-img" v-if="action!=='loadQty' && action!=='unloadQty'">
					<bs-uploader uploadTitle="上传图片" ref="myUploadImg" v-if="action!=='loadAbort'" />
				</view>
				<!-- 备注信息 -->
				<bs-todoRemark ref="myRemark" />
			</view>
			<!-- 底部按钮 -->
			<view class="operation-btn flex_sb">
				<button class="backBtn common_btn" @click="onNavBack">返回</button>
				<button :class="['common_btn', {'submitBtn': !isScanOrder}]" :disabled="true" @click="onSubmit" v-if="isScanOrder && !orderList.length">
					{{action==='scanOrderLoad' || action==='scanOrderShipLoad' ? '装货完成' : (action==='scanOrderUnload' || action==='scanOrderShipUnload' ? '卸货完成' :'确定')}}
				</button>			
				<button :class="['common_btn', {'submitBtn': !isScanOrder}]" @click="onSubmit" v-else>
					{{action==='scanOrderLoad' || action==='scanOrderShipLoad' ? '装货完成' : (action==='scanOrderUnload' || action==='scanOrderShipUnload' ? '卸货完成' :'确定')}}
				</button>
			</view>
			<!-- 类型选择常规弹窗 -->
			<bs-selectPopup ref="mySelectPop" :popTitle="popTitle" :selectEnum="selectEnum" :visible="visible"
				@onVisible="onVisible" @onConfirm="onConfirmSelect" />
		</template>
	</view>
</template>

<script>
	import { rejectSign, waiveLoad, loadStates, unloadStates } from "../../enum/enum"
	import { shipmentLocation, shipmentStop, OMShipmentCancel, ORShipmentCancel, getLocationLoade} from '../../api/apiList'
	// #ifdef H5
	import { Html5Qrcode } from "html5-qrcode"
	// #endif
	const getUserLocation = require('../../mixins/getUserLocation')
	const app = getApp()
	export default {
		mixins: [getUserLocation],
		options: { styleIsolation: 'shared' },
		data() {
			return {
				shipmentMode: '', // 运输模式 OM、OR、MS: 大宗运输Mass
				shipmentNo: "", //运单号

				carSeal: "", //铅封号
				loadQty: '', //装货数量
				unloadQty: '', //卸货数量
				currentSelect: "", //当前选择
				selectEnum: [], //类型枚举
				viewEnums: {}, //视图枚举
				visible: false,
				popTitle: '', //弹窗标题
				action: "", //当前状态
				isScanOrder: false, //是否为扫码装卸
				selectedIds: [], //shipmentLocationId
				orderList: [], //运输单列表
				total: { //总计
					totalQty: 0,
					totalWeight: 0,
					totalVolume: 0
				},
				swipeOption: [{ //活动单元格按钮组
					icon: 'trash-fill',
					style: {
						backgroundColor: '#f56c6c',
						width: '100rpx',
						height: '100%',
					}
				}],
				showReader: false
			}
		},
		onLoad: function(options) {		
			const data = JSON.parse(options.data)
			const action = data.action
			let shipmentMode = ''
			switch (app.globalData.shipmentInfo.shipmentBizName) { //根据shipmentBizName 判断运输模式
				case 'tm.MovementShipment':
				case 'tm.SectionShipment': 
					shipmentMode = 'OM'
					break
				case 'tm.MassShipment':
					shipmentMode = 'MS'; //大宗运输
					break
				default:
					shipmentMode = 'OR';
			}
			let selectEnum = []
			let popTitle = ''
			switch (action) {
				case "unloadRefuse":
					selectEnum = rejectSign
					popTitle = '请选择拒收原因'
					break;
				case "loadAbort":
					selectEnum = waiveLoad
					popTitle = '请选择放弃装货原因'
					break;
				case "loadFinish":
				case "scanOrderLoad":
				case "scanOrderShipLoad":
					selectEnum = loadStates
					popTitle = '请选择装货状态'
					break;
				default:
					selectEnum = unloadStates
					popTitle = '请选择卸货状态'
			}
			let viewEnums = {}
			selectEnum.map(item => {
				viewEnums[item.value] = item.label
			})
			const isScanOrder = action.includes('scanOrder')
			const loadDischargMode = {
							loading: "装货开始",
							loadFinish: "装货完成",
							loadQty: "数量装货",
							unloadQty: "数量卸货",
							scanOrderLoad: "扫码装货", //已配载
							scanOrderShipLoad: "扫码装货", // 未配载
							loadAbort: "放弃装货",
							unloading: "卸货开始",
							unloadFinish: "卸货完成",
							scanOrderUnload: "扫码卸货", //已配载  
							scanOrderShipUnload: "扫码卸货", //未配载      
							unloadRefuse: "拒收",
						}
			this.setNavTitle(loadDischargMode[action])

			this.action = action
			this.popTitle = popTitle
			this.isScanOrder = isScanOrder
			this.shipmentMode = shipmentMode
			this.selectEnum = selectEnum
			this.viewEnums = viewEnums
			this.currentSelect = selectEnum[0].value
			this.selectedIds = [data.selectedId]
			this.shipmentNo = app.globalData.shipmentInfo.shipmentNo
			this.getUserSetting() //获取当前位置
			if(isScanOrder){
				this.initLocationLoade()
			}
		},
		methods: {
			//设置页面头部标题
			setNavTitle(title) {
				uni.setNavigationBarTitle({ title })
			},
			
			//扫码装货时获取已确认装货订单列表			
			initLocationLoade(){
				const newAction = this.action.includes('Unload') ? 'getUnloadedData' : 'getLoadedData'
				const data = {
					"args": {
						"selectedIds": this.selectedIds
					}
				}
				getLocationLoade(newAction, data).then(res => {
					// OR OM 运输模式判断
					if (this.shipmentMode === 'OM') {
						this.onShipModeOM(res.data.data)
					} else if(this.shipmentMode === 'OR') {
						this.onShipModeOR(res.data.data)
					}
				})
			},			
						
			// 确认
			onSubmit() {
				this.confirmReport()
			},
						
			//确认提交
			confirmReport() {
				let remark = '' //备注信息
				let action = this.action
				const imgInstance = this.$refs.myUploadImg //获取图片上传实例
				const remarkInstance = this.$refs.myRemark // 获取备注信息实例
				const { longitude, latitude, address, time } = this.locationInfo
				if (remarkInstance) {
					remark = remarkInstance.value
				}
				
				let baseData = {
					"aux": {
						content: action === "loadAbort" || action === "unloadRefuse" ? `${this.currentSelect}|${remark}` : remark,
						weightTime: time,
						qty: action === 'loadQty' ? this.loadQty : this.unloadQty,
						carSeal: this.carSeal,
						loadUnloadStatus: action === "loading" || action === "unloading" ? '' :  this.currentSelect,
						time,
						longitude,
						latitude,
						address,
						eventSource: 'DriverApp',
					},
					"args": {
						"selectedIds": this.selectedIds
					}
				}
				
				if (this.isScanOrder) { //判断是否为扫码装卸
					action = action.includes('Unload') ? 'unloadFinish' : 'loadFinish'
				}
				if (imgInstance) {
					imgInstance.uploadImage(images => {
						baseData.aux.images = images						
						if(this.shipmentMode === 'MS'){
							this.onMassShipment(action, baseData)
						} else {
							this.onReportTost(action, baseData)
						}
					})
				} else {
					if(this.shipmentMode === 'MS'){
						this.onMassShipment(action, baseData)
					} else {
						this.onReportTost(action, baseData)
					}
				}
			},

			//上报函数调用提示 action：提交的动作类型 data：接口请求参数
			onReportTost(action, data) {
				shipmentLocation(action, data).then(res => {
					if (res.data.messageType === 'success') {
						uni.showToast({
							title: '操作成功',
							duration: 3000
						})
						setTimeout(() => {
							this.onNavBack()
						}, 1500)
					}
				})
			},
			
			//大宗装卸货
			onMassShipment(action, data){
				shipmentStop(action, data).then(res => {
					if (res.data.messageType === 'success') {
						uni.showToast({
							title: '操作成功',
							duration: 3000
						})
						setTimeout(() => {
							this.onNavBack()
						}, 1500)
					}
				})
			},
			
			//类型选择弹窗
			onVisible() {
				const mySelectPop = this.$refs.mySelectPop
				if (mySelectPop) {
					mySelectPop.setSelect(this.currentSelect)
				}
				this.visible = !this.visible
			},
			//确认选择
			onConfirmSelect(value) {
				this.currentSelect = value
				this.visible = false
			},
			//返回上一级页面
			onNavBack() {
				uni.navigateBack()
			},

			//单号输入查询
			onSearch(orderNo) {
				this.onScanQRSuccess(orderNo)
			},

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

			onHtml5QrCode() { //适用微信以外H5扫码
				const _this = this
				this.showReader = true
				this.$nextTick(() => {
					const {windowWidth, windowHeight} = uni.getSystemInfoSync()
					const minWidth = Math.min(windowWidth, windowHeight)
					let config = { //扫一扫相关设置
						fps: 10, //默认帧数，增加以提高扫码速度，过大则影响性能，应小于1000
						qrbox: { width: minWidth * 0.667, height: minWidth * 0.667 }, //扫码取景器宽高
						aspectRatio: Math.ceil((windowHeight / windowWidth) * 100) / 100 ,//扫码视频流背景比例，默认4:3
					}
					let html5QrCode = new Html5Qrcode("reader")			
					Html5Qrcode.getCameras().then((devices) => {
						if (devices && devices.length) {
							let cameraId = "";
							if (devices.length == 1) {
								cameraId = devices[0].id; //前置摄像头
							} else {
								cameraId = devices[1].id; //后置摄像头
							}
							if (cameraId) {
								html5QrCode.start({ deviceId: { exact: cameraId } }, config, (resText, result) => {								
									html5QrCode.stop() //停止扫码
									_this.onScanQRSuccess(resText)
									_this.showReader = false
								}).catch((err) => {
									alert("通过摄像头扫码异常....", err)
									this.showReader = false
								});
							}
						} else { //不带相机ID扫描,允许传递约束来代替相机设备 ID, environment 表示后置摄像头  换成user则表示前置摄像头
							const facingMode = { facingMode: "environment" } || { facingMode: { exact: "environment" } }
							html5QrCode.start(facingMode, config, (resText, result) => {													
								html5QrCode.stop() //停止扫码
								_this.onScanQRSuccess(resText)
								_this.showReader = false
							}).catch((err) => {
								alert("通过摄像头扫码异常....", err)
						 	this.showReader = false
							});
						}
					}).catch((err) => {
						uni.showToast({
							title: '用户取消授权,重进应用以重新授权',
							icon: 'none',
							duration: 3000
						})
						this.showReader = false
					});
				})
			},

			//扫码成功回调
			onScanQRSuccess(orderNo) {
				// if (!(orderNo.includes('OR') || orderNo.includes('OM'))) {
				// 	uni.showToast({
				// 		title: '请输入正确运输订单号!',
				// 		icon: 'none',
				// 		duration: 3000
				// 	})
				// 	return
				// }
				const action = this.action
				const data = {
					"aux": {
						codes: orderNo + '\n', //type: String
						noField: 'orderNo',
					},
					"args": {
						"selectedIds": this.selectedIds
					}
				}
				//上传运单号
				shipmentStop(action, data).then(res => {
					if (res.data.messageType === 'success') {
						uni.showToast({
							title: '扫码成功',
							duration: 3000
						})
						// OR OM 运输模式判断
						if (this.shipmentMode === 'OM') {
							this.onShipModeOM(res.data.data)
						} else if(this.shipmentMode === 'OR') {
							this.onShipModeOR(res.data.data)
						}
					}
				})
			},
			//OM模式
			onShipModeOM(data) {
				let { orderList, total } = this
				data.map(item => {
					orderList.push({
						id: item.id, //当前订单id
						orderNo: item['movement_no'],
						orderQty: item['ship_qty'],
						orderWeight: item['ship_weight'],
						orderVolume: item['ship_volume']
					})
					total.totalQty += item['ship_qty']
					total.totalWeight += item['ship_weight']
					total.totalVolume += item['ship_volume']
				})
				this.orderList = [...orderList]
				this.total = total
			},
			//OR模式
			onShipModeOR(data) {
				let { orderList, total } = this
				data.map(item => {
					orderList.push({
						id: item.id, //当前订单id
						orderNo: item['order_no'],
						orderQty: item['qty'],
						orderWeight: item['weight'],
						orderVolume: item['volume']
					})
					total.totalQty += item['qty']
					total.totalWeight += item['weight']
					total.totalVolume += item['volume']
				})
				this.orderList = [...orderList]
				this.total = total
			},
			//删除订单
			onDeleteOrder(orderInfo) {
				const _this = this
				uni.showModal({
					title: '删除提示',
					content: '确定删除该回单吗？',
					success: (res) => {
						if (res.confirm) {							
							const newAction = _this.action.includes('Unload') ? 'unloadCancel' : 'loadCancel'
							const reqData = {
								"args": {
									"selectedIds": [orderInfo.id]
								}
							}
							// OR OM 运输模式判断
							if (_this.shipmentMode === 'OM') {
								OMShipmentCancel(newAction, reqData).then(res => { //OM模式取消
									_this.onCancelBack(orderInfo, res)
								})
							} else if (_this.shipmentMode === 'OR') {
								ORShipmentCancel(newAction, reqData).then(res => { //OR模式取消
									_this.onCancelBack(orderInfo, res)
								})
							}
						} else if (res.cancel) {}
					}
				})
			},
			//更新订单列表
			onCancelBack(orderInfo, res) {
				let { orderList, total } = this
				if (res.data.messageType === 'success') {
					uni.showToast({
						title: '删除成功',
						duration: 3000
					})
					orderList = orderList.filter(item => item.id !== orderInfo.id)
					total.totalQty -= orderInfo.orderQty
					total.totalWeight -= orderInfo.orderWeight
					total.totalVolume -= orderInfo.orderVolume
					this.orderList = [...orderList]
					this.total = total
				}
			},
		}
	}
</script>

<style lang="scss">
	.loadDischarg {

		.scanQR {
			padding: 24rpx 32rpx;
			font-size: 28rpx;
			background: #fff;
			margin: 0 0 24rpx 0;

			/deep/.uicon-scan {
				margin-left: 30rpx;
			}
		}

		.order-list {
			padding: 0 32rpx;
			background-color: #ffffff;
			padding-top: 36rpx;

			.orderQty {
				font-size: 28rpx;
				color: #262626;
				margin-bottom: 24rpx;
			}

			.oeder-detail {
				margin-top: 30rpx;
				padding: 10rpx;
				min-height: 200rpx;

				/deep/.order-item {
					overflow: hidden;
					border-radius: 12rpx;
					margin-bottom: 20rpx;
					background: #F5F5F5;

					.piece,
					.ton,
					.DCube {
						font-size: 24rpx;
						margin: 0 20rpx;
					}

					.t-icon-delete {
						width: 48rpx;
						height: 48rpx;
					}

					.custom-cell-row {
						margin: 10rpx 0 10rpx 10rpx;
					}

					.u-swipe-action-item__content {
						background-color: #E9E9E9;
					}

					&/deep/.uicon-trash-fill {
						font-size: 40rpx !important;
					}
				}
			}
		}

		/deep/.mainNode-list,
		/deep/.reject-sign {
			margin-top: 24rpx;
			padding: 0 32rpx;
			background-color: #ffffff;

			.customRow-title {
				margin-left: 0;
				font-size: 28rpx;
				color: #8C8C8C;
			}

			.customRow-value {
				width: 60%;
			}

			.cell-leftIcon {
				width: 0;
			}

			.icon-min-width {
				justify-content: flex-end;
			}
		}
		
		/deep/.massLoad{
			background-color: #ffffff;
			
			.u-cell__body {
				padding: 40rpx 0;
				
				.u-cell__body__content{
					flex-grow: 0.65;
				}
				.customRow-title {
					margin-left: 0;
					font-size: 28rpx;
					color: #8C8C8C;
				}
			}									
		}

		.base-content {
			margin-top: 24rpx;
			padding: 32rpx;
			background-color: #ffffff;

			.upload-img {
				margin-bottom: 32rpx;
			}

			.todo-remark {
				margin-top: 0;
			}

			/deep/.u-textarea__count {
				background: transparent !important;
			}
		}

		.operation-btn {
			min-height: 220rpx;

			.common_btn {
				&[disabled] {
					border: none;
					color: #BFBFBF;
					background-color: #F0F0F0;
				}
			}
		}
	}
</style>
