<template>
		<uni-collapse ref="myCollapse" v-model="activeNames" @change="onChange">
			<view class="outer-frame" v-for="item in stopsdatas" :key="item.id" @click.capture="onClickPanel" :data-info="item">
				<!-- 装货站点渲染模板-->
				<template v-if="item.loadStop">
					<uni-collapse-item :show-arrow="false" title-border="none" :name="item.id">
						<!-- 自定义标题栏左侧内容 -->
						<template v-slot:title>
							<view class="loadStop-station-title flex_center">
								<text class="station-state">装</text>
								<text style="flex-grow: 1">{{item['location.name']}}</text>
								<!-- 自定义标题栏右侧图标 -->
								<view :class="['panel-title-rightIcon', 't-icon', activeNames.includes(item.id) ? 't-icon-unfold' :'t-icon-fold']" />
							</view>
						</template>
						<!-- 主体内容-->
						<view class="station-content">
							<bs-customRowCell leftIcon="calling-card" :title="item['location.addressContact.name']" separator>
								<view slot="rightIcon" class="row-rightIcon t-icon t-icon-phone" @click="onVisiblePhoneList" />
							</bs-customRowCell>
							<bs-customRowCell leftIcon="address" separator :title="getLocationCity(item)">
								<view slot="rightIcon" class="row-rightIcon t-icon t-icon-navigation" @click="onNavigation" :data-address="item" />
							</bs-customRowCell>
							<bs-customRowCell leftIcon="cargoQty" isOmits>
								<view slot="title">
									<text class="cargoQty-item">{{item.loadOrders}}单</text>
									<text class="cargoQty-item">{{item.planLoadQty}}件</text>
									<text class="cargoQty-item">{{item.planLoadWeight}}千克</text>
									<text class="cargoQty-item">{{item.planLoadVolume}}方</text>
								</view>
							</bs-customRowCell>
							<bs-customRowCell leftIcon="warn" title="提货要求">
								<u-icon slot="rightIcon" name="arrow-right" size="44" @click="onVisibleRemark" />
							</bs-customRowCell>
							<!-- 动态显示区域 -->
							<template v-if="shipmentStatus !=='Approved'">
								<view class="transport_info">
									<bs-customCell label="到达站点" :value="item.actualArrivalTime" labelCol="3" wrapCol="9"
										v-if="item.actualArrivalTime" />
									<bs-customCell :label="orderSplitMode === 'Weight' ? '重量装货' : '数量装货'" :value="item.weightTime" labelCol="3" wrapCol="9"
										v-if="item.weightTime" />	
									<bs-customCell label="开始装货" :value="item.loadStartTime" labelCol="3" wrapCol="9"
										v-if="item.loadStartTime" />
									<bs-customCell label="完成装货" :value="item.loadFinishTime" labelCol="3" wrapCol="9"
										v-if="item.loadFinishTime" />
									<bs-customCell label="过磅磅差" :value="String(item.netWeight)" labelCol="3" wrapCol="9" />
									<bs-customCell label="离开站点" :value="item.actualDepartureTime" labelCol="3" wrapCol="9"
										v-if="item.actualDepartureTime" />
								</view>
								<!-- 操作按钮区域 -->
								<template
									v-if="shipmentStatus ==='Shipping' || shipmentStatus ==='Dispatch' || shipmentStatus ==='Finished'">
									<view class="operation-btns flex_sb flex_wrap">
										<button class="common_btn" :disabled="item.actualArrivalTime"
											@click="onActionStops" data-action="arrival">到站</button>
										<button class="common_btn" :disabled="item.loadFinishTime"																					
											@click="onVisible" data-action="loadStop">装货</button>
										<button class="common_btn" :disabled="orderSplitMode === 'Qty'" data-path="/subpkg/uploadWeight/uploadWeight"
											@click="onNavigatePage" data-action="uploadPound">磅单</button>
										<button class="common_btn" :disabled="item.actualDepartureTime"
											@click="onActionStops" data-action="departure">离站</button>
									</view>
								</template>
							</template>
						</view>
					</uni-collapse-item>
				</template>
				<!-- 卸货站点渲染模板 -->
				<template v-if="item.unloadStop">
					<uni-collapse-item :show-arrow="false" title-border="none" :name="item.id">
						<!-- 自定义标题栏左侧内容 -->
						<template v-slot:title>
							<view class="unloadStop-station-title flex_center">
								<text class="station-state">卸</text>
								<text style="flex-grow: 1">{{item['location.name']}}</text>
								<!-- 自定义标题栏右侧图标 -->
								<view :class="['panel-title-rightIcon', 't-icon', activeNames.includes(item.id) ? 't-icon-unfold' :'t-icon-fold']" />
							</view>
						</template>
						<!-- 主体内容-->
						<view class="station-content">
							<bs-customRowCell leftIcon="calling-card" :title="item['location.addressContact.name']" separator>
								<view slot="rightIcon" class="row-rightIcon t-icon t-icon-phone" @click="onVisiblePhoneList" />
							</bs-customRowCell>
							<bs-customRowCell leftIcon="address" separator :title="getLocationCity(item)">
								<view slot="rightIcon" class="row-rightIcon t-icon t-icon-navigation"
									@click="onNavigation" :data-address="item" />
							</bs-customRowCell>
							<bs-customRowCell leftIcon="cargoQty" isOmits>
								<view slot="title">
									<text class="cargoQty-item">{{item.unloadOrders}}单/</text>
									<text class="cargoQty-item">{{item.planUnloadQty}}件/</text>
									<text class="cargoQty-item">{{item.planUnloadWeight}}千克/</text>
									<text class="cargoQty-item">{{item.planUnloadVolume}}方</text>
								</view>
							</bs-customRowCell>
							<bs-customRowCell leftIcon="warn" title="配送要求">
								<u-icon slot="rightIcon" name="arrow-right" size="44" @click="onVisibleRemark" />
							</bs-customRowCell>
							<!-- 动态显示区域 -->
							<template v-if="shipmentStatus !=='Approved'">
								<view class="transport_info">
									<bs-customCell label="到达站点" :value="item.actualArrivalTime" labelCol="3" wrapCol="9"
										v-if="item.actualArrivalTime" />
									<bs-customCell :label="orderSplitMode === 'Weight' ? '重量卸货' : '数量卸货'" :value="item.weightTime" labelCol="3" wrapCol="9"
										v-if="item.weightTime" />	
									<bs-customCell label="开始卸货" :value="item.unloadStartTime" labelCol="3" wrapCol="9"
										v-if="item.unloadStartTime" />
									<bs-customCell label="完成卸货" :value="item.unloadFinishTime" labelCol="3" wrapCol="9"
										v-if="item.unloadFinishTime" />
									<bs-customCell label="过磅磅差" :value="String(item.netWeight)" labelCol="3" wrapCol="9" />
									<bs-customCell label="离开站点" :value="item.actualDepartureTime" labelCol="3" wrapCol="9"
										v-if="item.actualDepartureTime" />
									<!-- <bs-customCell label="纸质签收" :value="item.receiveTime" labelCol="3" wrapCol="9"
										v-if="item.receiveTime" /> -->
									<bs-customCell label="签收时间" :value="item.signatureTime" labelCol="3" wrapCol="9"
										v-if="item.signatureTime" />
								</view>
								<!-- 操作按钮区域 -->
								<template
									v-if="shipmentStatus ==='Shipping' || shipmentStatus ==='Dispatch' || shipmentStatus ==='Finished'">
									<view class="operation-btns flex_sb flex_wrap">
										<button class="common_btn" :disabled="item.actualArrivalTime"
											@click="onActionStops" data-action="arrival">到站</button>
										<button class="common_btn" :disabled="item.unloadFinishTime"
											@click="onVisible" data-action="unloadStop">卸货</button>
										<button class="common_btn" :disabled="orderSplitMode === 'Qty'" data-path="/subpkg/uploadWeight/uploadWeight"
											@click="onNavigatePage" data-action="uploadPound">磅单</button>
										<button class="common_btn" :disabled="item.actualDepartureTime"
											@click="onActionStops" data-action="departure">离站</button>
										<button class="common_btn" :disabled="item.signatureTime"
											@click="onNavigatePage" data-path="/subpkg/signFor/signFor"
											data-action="receive">纸质签收</button>
										<button class="common_btn" :disabled="item.signatureTime"
											@click="onNavigatePage" data-path="/subpkg/signFor/signFor"
											data-action="signature">电子签收</button>
									</view>
								</template>
							</template>
						</view>
					</uni-collapse-item>
				</template>
			</view>
			<!-- 弹窗组件 -->
			<!-- 联系方式 -->
			<u-action-sheet :show="phoneListVisible" cancelText="取消" safeAreaInsetBottom @close="onVisiblePhoneList"
				round="26">
				<view class="contactList flex_col">
					<text selectable class="phoneItem"
						@click="onMakePhoneCall">联系人电话：{{currentLocationInfo['location.addressContact.tel'] || '暂无'}}</text>
					<!-- <text style="border-top: 2rpx solid #DFDFDF;width:100%; margin:10rpx 0" /> -->
				</view>
			</u-action-sheet>
			<!-- 提货备注详情 -->
			<view @touchmove.stop.prevent="onTouchMove">
				<u-popup :show="remarkVisible" round="32" mode="bottom" closeable @close="onVisibleRemark">
					<scroll-view scroll-y class="remarks-container" >					
						<view class="remarks-title">
							<text>{{currentLocationInfo.loadStop ? '提货' : '配送'}}要求</text>
						</view>
						<u-empty mode="data" textSize='32' iconSize="160" text="暂无备注" v-if="!orderRemarks.length" />
						<view class="remark-item" v-for="(item,index) in orderRemarks" :key="item.id">
							<text>{{index + 1}}.</text>
							<text class="remark-orderNo"> 订单号：{{item.orderNo}}</text>
							<view class="remark-detail">
								<text>要求：</text>
								<text>{{(currentLocationInfo.loadStop ? item.originalRequirement : item.destinationRequirement) || ''}}</text>
							</view>
						</view>
					</scroll-view>
				</u-popup>
			</view>		
			<!-- 装卸货类型选择 -->
			<bs-selectPopup ref="mySelectPop" :popTitle="`请选择${currentLocationInfo.loadStop ? '装' : '卸'}货类型`"
				:selectEnum="optionEnums" :visible="visible" @onVisible="onVisible" @onConfirm="onConfirmSelect" />
		</uni-collapse>
	</view>
