<template>
  <view class="page">
    <u-navbar class="u-navbar" title="作业点申请" placeholder @leftClick="leftClick" leftIconColor="#fff"  bgColor="#00337A"  :titleStyle="{ color: '#FFF', fontSize: '32rpx' }"></u-navbar>
	<view class="tab-box">
		<view class="tab-item" :class="currentTabIndex == 0 ? 'active' : ''" @click="currentTabIndex = 0">
			申请
			<view class="activeLine" v-if="currentTabIndex == 0"></view>
		</view>
		<view class="tab-item" :class="currentTabIndex == 1 ? 'active' : ''" @click="currentTabIndex = 1">
			申请记录
			<view class="activeLine" v-if="currentTabIndex == 1"></view>
		</view>
	</view> 
		<scroll-view class="content" scroll-y="true">
			<view class="view-box" v-show="currentTabIndex == 0">
				<u--form class="form-box" :model="formData" ref="cForm">
					<view class="form-input-box">
						<view style="width:20%;height: 100%;">
							<text>作业点名称:</text>
						</view>
						<u-form-item prop='workSceneName' style="width:50%;height: 100%;" >
							<u--input v-model="formData.workSceneName" type="text" placeholder="请输入打卡点名称" maxlength="20"  border="surround" clearable></u--input>
						</u-form-item>
						<view class="submitBtn" @click="uploadWorkSceneApply">提交</view>
					</view>
					<view class="form-input-box">
						<view style="width:10%;height: 100%;">
							<text>经度:</text>
						</view>
						<u-form-item style="width:35%;height: 100%;" >
							<u--input v-model="longitude" type="text" maxlength="12"  border="surround" clearable readonly></u--input>
						</u-form-item>
						<view style="width:10%;height: 100%;">
							<text>维度:</text>
						</view>
						<u-form-item style="width:35%;height: 100%;" >
							<u--input v-model="latitude" type="text" maxlength="12"  border="surround" clearable readonly></u--input>
						</u-form-item>
					</view>
				</u--form>
				
				<view class="map-box" > 
					<view class="map" :data="workData" :change:data="allmap.getResData" style="width: 100%;height: 100%;" id="container"></view>
				</view>
			</view>
			<view class="view-box list-box" v-show="currentTabIndex == 1">
				<u-list height="75vh">
						<u-list-item  v-for="(item, index) in listData" :key="index">
							<view class="list-item" >
								<view class="content-box">
									<view class="item-text" >
										<text class="label" style="font-weight: bold;">打卡点名称：</text>
										<text class="info">{{item.workSceneName}}</text>
									</view>
									<view class="item-text">
										<text class="label" style="font-weight: bold;">审核结果：</text>
										<text class="info" v-if="item.examineStatus==0" style="color: #E18415;">待审核</text>
										<text class="info" v-if="item.examineStatus==1" style="color: #06E7A3;;">已通过</text>
										<text class="info" v-if="item.examineStatus==2" style="color: red;">未通过</text>
									</view>
									<view class="item-text" @click="goDetail(item)">
										<text class="label" style="font-weight: bold;">地图查看：</text>
										<text class="info" style="color: #5097EF;">查看</text>
									</view>
								</view>
							</view>
						</u-list-item>
					</u-list>
			</view>
		</scroll-view>
 
  </view>
</template>

