<template>
	<view class="signFor content_box">
		<shipmentBriefInfo />
		<!-- 订单信息 -->
		<view class="orders-total">
			<view class="orderQty font_bolder">订单总数：{{orderList.length}}</view>
			<scroll-view class="order-detail-list" scroll-y>
				<u-empty mode="data" textSize='32' iconSize="160" text="暂无订单" v-if="!orderList.length" />
				<view class="order-detail-item" v-for="(item,index) in orderList" :key="index">
					<view class="orderNo">订单号 : {{item.orderNo}}</view>
					<u-line color="#F0F0F0" margin="20rpx 0" />
					<view class="cargoQty">
						<text>货量 :</text>
						<text style="margin-left: 30rpx;">{{item.qty}}件 /</text>
						<text style="margin-left: 20rpx;">{{item.weight}}千克 /</text>
						<text style="margin-left: 20rpx;">{{item.volume}}方</text>
					</view>
					<!-- 异常选择 -->
					<view class="abnormal-select flex_sb flex_center">
						<text>是否异常</text>
						<u-switch v-model="item.abnormal" size="43" activeColor="#EB2F48" />
					</view>
					<!-- 备注信息 -->
					<view class="remark-content">
						<u-textarea border="none" placeholder="请输入备注" v-model="item.content" holdKeyboard />
						<!-- 图片上传 -->
						<block v-if="!isSignature">
							<view class="uploader-imgList flex flex_wrap">
								<view class="previewImages" v-for="(itm,idx) in item.images" :key="idx">
									<image mode="aspectFill" :src="itm" @click="onPreviewImage(idx, item.images)"
										class="previewImg" />
									<u-icon name="close-circle-fill" class="clearIcon" size="30"
										@click="deleteImage(idx, item)" />
								</view>
								<!-- <view v-if="!item.images.length" style=" width: 200rpx" /> -->
								<template v-if="isIos">
									<view class="uploadeBtn flex_col" @click="onUpLoad(item.id)">
										<view class="t-icon t-icon-picture" />
										<text style="margin-top:6rpx">上传照片</text>
										<view class="font_bolder orderTotal">
											<text style="color: #f56c6c;position: absolute;right: -2rpx;">*</text>
											<text>（{{item.images.length}}/6）</text>
										</view>
									</view>
								</template>
								<template v-else>
									<u-upload :fileList="item.images" :maxCount="6" :sizeType="['compressed']" multiple :previewImage="false"
										@afterRead="uploadAfterRead" :name="item.id">
										<!-- 自定义上传按钮 -->
										<view class="uploadeBtn flex_col">
											<view class="t-icon t-icon-picture" />
											<text style="margin-top:6rpx">上传照片</text>
											<view class="font_bolder orderTotal">
												<text style="color: #f56c6c;position: absolute;right: -2rpx;">*</text>
												<text>（{{item.images.length}}/6）</text>
											</view>	
										</view>
									</u-upload>
								</template>
							</view>
						</block>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 底部按钮 -->
		<view class="operation-btn flex_sb">
			<button class="backBtn common_btn" @click="onNavBack">取消</button>
			<button class="signatureBtn common_btn" @click="onNavSignature" v-if="isSignature">签名</button>
			<button class="submitBtn common_btn" @click="onSubmit" v-else>确定</button>
		</view>
	</view>
</template>