</template>

<script>
	import AMap from '../../utils/AMapUtil.js'; //高德工具类
	import BMap from '../../utils/BMapUtil.js'; //百度工具类
	import { formatTime } from '../../utils/util'
	import { shipmentLocation, ordermovementOM, ordermovementOR, ordermovementMASS } from '../../api/apiList'
	import { loadTypes, unloadTypes} from '../../enum/enum'
	const getUserLocation = require('../../mixins/getUserLocation')
	const appInstance = getApp()
	export default {
		name: "stopsDetail",
		mixins: [getUserLocation],
		options: { styleIsolation: 'shared' },
		data() {
			return {
				loadModel: '已配载', //配载模式： 已配载、未配载
				stopsdatas: [], // 站点信息

				activeNames: [], //当前展开面板 names => shipmentLocationId
				currentName: "", //当前所点击面板 name
				optionEnums: [], //装、卸货选项枚举
				currentLocationInfo: '', //当前选中站点信息,声明为空字符串以避免联系人字段为空时，VUE更新错误
				orderRemarks: [], //订单备注，提货、配送要求

				phoneListVisible: false, // 联系人列表显隐
				remarkVisible: false, //提货要求显隐明细
				visible: false, //装卸货选择poup显隐
			};
		},
		props: {
			propData: { //站点信息
				type: String,
				default: ""
			},
			shipmentStatus: {
				type: String,
				default: '' //运单状态
			},
			orderSplitMode: {
				type: String,
				default: '' //大宗拆量方式
			}
		},
		watch: {
			propData: {
				handler(newValue) {
					this.stopsdatas = JSON.parse(newValue);
					this.$nextTick(() => {
						this.$refs.myCollapse.resize()
					})
				}
			}
		},
		methods: {
			onTouchMove(){
				//防止滚动穿透
			},
			// 折叠面板 
			onChange(values) {
				this.activeNames = values
			},
			//监听面板点击事件
			onClickPanel(e) {
				const data = e.currentTarget.dataset.info
				this.currentName = data.id				
				this.onSetGlobalData(data)											
				this.currentLocationInfo = data
			},
			//设置全局变量stopsInfo
			onSetGlobalData(data) {
				appInstance.globalData.stopsInfo = {
					locationId: data['location.id'],
					locationName: data['location.name'], //站点名称
					locationAddress: this.getLocationCity(data), //站点地址 
					loadStop: data.loadStop, //是否装货站点
					unloadStop: data.unloadStop, //是否卸货站点
					netWeight: data.netWeight, //过磅净重
					locationOrders: data.loadOrders || data.unloadOrders, //订单数
					locationQty: data.planLoadQty || data.planUnloadQty, //件数数
					locationWeight: data.planLoadWeight || data.planUnloadWeight, //重量
					locationVolume: data.planLoadVolume || data.planUnloadVolume, //体积
				}
			},
			//到站、离站
			onActionStops(e) {				
				const action = e.target.dataset.action
				this.action = action
				this.getUserSetting()
			},
			//获取当前位置
			getSiteName() {
				const _this = this
				const { serviceProvider } = getApp().globalData
				const newMapUtil = serviceProvider === 'AMap' ? AMap : BMap
				newMapUtil.reverseGeocoder().then(res => {
					const address = res.textData.desc
					const time = formatTime(new Date())
					const info = { ...res, address, time }
					getApp().globalData.userLocation = info;
					_this.locationInfo = info
					if(_this.action){
						_this.onArrivalDeparture(info)
					}
				}).catch(err => {
					uni.showToast({
						title: err,
						icon: 'none',
						duration: 3000
					});
				})
			},
			// 到站经纬度校验
			siteVerify(info){			
				let lo1 = info.longitude
				let	la1 = info.latitude
				let	lo2 = this.currentLocationInfo['location.longitude']
				let	la2 = this.currentLocationInfo['location.latitude']
				let	fenceRadius = this.currentLocationInfo['location.appFenceRadius']
				let	distance = this.distance(la1, lo1, la2, lo2)
				if (fenceRadius > 0) {
					if (+distance > fenceRadius) {
						uni.showToast({
							title: '当前位置与签到位置偏差过大!',
							icon: 'none',
							duration: 3000
						})
						return false
					}else{
						return true
					}
				}else{
					return true
				}					
			},
			// 计算两点之间距离
			distance(la1, lo1, la2, lo2) {
				let La1 = la1 * Math.PI / 180.0;
				let La2 = la2 * Math.PI / 180.0;
				let La3 = La1 - La2;
				let Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
				s = s * 6378.137;
				s = Math.round(s * 10000) / 10000;
				s = s.toFixed(2);
				return s;
			},
			//到站离站
			onArrivalDeparture(info) {
				const action = this.action
				if(action === 'arrival'){ //到站操作校验经纬度
					if(!this.siteVerify(info)) return
				}
				const { longitude, latitude, address, time } = info
				const reqData = {
					"aux": { longitude, latitude, address, time, eventSource: 'DriverApp' },
					"args": {
						"selectedIds": [this.currentName]
					}
				}
				shipmentLocation(action, reqData).then(res => {
					if (res.data.messageType === 'success') {
						uni.showToast({
							title: '操作成功',
							duration: 1500
						})
						setTimeout(() => {
							this.$emit("onRefresh")
						}, 1500)
					}
				})
			},
			// 装卸货类型选择
			onVisible(e) {
				if (this.visible) { //关闭
					this.visible = false
				} else { //打开时清空选择
					const action = e.target.dataset.action
					const mySelectPop = this.$refs.mySelectPop //获取弹窗实例
					if (mySelectPop) {
						mySelectPop.setSelect('')
					}
					const isLoad = action === 'loadStop' //判断是否为装货
					let optionEnums = isLoad ? loadTypes.filter(item => item.value !== 'loadQty') : unloadTypes.filter(item => item.value !== 'unloadQty') //清除缓存
					const isMassLoad = getApp().globalData.shipmentInfo.shipmentBizName === 'tm.MassShipment' //判断是否为大宗模式 				
					let newType = null	
					if(isMassLoad){ //大宗模式按数量装卸
					  if(this.orderSplitMode !== 'Weight'){ //订单拆分模式为重量时不显示
						newType = isLoad ? {value: 'loadQty',label: '数量装货'} : {value: 'unloadQty',label: '数量卸货'}   
					  }						
					} else{
						if (this.loadModel === '已配载') {
							newType = isLoad ? {value: 'scanOrderLoad',label: '扫码装货'} : {value: 'scanOrderUnload',label: '扫码卸货'}
						} else {						
							newType = isLoad ? {value: 'scanOrderShipLoad',label: '扫码装货'} : {value: 'scanOrderShipUnload',label: '扫码卸货'}
						}	
					}
					if(newType && !optionEnums.find(item => item.value === newType.value)){
						optionEnums.splice(2,0, newType) //数组方法：指定位置添加某个元素	
					}			
					this.optionEnums = optionEnums
					this.visible = true
				}
			},
			//确认选择
			onConfirmSelect(action) {
				if (!action) {
					uni.showToast({
						title: '请选择类型',
						icon: 'none',
						duration: 1000
					})
					return
				}
				this.visible = false
				const data = { action, selectedId: this.currentName }
				uni.navigateTo({
					url: `/subpkg/loadDischarg/loadDischarg?data=${JSON.stringify(data)}`,
				})
			},
			//拨打电话
			onMakePhoneCall() {
				const phone = this.currentLocationInfo['location.addressContact.tel']
				uni.makePhoneCall({
					phoneNumber: String(phone) //号码仅支持字符串
				});
			},
			//导航并显示内置地图
			onNavigation(e) {
				const addressInfo = e.target.dataset.address
				const province = addressInfo['location.province']
				const city = addressInfo['location.city']
				const district = addressInfo['location.district']
				const detail = addressInfo['location.detail'] || ''
				const latitude = addressInfo['location.latitude']
				const longitude = addressInfo['location.longitude']
				const address = (province !== city ? province : '') + city?city:"" + district?district:"" + detail?detail:""				
				if (!address) {
					uni.showToast({
						title: '详细地址为空，无法导航',
						icon: 'none',
						duration: 3000
					})
					return
				}
				// #ifdef H5
				const isWxBrowser = getApp().isWxBrowser()
				if(isWxBrowser){
					if (this.$jwx) {
						this.$jwx.openLocation({
							latitude,
							longitude,
							scale: 18,
							name: detail || address, //要导航的位置名称,H5可正常打开地图
							address
						})
					}
				} else {
					uni.openLocation({ //打开微信内置地图
						latitude,
						longitude,
						scale: 18,
						name: detail || address, //要导航的位置名称
						address
					})
				}
				// #endif
				
				// #ifdef MP
				uni.openLocation({ //打开微信内置地图
					latitude,
					longitude,
					scale: 18,
					name: detail || address, //要导航的位置名称
					address
				})
				// #endif				
			},

			//联系人列表
			onVisiblePhoneList() {
				this.phoneListVisible = !this.phoneListVisible
			},
			//备注明细
			onVisibleRemark() {
				const { remarkVisible, orderRemarks } = this
				if (!remarkVisible && !orderRemarks.length) { //防止重复请求
					this.getOrderRemark()
				}
				this.remarkVisible = !this.remarkVisible
			},
			//获取订单备注
			getOrderRemark() {
				const { shipmentId, shipmentBizName } = appInstance.globalData.shipmentInfo
				let shipmentMode = ''
				switch (shipmentBizName) { //根据shipmentBizName 判断运输模式
					case 'tm.MovementShipment':
					case 'tm.SectionShipment': //暂时走OM逻辑
						shipmentMode = 'OM'
						break
					case 'tm.MassShipment':
						shipmentMode = 'MS'; //大宗运输
						break
					default:
						shipmentMode = 'OR';
				}
				
				if(shipmentMode === 'MS'){
					const reqData = { "aux": { "id": shipmentId } }
					ordermovementMASS(reqData).then(res => {
						const data = res.data.data.header
						const newRemark = {
							'id': data['massOrder.id'], //订单id
							'orderNo': data['massOrder.orderNo'], //订单号
							'originalRequirement': data['massOrder.originalRequirement'], //提货要求
							'destinationRequirement': data['massOrder.destinationRequirement'], //配送要求
						}
						this.orderRemarks = this.orderRemarks.concat(newRemark)
					})
				} else {
					const reqData = {
						"args": {
							"pageNum": 1,
							"pageSize": 100,
							"restrictions": [{
								"field": "shipment.id",
								"type": "EQ",
								"value": shipmentId
							}]
						}
					}
					const requestFun = shipmentMode === 'OM' ? ordermovementOM : ordermovementOR
					requestFun(reqData).then(res => {
						const datas = res.data.data.datas
						let newDatas = []
						if (shipmentMode === 'OM') { //OM模式时自定义数据字段名,默认使用简易的OR模式字段名
							datas.map(item => {
								newDatas.push({
									'id': item.id, //订单id
									'orderNo': item.movementNo, //订单号
									'originalRequirement': item['orderRelease.originalRequirement'], //提货要求
									'destinationRequirement': item['orderRelease.destinationRequirement'], //配送要求
								})
							})
						} else {
							newDatas = [...datas]
						}
						this.orderRemarks = [...newDatas]
					})
				}								
			},
			// 路由跳转
			onNavigatePage(e) {
				const { action, path } = e.target.dataset
				const data = {
					action,
					selectedId: this.currentName,
					currentLocationInfo: this.currentLocationInfo
				}
				uni.navigateTo({
					url: path + `?data=${JSON.stringify(data)}`,
				})
			},
		}
	}