<script>
import { pathToBase64, base64ToPath } from 'image-tools';
import config from '@/config'
export default {
	data() {
		return {
			workData:{},
			currentTabIndex:0, 
			teamId:uni.getStorageSync('realNameUser').teamId,
			userId:uni.getStorageSync('realNameUser').userId ,
			longitude:117.150204,
			latitude:31.877608,
			formData:{workSceneName:""},
			listData:[],
		}
	},
	onLoad(option) {
		setTimeout(()=>{
			this.workData=JSON.parse(option.workData)
			this.longitude = this.workData.longitude;
			this.latitude = this.workData.latitude;
		},2000)
	},
	onShow() {
		
	},
	watch: {
		currentTabIndex: function(newVal, oldVal) {
			if (newVal == 1) {
				this.selectWorkSceneApply()
			} else {
				
			}
		}
	},
	methods: {
		selectWorkSceneApply(){
			let param={
				userId:uni.getStorageSync('realNameUser').userId
			}
			uni.request({
				url: config.realAppUrl+'/BasePerson/selectWorkSceneApply',
				method: 'post',
				data: param,
				header: {
					'Content-Type': 'application/json',
					Authorization: uni.getStorageSync('realNameToken')	
				},
				success: res => {
				console.log(res)
					res = res.data;
					if(res.code==200){
						this.listData=res.data;
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				},
				fail: err => {
					console.log(err)
				}
			}) 
		},
		goDetail(item){
			let arr=[{
				lon:item.lon,
				lat:item.lat,
				rangeName:item.workSceneName
			}];
			uni.navigateTo({ 
				url: `/pages/realName/workAttendance/clock/checkMap?teamList=${JSON.stringify(arr)}` 
			})
		},
		//给renderJS调用的方法
		methodForRenderJs:function(val){
			console.log("收到参数：");
			this.longitude = val.longitude;
			this.latitude = val.latitude;
		},
		// 申请打卡点
		uploadWorkSceneApply(){ 
			if(this.formData.workSceneName==""){
				uni.$u.toast('请填写作业点名称！');
			}else{
				let param={
					workSceneName:this.formData.workSceneName,
					lon:this.longitude, //经度
					lat:this.latitude, //维度
					userId:this.userId, //用户编号
					uploadTime:this.timeFormat(null,'yyyy-mm-dd hh:MM:ss'), //自动生成yyyy-mm-dd hh:mm:ss
					teamId:this.teamId //用户信息中的班组编号
				}
				console.log(param)
				uni.request({
				  url: config.realAppUrl + '/BasePerson/uploadWorkSceneApply',
				  method: 'post',
				  data: param,
				  header: {
					'Content-Type': 'application/json',
					Authorization: uni.getStorageSync('realNameToken')
				  },
				  success: res => {
					console.log(res) 
					res = res.data;
					if(res.code==200){
						uni.$u.toast('申请已提交！');
					}else{
						uni.$u.toast(res.msg);
					}
				  },
				  fail: err => {
					uni.$u.toast('申请失败！');
					console.log(err)
				  }
				})
			}
		
		},
		
		leftClick() {
			console.log('返回')
			uni.navigateBack({
				delta: 1 // 返回
			});
		},
		timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
			let date
			// 若传入时间为假值，则取当前时间
			if (!dateTime) {
				date = new Date()
			}
			// 若为unix秒时间戳，则转为毫秒时间戳（逻辑有点奇怪，但不敢改，以保证历史兼容）
			else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
				date = new Date(dateTime * 1000)
			}
			// 若用户传入字符串格式时间戳，new Date无法解析，需做兼容
			else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
				date = new Date(Number(dateTime))
			}
			// 处理平台性差异，在Safari/Webkit中，new Date仅支持/作为分割符的字符串时间
			// 处理 '2022-07-10 01:02:03'，跳过 '2022-07-10T01:02:03'
			else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
				date = new Date(dateTime.replace(/-/g, '/'))
			}
			// 其他都认为符合 RFC 2822 规范
			else {
				date = new Date(dateTime)
			}
		
			const timeSource = {
				'y': date.getFullYear().toString(), // 年
				'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
				'd': date.getDate().toString().padStart(2, '0'), // 日
				'h': date.getHours().toString().padStart(2, '0'), // 时
				'M': date.getMinutes().toString().padStart(2, '0'), // 分
				's': date.getSeconds().toString().padStart(2, '0') // 秒
				// 有其他格式化字符需求可以继续添加，必须转化成字符串
			}
		
			for (const key in timeSource) {
				const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
				if (ret) {
					// 年可能只需展示两位
					const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
					formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
				}
			}
			return formatStr
		},
	},
}
</script>

<script module="allmap" lang="renderjs">
	import { myBMapGL1 } from "../../util/map.js"; 
	import no_warn from "../../../../static/realName/coor.png";
	var bmap;
	export default {
			data() {
				return {
					latitude: 31.877608,
					longitude: 117.150204,
				}
			},
			mounted() {
				this.initMap()
			},
			beforeDestroy() {
				bmap && bmap.destroy();
				bmap = null
			},
			methods: {
				//获取地图信息
				initMap() {
					myBMapGL1().then((res) => {
						// 创建地图实例
						bmap = new BMapGL.Map("container");
						bmap.centerAndZoom(new BMapGL.Point(this.longitude, this.latitude), 12); 
						// 监听地图点击事件
						bmap.addEventListener('click', this.handleMapClick);
						// 这里边写加载完成之后的执行操作
						bmap.enableScrollWheelZoom(true);
					})
				}, 
				getResData(newValue, oldValue, ownerVm, vm) {
					console.log(newValue,"newList---------")
						const lon = Number(newValue.longitude);
						const lat = Number(newValue.latitude);
						bmap.centerAndZoom(new BMapGL.Point(lon, lat), 12);
						bmap.clearOverlays();
						// 中心点
						let point = new BMapGL.Point(lon,lat)
						let marker = "", myIcon = "";
						myIcon = new BMapGL.Icon(no_warn, new BMapGL.Size(20,20))
						myIcon.setImageSize(new BMapGL.Size(20, 20));
						marker = new BMapGL.Marker(point, { icon: myIcon });
						marker.id = "center";
						bmap.addOverlay(marker);
						let circle = new BMapGL.Circle(point, 6000, {
							strokeColor: "#06E7A3",
							strokeWeight: 2,
							strokeOpacity: 1,
							fillOpacity: 0.1,
							zIndex: 999
						});
						circle.id = "circle";
						bmap.addOverlay(circle); 
					 
				},
				handleMapClick(e) {
				   console.log(e);
				   console.log(e.latlng);
				   this.$ownerInstance.callMethod('methodForRenderJs',{longitude:e.latlng.lng,latitude:e.latlng.lat});
				   bmap.clearOverlays();
				   let lon = e.latlng.lng;
				   let lat = e.latlng.lat; 
				   let point = new BMapGL.Point(lon,lat)
				   let marker = "", myIcon = "";
				   myIcon = new BMapGL.Icon(no_warn, new BMapGL.Size(20,20))
				   myIcon.setImageSize(new BMapGL.Size(20, 20));
				   marker = new BMapGL.Marker(point, { icon: myIcon });
				   marker.id = "center";
				   bmap.addOverlay(marker);
				   let circle = new BMapGL.Circle(point, 6000, {
				   	strokeColor: "#06E7A3",
				   	strokeWeight: 2,
				   	strokeOpacity: 1,
				   	fillOpacity: 0.1,
				   	zIndex: 999
				   });
				   circle.id = "circle";
				   bmap.addOverlay(circle); 
				},
			},
			beforeDestroy() {
				// 清理监听器
				const map = this.$refs.bmap;
				if (map) {
				  bmap.removeEventListener('click', this.handleMapClick);
				}
			}
		}
