<template>
	<scroll-view class="shipmentDetail content_box">
		<shipmentCard :propData="JSON.stringify(data)" @getCurrentLocation="getCurrentLocation" />
		<template v-if="data.shipmentStatus!=='Approved' && data.shipmentStatus!=='Dispatch'">
			<view class="operation-btns">
				<button class="common_btn" @click="onNavSign" v-if="data.shipmentStatus==='Shipping'">上报</button>
				<button :class="['common_btn', {'btn-active': data.shipmentStatus==='Finished'}]" @click="onNavReport">
					费用上报
				</button>
				<!-- 运输中显示 -->
				<template v-if="data.shipmentStatus==='Shipping'">
					<button class="common_btn" @click="onNavPage" data-path="/subpkg/transferChange/transferChange"
						data-action="transferAndChangeTruck">中转换车</button>
					<button class="common_btn" @click="onNavPage" data-path="/subpkg/transferChange/transferChange"
						data-action="transferAndUnload">中转卸货</button>
				</template>
			</view>
		</template>
		<view class="flex_sb" style="margin: 28rpx 30rpx 0 0">
			<view></view>
			<view class="flex_center" @click="onNavShipmentLbs" data-path="/subpkg/shipmentLbs/shipmentLbs">
				<view class="t-icon t-icon-view-track"></view>
				<text style="margin-left: 10rpx; color: #434343; font-weight: 400;">查看轨迹</text>
			</view>
		</view>
		<stopsDetail ref="ownerStops" :propData="JSON.stringify(stopsDatas)" :shipmentStatus="data.shipmentStatus"
			:orderSplitMode='data.splitMode' @onRefresh="onRefresh" />
		<button class="common_btn historyBtn" @click="onNavHistory">操作历史</button>
	</scroll-view>
</template>