</script>

<style lang="scss">
	.stopsDetail {

		.uni-collapse {
			background-color: #FAFAFA;
		}

		/deep/.uicon-close {
			margin-right: 20rpx;
			font-size: 40rpx !important;
			width: 24rpx;
			height: 24rpx;
		}

		.outer-frame {
			margin-top: 28rpx;

			.loadStop-station-title,
			.unloadStop-station-title {
				font-size: 34rpx;
				font-weight: bolder;
				background-color: #FFFFFF;
				padding-right: 30rpx;

				.station-state {
					color: #FFFFFF;
					font-size: 32rpx;
					font-weight: 500;
					margin: 24rpx 24rpx 24rpx 0;
					padding: 16rpx 20rpx;
					text-align: center;
					border-radius: 0 50% 50% 0;
					background: #2E75E6;
				}

				.panel-title-rightIcon {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.unloadStop-station-title {
				.station-state {
					background: #F7A64A;
				}
			}

			/deep/.station-content {
				border-top: 2rpx solid #E5E5E5;
				padding: 32rpx;
				.u-cell__body{
					font-size: 28rpx;
				}
				.row-rightIcon {
					width: 44rpx;
					height: 44rpx;
				}
				
				.cell-leftIcon{
					width: 32rpx !important;
					height: 32rpx !important;
				}

				.cargoQty-item {
					margin-right: 20rpx;
				}

				.uicon-arrow-right {
					margin-left: 40rpx;
				}

				.customRow-title {
					margin-left: 10rpx;
				}

				.custom-cell-row {
					margin: 32rpx 0;
					font-size: 28rpx;
					color: #8C8C8C;
				}
			}
		}

		.contactList {
			align-items: center;
			padding: 24rpx 0;

			.phoneItem {
				margin: 10rpx;
			}
		}

		.remarks-container {
			font-weight: 400;
			width: 95%;
			height: 70vh;
			padding: 30rpx 20rpx 20rpx;

			.remarks-title {
				color: #8C8C8C;
				text-align: center;
				margin-bottom: 50rpx;
			}

			.remark-item {
				font-size: 28rpx;
				margin: 10rpx 0;
				padding: 16rpx;

				.remark-orderNo {
					display: inline-block;
					margin-left: 20rpx;
					color: #8C8C8C;
				}

				.remark-detail {
					margin: 10rpx 0 0 50rpx;
				}
			}
		}
		.operation-btns{
			.common_btn{
				background: transparent;
				width: 338rpx;
				height: 80rpx;
				&[disabled]{
					border-color: #BFBFBF;
					color: #BFBFBF;
					background-color: #F0F0F0;
				}
			}
			
		}
		.transport_info{
			/deep/ .u-col{
				flex: none !important;
				width: auto;
				margin-right: 32rpx;
			}
		}
	}
</style>
