<template>
	<view class="">
		<view class="" v-if="!loading">
			<view class="" v-if="isWork">
				<view class="top"></view>
				<view class="" style="margin-top: -440rpx;">
					<view @click="jump('/punch/pages/rule/rule')" class="person ">
						<view class="flex">
							<view class="tag" v-if="vuex_userInfo.realName">
								<text>{{vuex_userInfo.realName.substr(0,1)}}</text>
							</view>
							<view class="content">
								<view class="name">
									{{vuex_userInfo.realName}}
								</view>
								<view class="company">
									{{vuex_userInfo.enterpriseName}}
								</view>
							</view>
						</view>
						<view  @click.stop="jump('/punch/pages/punch-list/punch-list')" class="date">
							<text>{{date}}</text>
							<text class="cuIcon-unfold padding-left-10"></text>
						</view>
					</view>
			
					<view class="page-content">
						<view class="" v-if="!necessaryData.isDone">
							<view class="location" style="padding-top: 60rpx;">
								<view class="text-lg">
									<u-icon name="map-fill" color="#5064eb;"></u-icon>
									<text class="">当前位置</text>
									<text style="color:  #12914f;" v-if="necessaryData.isInPunchLocation">（已进入打卡范围内）</text>
									<text class="text-fail" v-else>（不在打卡范围内）</text>
									<text v-if="!necessaryData.isInPunchLocation" @click="getCoordinates"
										class="reset-location" style="color: #5064eb;">重新定位</text>
								</view>
								<view style="padding-top: 20rpx;font-size: 28rpx;">
									<text class="padding-left-10">{{cur_address}}</text>
								</view>
							</view>
							<view @click="punch" class="btn-position">
								<view class="dk-btn ">
									<text>{{time}}</text>
									<text v-if="necessaryData.workStatus==0">上班打卡</text>
									<text v-if="necessaryData.workStatus==1">下班打卡</text>
								</view>
							</view>
							<view class="text-center margin-top-50" v-if="needWifi">
								<text v-if="necessaryData.isInPunchWifi">已进入WiFi考勤区域：{{cur_wifi}}</text>
								<text v-else class="text-lg">不在wifi考勤区域内</text>
							</view>
						</view>
						<view class="result" v-else>
							<image src="/punch/static/icon/success.png" mode=""></image>
							<text class="tips">打卡成功</text>
						</view>
			
						<view class="margin-50 " style="padding-top: 60rpx;">
							<u-time-line>
								<u-time-line-item nodeTop="2">
									<template v-slot:node>
										<view class="u-node bg-white">
											<text class="cuIcon-title"
												:class="$isEmpty(necessaryData.workPunchRecords)?'':'base-color'"
												style="font-size: 40rpx;"></text>
										</view>
									</template>
									<template v-slot:content>
										<view class="dk-time-line">
											<view class="dk-title">
												<text>上班打卡</text>
												<text v-if="necessaryData.workPunchRecords[0]" class="text-fail"
													style="font-weight: 500;">（{{necessaryData.workPunchRecords[0].exceptionMessage}}）</text>
												<text v-if="!necessaryData.workPunchRecords[0]&&necessaryData.workStatus==1"
													class="text-fail" style="font-weight: 500;">（未打卡）</text>
											</view>
											<view class="dk-subTitle">
												<u-icon name="clock-fill" color="#7e7e7e" :size="28"></u-icon>
												<text
													class="padding-left-10">{{necessaryData.workPunchRecords[0].checkinTime || '上班未打卡'}}</text>
											</view>
											<view v-if="necessaryData.workPunchRecords[0].locationName" class="dk-subTitle">
												<u-icon name="map-fill" color="#7e7e7e" :size="28"></u-icon>
												<text
													class="padding-left-10">{{necessaryData.workPunchRecords[0].locationName || '上班未打卡'}}</text>
											</view>
											<view v-if="necessaryData.workPunchRecords[0].wifeName" class="dk-subTitle"
												style="margin-bottom: 40rpx;">
												<u-icon name="wifi" color="#616161" :size="28"></u-icon>
												<text
													class="padding-left-10">{{necessaryData.workPunchRecords[0].wifeName || '上班未打卡'}}</text>
											</view>
										</view>
									</template>
								</u-time-line-item>
								<u-time-line-item nodeTop="2">
									<template v-slot:node>
										<view class="u-node bg-white">
											<text class="cuIcon-title"
												:class="$isEmpty(necessaryData.offWorkPunchRecords)?'':'base-color'"
												style="font-size: 40rpx;"></text>
										</view>
									</template>
									<template v-slot:content>
										<view class="dk-time-line">
											<view class="dk-title">
												下班打卡
												<text v-if="necessaryData.offWorkPunchRecords[0]" class="text-fail"
													style="font-weight: 500;">（{{necessaryData.offWorkPunchRecords[0].exceptionMessage}}）</text>
											</view>
											<view class="dk-subTitle">
												<u-icon name="clock-fill" color="#7e7e7e" :size="28"></u-icon>
												<text
													class="padding-left-10">{{necessaryData.offWorkPunchRecords[0].checkinTime || "下班未打卡"}}</text>
											</view>
											<view v-if="necessaryData.offWorkPunchRecords[0].locationName"
												class="dk-subTitle">
												<u-icon name="map-fill" color="#7e7e7e" :size="28"></u-icon>
												<text
													class="padding-left-10 text-cut-1">{{necessaryData.offWorkPunchRecords[0].locationName || "下班未打卡"}}</text>
											</view>
											<view v-if="necessaryData.offWorkPunchRecords[0].wifeName" class="dk-subTitle"
												style="margin-bottom: 40rpx;">
												<u-icon name="wifi" color="#616161" :size="28"></u-icon>
												<text
													class="padding-left-10">{{necessaryData.offWorkPunchRecords[0].wifeName || '下班未打卡'}}</text>
											</view>
										</view>
									</template>
								</u-time-line-item>
							</u-time-line>
						</view>
					</view>
				</view>
			</view>
			
			<view style="padding-top: 200rpx;" v-else>
				<u-empty icon-size="300" text="今天不上班，要好好休息哟~" src="/punch/static/icon/rest.png">
					<view style="text-decoration: underline;" class="margin-top-30 base-color flex" slot="bottom">
						<navigator url="/punch/pages/punch-list/punch-list" hover-class="none">打卡记录</navigator>
						<navigator url="/punch/pages/rule/rule" hover-class="none" style="margin-left: 30rpx;">
							打卡规则</navigator>
					</view>
				</u-empty>
			</view>
			
			<u-modal v-model="exceptionShow" @confirm="save" :confirm-text="confirmText" :show-cancel-button="showCancel"
				:show-title="false" confirm-color="#5064eb">
				<view class="slot-content">
					<image src="../../static/icon/exception.png" mode=""></image>
					<view>
						<view class="tips" style="text-align: center;" v-if="exception.includes(item.value)"
							v-for="(item,index) in exceptionMsgArr" :key="index">
							<text class="cuIcon-title" v-if="exception.length>1"></text>
							<text> {{item.label}}</text>
						</view>
					</view>
				</view>
			</u-modal>
		</view>
		
		<view  class="loading" v-else>
			<image style="width: 600rpx;" src="https://image.weilanwl.com/gif/loading-white.gif" mode="widthFix"></image>
		</view>
	</view>