<script>
	import { shipmentOrderDetail, shipmentStationDetail, shipmentOrderDetailMass } from '../../api/apiList'
	import { formatGMT } from '../../utils/util'
	import { TokenPrefix } from '../../publicConfig/config.js'
	const appInstance = getApp()
	export default {
		options: {
			styleIsolation: 'shared'
		},
		data() {
			return {
				
				data: {}, //运单简要信息
				stopsDatas: [], //站点信息
				orderId: '', //订单id
			}
		},
		onLoad: function(options) {
			const data = JSON.parse(options.shipmentgroup)
			this.data = data
		},
		onShow: function() {
			let XSRFToken = uni.getStorageSync(`${TokenPrefix}_XSRFToken`)
			if (XSRFToken) {
				this.onRefresh()
			}
		},
		methods: {
			//初始化数据
			initData2() {
				const data = {
					"aux": {
						"id": this.orderId
					}
				}
				const { shipmentBizName } = appInstance.globalData.shipmentInfo
				const requestFun = shipmentBizName === 'tm.MassShipment' ? shipmentOrderDetailMass : shipmentOrderDetail
				requestFun(data).then(res => {
					const data = res.data.data.header
					data.shipmentDate = formatGMT(data.shipmentDate, 'D') //格式化时间
					data.finishTime = formatGMT(data.finishTime) //格式化时间
					data.splitMode = shipmentBizName === 'tm.MassShipment' ? data['splitMode'] : '' //大宗拆量方式
					appInstance.globalData.shipmentInfo = { //设置全局变量
						...appInstance.globalData.shipmentInfo,
						shipmentNo: data.shipmentNo,
						shipmentId: data.id,
						truckName: data['truck.name']
					}
					this.data = data
				})
			},
			//初始化站点信息
			initStationDetail() {
				const data = {
					"args": {
						"pageNum": 1,
						"pageSize": 100,
						"restrictions": [{
							"field": "shipment.id",
							"type": "EQ",
							"value": this.orderId
						}]
					}
				}
				shipmentStationDetail(data).then(res => {
					let stopsDatas = res.data.data.datas
					stopsDatas.sort((a, b) => (a.stopNumber - b.stopNumber || b.loadStop - a.loadStop)) //站点排序
					stopsDatas.map(stop => { //格式化站点信息中时间
						stop.actualArrivalTime = formatGMT(stop.actualArrivalTime)
						stop.actualDepartureTime = formatGMT(stop.actualDepartureTime)
						stop.loadStartTime = formatGMT(stop.loadStartTime)
						stop.loadFinishTime = formatGMT(stop.loadFinishTime)
						stop.unloadStartTime = formatGMT(stop.unloadStartTime)
						stop.unloadFinishTime = formatGMT(stop.unloadFinishTime)
						stop.receiveTime = formatGMT(stop.receiveTime)
						stop.signatureTime = formatGMT(stop.signatureTime)
						stop.weightTime = formatGMT(stop.weightTime)
					})
					this.stopsDatas = stopsDatas
				})
			},
			//站点操作后页面刷新
			onRefresh() {
				this.initData()
				// this.initStationDetail()
			},
			//跳转异常上报
			onNavSign() {
				const orderId = this.orderId
				uni.navigateTo({
					url: `/subpkg/reportSign/reportSign?selectedId=${orderId}`,
				})
			},
			//跳转费用上报
			onNavReport() {
				uni.navigateTo({
					url: `/subpkg/reportCost/reportCost?data=${JSON.stringify(this.data)}`,
				})
			},
			//跳转中转换车、中转卸货
			onNavPage(e) {
				const {
					path,
					action
				} = e.target.dataset
				const data = {
					selectedId: this.data.id,
					action
				}
				uni.navigateTo({
					url: path + `?data=${JSON.stringify(data)}`,
				})
			},
			//查询操作历史
			onNavHistory() {
				uni.navigateTo({
					url: `/subpkg/queryHistory/queryHistory?id=${this.data.id}`,
				})
			},
			//校验当前位置与站点距离, 自动展开较近站点详情
			getCurrentLocation(addresInfo) {
				const _this = this
				const {
					latitude,
					longitude
				} = addresInfo
				const stopsDatas = this.stopsDatas
				if (stopsDatas.length) {
					let distances = []
					const stopsInstance = this.$refs.ownerStops
					stopsDatas.map(stop => {
						const locationLatitude = stop['location.latitude']
						const locationLongitude = stop['location.longitude']
						if (locationLatitude && locationLongitude) {
							const distance = _this.distance(latitude, longitude, locationLatitude,
								locationLongitude)
							distances.push({
								id: stop.id,								
								distance,
								locationId: stop['location.id']
							})
						}
					})
					if (distances.length) {
						distances = distances.sort((a, b) => (a.distance - b.distance)) //站点距离排序 由近到远
						stopsInstance.activeNames = [distances[0].id]
						appInstance.globalData.stopsInfo.locationId = [distances[0].locationId] //设置全局变量，避免自动展开面板后查询不到站点关联订单
						// stopsInstance.currentName = distances[0].id

					} else {
						stopsInstance.activeNames = [stopsDatas[0].id]
						appInstance.globalData.stopsInfo.locationId = [stopsDatas[0][location.id]]
						// stopsInstance.currentName = stopsDatas[0].id
					}
				}
			},

			// 计算两点之间距离
			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;
			},
			
			//跳转运单Lbs
			onNavShipmentLbs(e) {		
				const {id, shipmentNo} = this.data
				const data = {shipmentId: id, shipmentNo}
				const path = e.currentTarget.dataset.path + `?data=${JSON.stringify(data)}`
				uni.navigateTo({
					url: path,
				})
			},
		}
	}
</script>

<style lang="scss">
	.shipmentDetail {
		background: #FAFAFA;

		.operation-btns {
			margin-top: 24rpx;
			padding-bottom: 24rpx;
			display: flex;
			flex-wrap: wrap;

			.btn-active {
				width: 90%;
				border: none;
				color: #2E75E6;
				background-color: #EAF1FC;
			}
		}

		.historyBtn {
			width: 90%;
			border: none;
			margin: 30rpx auto;
			background: #EAF1FC;
		}
	}
</style>