<script>
	import { signFor, uploadImg, ordermovementOM, ordermovementOR, ordermovementMASS } from '../../api/apiList'
	const getUserLocation = require('../../mixins/getUserLocation')
	const appInstance = getApp()

	export default {
		mixins: [getUserLocation],
		data() {
			return {
				orderList: [], //订单列表
				selectedId: '', //shipmentLocationId
				isSignature: true, //是否为签名
				isIos: false,
				orderItemId: '',
				shipmentId: '', //运单id
				shipmentMode: '', // 运输模式 OM、OR、MS: 大宗运输Mass
				locationId: '',
				stopId: ''
			}
		},
		onLoad: function(options) {
			let data = JSON.parse(options.data)
			const { action, selectedId } = data
			const title = action === "signature" ? '电子签收' : '纸质签收'
			const isSignature = action === "signature"
			const { shipmentId, shipmentBizName } = appInstance.globalData.shipmentInfo
			const { locationId, id } = appInstance.globalData.stopsInfo
			let shipmentMode = ''
			switch (shipmentBizName) { //根据shipmentBizName 判断运输模式
				case 'tm.MovementShipment':
				case 'tm.SectionShipment': //暂时走OM逻辑
					shipmentMode = 'OM'
					break
				case 'tm.MassShipment':
					shipmentMode = 'MS'; //大宗运输
					break
				default:
					shipmentMode = 'OR';
			}
			this.shipmentMode = shipmentMode
			this.shipmentId = shipmentId
			this.isSignature = isSignature
			this.action = action
			this.selectedId = selectedId
			this.locationId = locationId
			this.initData()
			this.setNavTitle(title)
			// #ifdef H5
			const platform = uni.getSystemInfoSync().platform
			if (platform === 'ios') {
				// this.isIos = true
			}
			// #endif
			this.getUserSetting()
		},
		methods: {
			//设置页面头部标题
			setNavTitle(title) {
				uni.setNavigationBarTitle({
					title: title,
				})
			},
			//返回上一级页面
			onNavBack() {
				uni.navigateBack()
			},
			//初始化数据
			initData() {
				let newDatas = []
				if (this.shipmentMode === 'MS') {
					const reqData = { "aux": { "id": this.shipmentId } }
					ordermovementMASS(reqData).then(res => {
						const data = res.data.data.header
						newDatas.push({
							'id': data['massOrder.id'], //订单id
							'orderNo': data['massOrder.orderNo'], //订单号
							'qty': data['massOrder.qty'], //订单件数
							'weight': data['massOrder.weight'], //订单重量
							'volume': data['massOrder.volume'], //订单体积
							'abnormal': false, //订单是否异常
							'images': [], //订单图片
							'content': '', //订单备注信息
						})
						this.orderList = [...newDatas]
					})
				} else {
					const reqData = {
						"args": {
							"pageNum": 1,
							"pageSize": 100,
							"restrictions": [{
								"field": "shipment.id",
								"type": "EQ",
								"value": this.shipmentId
							}, {
								"field": 'destinationAddress.id',
								"type": "EQ",
								"value": getApp().globalData.stopsInfo.locationId
							}]
						}
					}
					const isOM = this.shipmentMode === 'OM'
					const requestFun = isOM ? ordermovementOM : ordermovementOR
					requestFun(reqData).then(res => {
						const datas = res.data.data.datas
						datas.map(item => {
							newDatas.push({
								'id': item.id, //订单id
								'orderNo': isOM ? item.movementNo : item.orderNo, //订单号
								'qty': isOM ? item.shipQty : item.qty, //订单件数
								'weight': isOM ? item.shipWeight : item.weight, //订单重量
								'volume': isOM ? item.shipVolume : item.volume, //订单体积
								'abnormal': false, //订单是否异常
								'images': [], //订单图片
								'content': '', //订单备注信息
							})
						})
						this.orderList = [...newDatas]
					})
				}
			},

			// 确认
			onSubmit() {
				this.convertReqData().then(list => {
					this.onSignFor(list)
				})
			},
			//订单签收
			onSignFor(list) {
				const { shipmentMode, selectedId, shipmentId, locationId } = this
				const { longitude, latitude, address, time } = this.locationInfo
				let baseReqData = {
					'aux': {
						stopId: locationId,
						shipmentId,
						list: [...list],
						eventSource: 'DriverApp',
						longitude,
						latitude,
						address,
						time
					}
				}
				const signMode = {
					'OM': 'MovementShipment',
					'OR': 'SimpleShipment',
					'MS': 'MassShipment'
				}
				signFor(signMode[shipmentMode], baseReqData).then(res => {
					if (res.data.messageType === 'success') {
						uni.showToast({
							title: '操作成功',
							duration: 3000
						})
						setTimeout(() => {
							this.onNavBack()
						}, 1500)
					}
				})
			},

			//格式化请求数据
			convertReqData() {
				const _this = this
				let list = []
				let orderList = this.orderList
				if (!orderList.length) {
					this.customTost()
					return
				}
				return new Promise((reslove, reject) => {
					for (let order of orderList) {
						if (!order.images.length) { //判断备注和图片必填
							uni.showToast({
								title: `订单${order.orderNo}图片信息不能为空`,
								icon: 'none',
								duration: 3000
							})
							break
						}
						_this.uploadImages(order.images, imgs => {
							list.push({
								'id': order.id,
								'images': imgs,
								'abnormal': order.abnormal,
								'content': order.content
							})
							if (list.length === orderList.length) {
								reslove(list)
							}
						})
					}
				})
			},
			//图片上传 IOS兼容
			onUpLoad(orderId) {
				if (this.$jwx) {
					const _this = this
					const sourceType = this.isIos ? ['album'] : ['album', 'camera'] // 可以指定来源是相册还是相机, ios指定为仅相册
					this.$jwx.chooseImage({
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: sourceType,
						success: function(res) {
							_this.onConvert(res.localIds)
							_this.orderItemId = orderId
						}
					})
				}
			},
			async onConvert(localIds) {
				for (var i = 0; i < localIds.length; i++) {
					await this.onReadImage(localIds[i]);
				}
			},
			onReadImage(localId) {
				const _this = this
				return new Promise((resolve, reject) => {
					_this.$jwx.getLocalImgData({
						localId: localId, // 图片的localID
						success: function(res) {
							const localData = res.localData
							let orderList = _this.orderList
							orderList.forEach(order => {
								if (order.id === _this.orderItemId) {
									order.images = [...order.images, localData]
								}
								return
							})
							_this.orderList = [...orderList]
							resolve('done!')
						}
					});
				})
			},
			//上传图片
			uploadImages(fileList, callback) {
				let images = []
				fileList.forEach(item => {
					uploadImg(item).then(res => {
						uni.hideLoading()
						let data = JSON.parse(res).data
						images.push(data.path)
						if (images.length === fileList.length) {
							return callback(images.join('|'))
						}
					}).catch(err => {
						console.log(err);
					})
				})
			},
			// 自定义轻提示
			customTost() {
				uni.showToast({
					title: '暂无可签收订单',
					icon: 'none',
					duration: 3000
				})
			},
			// 上传图片回调
			uploadAfterRead(info) {
				const { file, name } = info
				const newFile = file.map(item => item.url);
				let orderList = this.orderList
				orderList.forEach(order => {
					if (order.id === name) {
						order.images = [...order.images, ...newFile]
					}
					return
				})
				this.orderList = [...orderList]
			},
			// 预览图片回调
			onPreviewImage(index, images) {
				uni.previewImage({
					current: index,
					urls: images
				})
			},
			// 删除已选图片
			deleteImage(index, info) {
				let orderList = this.orderList
				uni.showModal({
					title: '删除提示',
					content: '确定删除本张图片吗？',
					success: (res) => {
						if (res.confirm) {
							orderList.forEach(order => {
								if (order.id === info.id) {
									let images = [...order.images]
									images.splice(index, 1)
									order.images = [...images]
								}
								return
							})
							this.orderList = [...orderList]
						} else if (res.cancel) {}
					}
				})
			},

			//跳转签名
			onNavSignature() {
				let orderList = this.orderList
				if (!orderList.length) {
					this.customTost()
					return
				}
				const flags = []
				orderList.map(order => {
					if (order.abnormal && !order.content) { //判断备注必填
						uni.showToast({
							title: '订单异常备注不能为空',
							icon: 'none',
							duration: 3000
						})
						flags.push(false)

					} else {
						flags.push(true)
					}
				})
				if (flags.every(item => item)) {
					const { locationId, orderList, shipmentMode, locationInfo, shipmentId } = this
					const data = { orderList, selectedId: locationId, locationInfo, shipmentMode, shipmentId }
					uni.navigateTo({
						url: `/subpkg/signature/signature?data=${JSON.stringify(data)}`,
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	.orders-total {
		font-size: 28rpx;
		background: #FAFAFA;

		.orderQty {
			padding: 26rpx 30rpx;
		}

		.order-detail-list {
			height: 800rpx;

			.order-detail-item {
				margin-bottom: 35rpx;
				padding: 30rpx;
				background-color: #FFFFFF;

				.orderNo,
				.cargoQty {
					margin-bottom: 30rpx;
				}

				.orderNo {
					color: #8C8C8C;
				}

				.remark-content {
					margin-top: 30rpx;
					padding: 16rpx;
					background: #FAFAFA;
					border-radius: 8px;

					/deep/.u-textarea {
						background: #FAFAFA;
					}

					.uploader-imgList {
						padding-top: 20rpx;

						.previewImages {
							position: relative;
							overflow: hidden;

							.previewImg {
								width: 180rpx;
								height: 140rpx;
								margin: 0 10rpx 20rpx;
							}

							/deep/.uicon-close-circle-fill {
								width: 26rpx;
								height: 26rpx;
								border-radius: 50%;
								background-color: #fff;
								color: #D81E06 !important;
								position: absolute;
								top: 5rpx !important;
								right: 15rpx;
							}
						}

						.uploadeBtn {
							position: relative;
							color: #929292;
							width: 180rpx;
							height: 140rpx;
							border: 2rpx dashed #D9D9D9;
							margin: 0 0 20rpx 6rpx;
							background-color: #fff;
							justify-content: center;
							align-items: center;
							font-size: 24rpx;

							.orderTotal {
								color: #333333;
								position: absolute;
								right: -90rpx;
								bottom: 0;
								z-index: 999;
							}

							.t-icon-picture {
								width: 50rpx;
								height: 50rpx;
							}
						}
					}
				}
			}
		}
	}
</style>