</template>

<script>
	let that;
	export default {
		data() {
			return {
				//是否是工作日
				isWork:false,
				
				//加载
				loading:true,
				//打卡异常时显示
				showCancel: true,
				exceptionShow: false,
				exceptionMsgArr: [{
						value: 1,
						label: '您迟到了'
					},
					{
						value: 2,
						label: '您早退了'
					},
					{
						value: 3,
						label: '不在指定打卡范围内'
					},
					{
						value: 5,
						label: '不在指定打卡范围内,不能打卡'
					},
				],
				confirmText: '确定打卡',
				exception: [],

				//日期
				date: '',
				//时间
				time: '',
				//更新位置的次数
				clickNum: 0,

				//当前位置信息
				cur_longitude: '', //当前经度
				cur_latitude: '', //当前纬度
				cur_address: '', //当前地址

				cur_wifi: '', //当前连接的WiFi名
				cur_wifi_mac: '', //当前连接WiFi的mac码

				necessaryData: {
					isDone: false, //是否完成了打卡
					needLocation: false, //是否需要位置打卡
					isInPunchLocation: false, //是否在指定位置范围内打卡
					needWifi: false, //是否需要wifi打卡
					isInPunchWifi: false, //是否在指定WiFi考勤区域内
					isWork: false, //当天是否是工作日
					/**
					 * 是通过哪个时间规则查询出来的
					 * 有两种，一个是正常工作日id
					 * 一个是特殊工作日的id
					 */
					ruleTimeId: '',
					/**
					 * ruleTimeId是属于哪个时间规则查询出来的
					 * 是通过正常工作日查询【1】
					 * 还是通过特殊工作日查询【0】
					 */
					ruleTimeType: '',
					workTime: '', //当天的上班时间
					offWorkTime: '', //当天的下班时间
					workPunchRecords: '', //上班打卡记录
					offWorkPunchRecords: '', //下班打卡记录
					/**
					 * 打卡状态
					 * 0:上班打卡
					 * 1:下班打卡
					 */
					workStatus: '',
					
					ruleTime:{},
				}
			};
		},
		created() {
			that = this
			//获取当前日期
			this.date = this.$dateTime.format(new Date(), 'YYYY-mm-dd')
			//获取当前时间
			this.getNowTime()
			
			
			console.log(this.vuex_punch_rules.isWork);
			if (this.vuex_punch_rules.isWork) {
				this.isWork=true
				this.getCoordinates()
				return
			}
			setTimeout(()=>{
				that.loading=false
			},20)
		},
		methods: {
			jump(url){
				if (!this.$isEmpty(url)) {
					uni.navigateTo({
						url
					})
				}
			},
			punch() {
				this.getPunchExcepton()
				if (this.$isEmpty(this.exception)) {
					//没有异常，正常打卡
					this.save()
					return
				}
				if (this.exception[0] == 5) {
					//不能打卡
					this.confirmText = '确定'
					this.showCancel = false
					this.exceptionShow = true
					return
				}
				this.exceptionShow = true
			},
			save() {
				let exceptionMessage = ""
				if (this.exception[0] == 5) {
					return
				}
				if (this.exception.includes(1)) {
					exceptionMessage = '迟到'
				}
				if (this.exception.includes(2)) {
					exceptionMessage = '早退'
				}
				if (this.exception.includes(3)) {
					if (this.$isEmpty(exceptionMessage)) {
						exceptionMessage = '范围外异常'
					} else {
						exceptionMessage += ',范围外异常'
					}
				}

				let params = {
					ownerId:this.vuex_userInfo.enterpriseId,
					personId: this.vuex_userInfo.id,
					personName: this.vuex_userInfo.realName,
					personType: 0,
					deviceId: this.$u.sys().deviceId,
					wifeName: this.cur_wifi,
					wifiMac: this.cur_wifi_mac,
					longitude: this.cur_longitude,
					latitude: this.cur_latitude,
					locationName: this.cur_address,
					checkinTime: this.$dateTime.format(),
					checkinType: this.necessaryData.workStatus,
					schCheckinTime: this.necessaryData.workStatus == 0 ? this.necessaryData.workTime : this
						.necessaryData
						.offWorkTime,
					exceptionMessage: exceptionMessage,
					ruleId: this.vuex_punch_rules.id,
					ruleTimeId: this.necessaryData.ruleTimeId,
					ruleTimeType: this.necessaryData.ruleTimeType,
				}
				this.$api.punch.save(params).then(res => {
					if (res.success == true) {
						this.getNecessaryData()
					} else {
						this.$dialog.showModal(res.msg, false).then(() => {
							this.exceptionShow = false
						})
					}
				})
			},
			/**
			 * 获取打卡异常，
			 * 正常情况，正常和正常外勤 exception为空 []
			 * 范围外打卡，exception 必有 范围外异常，或许会有迟到/早退异常 [3]/[3,1]/[3,2]
			 * 不能打卡 [5]
			 * 迟到异常 [1]
			 * 早退异常 [2]
			 */
			getPunchExcepton() {
				// 0正常 1 迟到  2早退  3 范围外异常 4 正常外勤 5不在范围内，不能打卡
				this.exception = []

				if (!this.necessaryData.isInPunchLocation && !this.necessaryData.isInPunchWifi) {
					//不在指定的wifi或者在指定的打卡位置上
					let optionOutRange = this.vuex_punch_rules.optionOutRange
					if (optionOutRange == 0) {
						//范围外异常
						this.exception.push(3)
					} else if (optionOutRange == 2) {
						this.exception.push(5)
						return
					}
				}
				let status = this.getWorkStatusException()
				if (status != 0) {
					this.exception.push(status)
				}
			},
			getWorkStatusException() {
				//当前时间戳
				let now = new Date().getTime()
				
				let ruleTime=this.necessaryData.ruleTime
				
				
				if (this.necessaryData.workStatus == 0) {
					//上班打卡
					//上班时间戳
					let workTime = this.$dateTime.createDate(`${this.date} ${this.necessaryData.workTime}:00`)
						.getTime()
					
					if (ruleTime.allowFlex==1) {
						//允许弹性上班时间
						workTime=workTime+ruleTime.flexOnDutyTime*60*1000
					}	
					
					if (now > workTime) {
						return 1
					}
				} else if (this.necessaryData.workStatus == 1) {
					//下班打卡
					//下班时间戳
					let offWorkTime = this.$dateTime.createDate(`${this.date} ${this.necessaryData.offWorkTime}:00`)
						.getTime()
						
					if (ruleTime.allowFlex==1) {
						//允许弹性下班时间
						offWorkTime=offWorkTime-ruleTime.flexOffDutyTime*60*1000
					}
						
					if (now < offWorkTime) {
						return 2
					}
				}
				return 0
			},
			/**
			 * 动态获取当前时间
			 */
			getNowTime() {
				this.time = this.$dateTime.format(new Date(), 'HH:MM:SS')
				setInterval(() => {
					that.time = that.$dateTime.format(new Date(), 'HH:MM:SS')
				}, 1000)
			},
			/**
			 * 获取经纬度
			 */
			async getCoordinates() {
				if (this.clickNum !== 0) {
					this.$dialog.showLoading("获取中...")
				}
				if (this.clickNum >= 5) {
					this.$u.toast("请稍后尝试")
					setTimeout(() => {
						that.clickNum = 1
					}, 15000)
					return;
				}
				this.clickNum++;
				let res = await this.$mpi.getLocation()
				if (this.clickNum !== 0) {
					setTimeout(() => {
						uni.hideLoading()
					}, 800)
				}
				that.cur_latitude = res.latitude
				that.cur_longitude = res.longitude
				this.getNecessaryData()
				this.getLocation()
			},
			/**
			 * 通过坐标获取具体位置
			 */
			getLocation() {
				let vuex_location = {
					latitude: this.cur_latitude,
					longitude: this.cur_longitude
				}
				let params = {
					longitude: that.cur_longitude,
					latitude: that.cur_latitude
				}
				that.$api.punch.getLocation(params).then(res => {
					if (that.clickNum != 1) {
						setTimeout(() => {
							uni.showToast({
								title: "更新成功"
							})
						}, 1200)
					}
					let Res_Data = res.data.result;
					//将位置共享给外出打卡，以免再次请求
					vuex_location.address = Res_Data.formatted_addresses.recommend
					that.$u.vuex('vuex_location', vuex_location)
					that.cur_address = Res_Data.address + '(' + Res_Data
						.formatted_addresses.recommend + ')'
				})
			},
			/**
			 * 获取必需的数据
			 */
			async getNecessaryData() {
				let res = {};
				try {
					res = await this.$mpi.getConnectedWifi()
				} catch (e) {
					console.log(e);
				}
				this.cur_wifi = res.wifi ? res.wifi.SSID : ''
				this.cur_wifi_mac = res.wifi ? res.wifi.BSSID : ""
				let params = {
					longitude: this.cur_longitude,
					latitude: this.cur_latitude,
					personId: this.vuex_userInfo.id,
					personType: 0,
					wifiMac: this.cur_wifi_mac
				}
				let resp = await this.$api.punch.getNecessaryData(params)
				this.necessaryData = resp.data
				
				that.loading=false
			},
		}
	};