</script>

<style lang="scss">
  
.page {
	width: 100vw;
	height: 100vh;
	background-color: #EFEFEF;
	box-sizing: border-box;
	.tab-box {
		width: 100%;
		margin: 20rpx auto;
		display: flex;
		justify-content: space-between;
		.tab-item {
			height: 70upx;
			width: 45%;
			font-size: 30upx;
			text-align: center;
			line-height: 70upx;
			color: #666;
		}
		.active {
			color: #00337A;
			border-radius: 10upx 10upx 0 0;
			font-weight: bold;	
		}
		.activeLine{
			background: #00337A;
			border-radius: 10upx;
			width: 100%;
			height: 6upx;
		}
	}
	.submitBtn{
		width: 15%;
		height: 60rpx;
		line-height: 60rpx;
		border-radius: 10rpx;
		background: #00337A;
		color: #FFF;
		padding: 10rpx 16rpx;
		text-align: center;
	}
	.content{
		width: 100%;
		height: 84vh;
		margin-top: 20rpx;
		// padding-bottom: 80rpx;
		background-color: #EFEFEF;
	}
	// padding: 0 20px;
	.map-box{
		width: 100%;
		height: 68vh;
		z-index: 9;
		position: absolute;
		bottom:1vh;
		background: #fff;
		.map{
			display: inline-block;
			width: 100%;
			height: 100%;
		}
	}
	
	.view-box{
		width: 100%;
		height: auto;
		margin: 0rpx auto;
		border-radius: 10rpx;
		padding-top: 20rpx;
		// background-color: red;
		
		.title-view{
			font-weight: 600;
			margin-left: 20rpx;
			border-bottom: 1rpx solid #EFEFEF;
		}
		.form-box{
			width: 100%;
			height: auto;
			font-size: 26rpx;
			.form-input-box{
				padding: 0 10rpx;
				display: flex;
				align-items: center;
				justify-content: space-between; 
			}
		}
		.view-item{
			width: 94%;
			margin: 0rpx auto;
			padding:10rpx;
			display: flex;
			border-bottom: 1rpx solid #EFEFEF;
			font-size: 26rpx;
			.label{
				width: 160rpx;
				color: #666;
				margin-bottom: 10rpx;
			}
			.img-box{
				width: 94%;
				height: auto;
				margin: 0rpx auto;
				padding:10rpx;
				display: flex;
				border-bottom: 1rpx solid #EFEFEF;
				.img-item {
					float: left;
					width: 200upx;
					height: 200upx;
					border: 1px solid #ddd;
					margin: 0 22rpx 20upx 0upx;
					position: relative;
					box-sizing: border-box;
					background: #eee;
					.img {
						display: block;
						width: 100%;
						height: 100%;
					}
					.remove-btn {
						position: absolute;
						top: -18upx;
						right: -18upx;
						width: 44upx;
						height: 44upx;
						z-index: 2;
					}
				}
				.upload-btn {
							display: flex;
							justify-content: center;
							align-items: center;
						.img {
							width: 60upx;
							height: 60upx;
							margin: unset;
						}
				}
			}
		}
	
	
		.sumbit-btn{
			width: 94%;
			height: 80rpx;
			margin: 0 auto;
			margin-bottom: 100rpx;
			display: flex;align-items: center;justify-content: center;
			background: #00337A;
			color: #FFF;
			border-radius: 10rpx;
		}
	}
	
	.list-box{
		width: 90%;
		height: auto;
		// border: 1px solid #000;
		margin: 0rpx auto;
		
		.list-item{
			width: 100%;
			height: auto;
			background-color: #fff;
			border-radius: 20rpx;
			margin: 20rpx 0;
			
			.content-box{
				width: 94%;
				height: auto;
				margin: 20rpx;
				// background-color: #F8F9FC;
				padding: 10rpx 0;
				
				.item-text{
					width: 95%;
					margin-left: 20rpx;
					margin-top: 15rpx;
					// display: flex;
					align-items: center;
					position: relative;
					.label{
						color: #3A3A3A;
						font-weight: 500;
					}
					.info-right{
						position: absolute;
						top: 0rpx;
						right: 40rpx;
					}
					.info{
						color: #6F6F6F;
					
					}
				}
			}
		}
	}
 

}
</style>