</script>

<style lang="scss">
	.top {
		height: 450rpx;
		background-color: $base-color;
	}

	.person {
		border-radius: 20rpx;
		padding: 40rpx;
		display: flex;
		justify-content: space-between;
		margin: 20rpx;
		background-color: #FFFFFF;

		.tag {
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100rpx;
			width: 100rpx;
			font-size: 34rpx;
			background-color: #036cc2;
			color: #FFFFFF;
		}

		.content {
			padding-left: 20rpx;

			.name {
				font-size: 34rpx;
				font-weight: 800;
			}

			.company {
				padding-top: 10rpx;
				font-size: 26rpx;
				color: $base-color;
			}
		}

		.date {
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.page-content {
		height: 1180rpx;
		margin: 20rpx;
		padding-bottom: 50rpx;
		border-radius: 20rpx;
		background-color: #FFFFFF;

		.reset-location {
			padding-left: 10rpx;
			text-decoration: underline;
		}

		.btn-position {
			display: flex;
			justify-content: center;
			margin-top: 40rpx;

			.dk-btn {
				width: 70%;
				padding: 20rpx 80rpx;
				// background-color: $base-color;
				background-image: linear-gradient(#52a5f8, $base-color);
				color: #FFFFFF;
				border-radius: 5000rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				box-shadow: 0rpx 10rpx 20rpx rgba(82, 159, 247, 0.8);

				text:first-child {
					font-size: 40rpx;
				}

				text:last-child {
					padding-top: 10rpx;
					font-size: 28rpx;
				}
			}
		}

		.location {
			padding: 30rpx 50rpx;
			display: flex;
			flex-direction: column;

			text:first-child {
				font-size: 32rpx;
			}

			text:last-child {
				padding-top: 10rpx;
				font-size: 26rpx;
				color: #676767;
			}
		}
	}

	.border-top {
		border-top: 1rpx dashed $dt-border-color-sm;
	}

	.dk-time-line {
		.dk-title {
			font-weight: 800;
			font-size: 32rpx;
			padding-bottom: 20rpx;
		}

		.dk-subTitle {
			display: flex;
			margin: 20rpx 0;
		}
	}

	.line-record {
		border-color: $base-color;
		color: $base-color;
	}

	.result {
		padding-top: 80rpx;
		padding-bottom: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		image {
			width: 180rpx;
			height: 180rpx;
		}

		.tips {
			padding-top: 50rpx;
			font-size: 36rpx;
			color: $base-color;
			font-weight: 800;
		}
	}

	.slot-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 50rpx 0 50rpx;

		image {
			margin-bottom: 50rpx;
			width: 100rpx;
			height: 100rpx;
		}

		.tips {
			margin-bottom: 20rpx;
			font-size: 28rpx;
			color: #333333;
		}
	}
	
	.loading{
		width: 100%;
		height: 60vh;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
