<template>
	<view>
		<cu-custom ref="cuCustom" bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true" :backUrl="backUrl">
			<block slot="backText">返回</block>
			<block slot="content">我的任务</block>
		</cu-custom>
		<scroll-view scroll-x class="bg-white nav">
			<view class="flex text-center">
				<view class="cu-item flex-sub" :class="index==TabCur?'text-orange cur':''"
					v-for="(item,index) in tabNav" :key="index" @tap="tabSelect" :data-id="index">
					{{tabNav[index]}}
				</view>
			</view>
		</scroll-view>
		<block>
			<view v-if="TabCur==1" class="tasks-bg">
				<view class="tasks-content">
					<view class="tasks-top">
						<view class="tasks-nr">
							<view>
								{{JOINNUM}}次
							</view>
							<view>
								参加考试
							</view>
						</view>
						<view class="tasks-nr">
							<view>
								{{PASSNUM}}次
							</view>
							<view>
								合格
							</view>
						</view>
						<view class="tasks-nr">
							<view>
								{{NOPASSNUM}}次
							</view>
							<view>
								不合格
							</view>
						</view>
					</view>
				</view>
				<view class="stripes"></view>
			</view>
			<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
				<view class="tasks-warp" v-if="TabCur==0 && taskList.length>0" v-for="(item,index) in taskList" :key="item.STUDYTASK_ID">
					<view class="tasks-item">
						<view class="title">
							任务名称：{{item.STUDY_NAME}}
						</view>
						<view class="tasks-state">
							培训行业类型：{{item.TRAINTYPENAME}}
						</view>
						<view class="tasks-state">
							岗位培训类型：{{item.POSTTYPENAME}}
						</view>
						<view class="tasks-state">
							培训时间：{{item.PEIXUE_START_TIME}}至{{item.PEIXUE_END_TIME}}
						</view>
						<view class="tasks-state">
							任务状态：{{item.TASKSTATENAME}}
						</view>
						<view v-if="item.STAGESTEP === '1'" class="flex">
							<view  class="tasks-time">
								{{ item.LASTTIME }}
							</view>
						</view>
						<view v-else-if="item.STAGESTEP === '2'" class="flex">
							<view class="tasks-time">
								剩余：{{ item.LASTTIME }}
							</view>
							<view class="">
								<button class="cu-btn bg-orange round sm" @click="$noMultipleClicks(goToMyStudy, item)">立即学习</button>
							</view>
						</view>
					</view>
				</view>
				<view class="tasks-warp" v-if="TabCur==1 && scoreList.length>0" v-for="(item,index) in scoreList" :key="item.STAGESTUDENTRELATION_ID">
					<view class="tasks-item">
						<view class="title">
							任务名称：{{item.STUDY_NAME}}
						</view>
						<view class="tasks-state">
							考试试卷：{{item.EXAMNAME}}
						</view>
						<view class="tasks-state">
							考试结果：
							<text v-if="item.STAGEEXAMSTATE=='3' && item.PASSSCORE <= item.STAGEEXAMSCORE">已通过</text>
							<text v-else-if="item.STAGEEXAMSTATE=='3' && item.PASSSCORE > item.STAGEEXAMSCORE">未通过</text>
							<text v-else-if="item.STAGEEXAMSTATE=='4'">未参加</text>
						</view>
						<view class="flex">
							<view class="tasks-state">
								考试成绩：
								<text v-if="item.STAGEEXAMSTATE=='4'">-</text>
								<text v-else>{{item.STAGEEXAMSCORE}}分</text>
							</view>
							<view class="">
								<button class="cu-btn round bg-orange sm" @click="$noMultipleClicks(goToMyExamResult, item)">考试详情</button>
							</view>
						</view>
					</view>
				</view>
				<view v-if="(TabCur==0 &&taskList.length<1) || (TabCur==1 &&scoreList.length < 1)" class="dy-null">
					<view class="dy-null-img">
						<image src="../../../static/null.png" mode=""></image>
					</view>
					<view class="dy-null-title">
						暂无数据
					</view>
				</view>
				<view class="cu-tabbar-height"></view>
			</mescroll-body>
		</block>
	</view>
</template>
<script>
	import {
		basePath,baseImgPath,corpinfoId,loginSession,loginUser
	} from '@/common/tool.js';
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js"
	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				baseImgPath: baseImgPath,
				CustomBar: this.CustomBar,
				backUrl: '/pages/application/onlinexxks/home',
				sTop: 0,
				totalHeight: 0,
				downOption: {
					use: true,
					auto: false
				},
				upOption: {
					use: true,
					auto: false,
					noMoreSize: 1,
					textNoMore: ''
					// textNoMore: '--已经没有更多了--'
				},
				scrollLeft: 0,
				taskList: [], //任务列表返回数据
                scoreList: [], //成绩列表返回数据
				page: 1, //分页参数--页数
				rows: 10, //分页参数--每页数据条数
				totalCount: 0, //分页参数--初始化页数
				isEnd: false, //防止多次刷新
				totalPage: 0, //分页参数--分页数量
				noClick: true,
				TabCur: 0,
				tabNav: ['课程列表', '成绩查询'],
				JOINNUM: 0,
				PASSNUM: 0,
				NOPASSNUM: 0

			};
		},
		onLoad() {
			//页面显示或从后台跳回小程序时显示此页面时触发，从跳转页面返回时触发，不能传递参数
			var _this = this
			_this.background = require('@/common/background.json')
			_this.showCount = -1
			_this.currentPage = 1
			_this.isEnd = false
			_this.getTaskInit()
			loginSession();
		},
		onShow() {
		},
		beforeDestroy() {
			// 清除定时器
			this.taskList.forEach((ele) => {
				if (ele.countDown) {
					clearInterval(ele.countDown)
					ele.countDown = null
				}
			})
		},
		methods: {
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
				if (this.TabCur == 0) {
					this.scoreList = []
					this.getTaskInit()
				} else {
					// 清除定时器
					this.taskList.forEach((ele) => {
						if (ele.countDown) {
							clearInterval(ele.countDown)
							ele.countDown = null
						}
					})
					this.taskList = []
					this.getScoreInit()
				}
			},
			//重置分页
			initPageData() {
				var _this = this;
				_this.showCount = -1;
				_this.currentPage = 1;
				_this.isEnd = false;
			},
			//翻页
			turnPage() {
				var _this = this;
				_this.showCount = -1;
				_this.currentPage = _this.currentPage + 1;
				_this.isEnd = false;
			},
			//跳转事件
			downCallback(page) { //搜索按钮事件
				var _this = this;
				if (_this.TabCur==0) {
					_this.getTaskQuery(page)
				} else {
					_this.getScoreQuery(page)
				}
			},
			// 滑动到底方法
			upCallback(page) {
				var _this = this;
				if (_this.TabCur==0) {
					_this.scrolltolowerTask(page)
				} else {
					_this.scrolltolowerScore(page)
				}
			},
			//切换选项卡初始化任务列表
			getTaskInit() { //搜索按钮事件
				var _this = this
				_this.initPageData()
				_this.taskList = []
				_this.getTaskData();
			},
			//下拉刷新任务列表
			getTaskQuery(page) {
				var _this = this;
				_this.initPageData()
				_this.taskList = [];
				_this.getTaskData();
			},
			//  上滑加载更多
			scrolltolowerTask(page) {
				var _this = this;
				_this.turnPage()
				if (_this.totalPage >= _this.currentPage) {
					_this.getTaskData(); //开始分页查询
				}
			},
			getTaskData() {
				var _this = this;
				if (_this.isEnd) {
					return
				} else {
					_this.isEnd = true;
				}
				uni.showLoading({
					title: "加载中..."
				}); //加载中动画
				uni.request({
					url: basePath + '/app/stagestudentrelation/pageTaskByUser?showCount=' + _this.showCount + '&currentPage=' + _this.currentPage,
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						CORPINFO_ID: corpinfoId,
						USER_ID: loginUser.USER_ID,
						tm: new Date().getTime()
					},
					success: (res) => {
						uni.hideLoading(); //结束加载中动画
						if (res.data != null) {
							_this.totalPage = res.data.page.totalPage
							// 从后端获取的数据，将这一步骤放到异步获取后端数据的地方，对后端返回的数据进行处理
							res.data.varList.forEach((ele) => {
								// 调用定时器传递
								_this.timeInterval(ele)
								// 如果数据不更新的话，增加下面代码
								// res.data.varList.splice(1, 0)
							})
							// 从后端获取的数据，将这一步骤放到异步获取后端数据的地方，对后端返回的数据进行处理
							if (_this.taskList.length == 0) {
								_this.taskList = res.data.varList;
							} else {
								if (res.data.varList != null) {
									_this.list2 = res.data.varList;
									_this.taskList = _this.taskList.concat(_this.list2);
								}
							}
							_this.mescroll.endSuccess(res.data.varList.length, (res.data.page.totalPage > res.data.page.currentPage))
							_this.mescroll.endUpScroll(res.data.page.totalPage == res.data.page.currentPage)
						}
					},
					fail: () => {
						//  请求失败,隐藏加载状态
						_this.mescroll.endErr()
					}
				})
			},
			// 倒计时定时器
			timeInterval(row) {
				var nowDate = new Date().getTime()
				const beginTime = new Date(row.PEIXUE_START_TIME).getTime()
				const endTime = new Date(row.PEIXUE_END_TIME + " 23:59:59").getTime()
				if (nowDate > endTime || row.STATE == 2) {
					this.$set(row, 'TASKSTATENAME', '已结束')
					this.$set(row, 'STAGESTEP', '3')
				} else {
					if (beginTime <= nowDate && nowDate <= endTime && (row.STAGEEXAMSTATE == '3' || row.STAGEEXAMSTATE == '4')) {
						this.$set(row, 'TASKSTATENAME', '已结束')
						this.$set(row, 'STAGESTEP', '3')
					}else {
						// 绑定定时器
						row.countDown = setInterval(() => {
							nowDate = new Date().getTime()
							if (beginTime - nowDate > 0) {
								// 对每行的剩余时间进行设置
								row.lastTime = beginTime - nowDate
								row.stagestep = '1' // 未考试
								this.$set(row, 'TASKSTATENAME', '未开始')
								this.$set(row, 'LASTTIME', this.timeFormat(row.lastTime))
								this.$set(row, 'STAGESTEP', row.stagestep)
								// if((beginTime-nowDate) == 5000) {
								// 	uni.showModal({
								// 		title: '',
								// 		content: '<<'+row.EXAMNAME+'>>离开考时间还有五分钟！',
								// 		showCancel: false,
								// 		confirmText: '确定',
								// 		success: res => {}
								// 	})
								// }
							} else if (beginTime <= nowDate && nowDate <= endTime) {
								row.lastTime = endTime - nowDate
								row.stagestep = '2' // 已开考
								this.$set(row, 'TASKSTATENAME', '进行中')
								this.$set(row, 'LASTTIME', this.timeFormat(row.lastTime))
								this.$set(row, 'STAGESTEP', row.stagestep)
								if (row.STATE == 0){
									row.STATE = 1
									this.updateTaskState(row)
								}
							} else {
								row.stagestep = '3' // 已结束
								this.$set(row, 'TASKSTATENAME', '已结束')
								this.$set(row, 'STAGESTEP', row.stagestep)
								if (row.STAGEEXAMSTATE == '1') { // 到时后自动更新学员状态为未参加考试
									uni.request({
										url: basePath + '/app/stagestudentrelation/updateStudentState',
										method: 'POST',
										dataType: 'json',
										header: {
											'Content-type': 'application/x-www-form-urlencoded'
										},
										data: {
											CORPINFO_ID: corpinfoId,
											USERNAME: loginUser.USERNAME,
											// TYPE: '3',
											STAGEEXAMSTATE: '4',
											STAGESTUDENTRELATION_ID: row.STAGESTUDENTRELATION_ID
										},
										success: (res) => {}
									})
								}
								if (row.STATE != 2){
									row.STATE = 2
									this.updateTaskState(row)
								}
								// 清除定时器
								if(row.countDown) {
									clearInterval(row.countDown)
									row.countDown = null
								}
							}
						}, 1000)
					}
				}
			},
			updateTaskState(item){
				uni.request({
					url: basePath + '/app/studytask/updateTaskState',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						STUDYTASK_ID: item.STUDYTASK_ID,
						STATE: item.STATE,
						USERNAME: loginUser.USERNAME
					},
					success: (res) => {}
				})
			},
			// 剩余时间格式化
			timeFormat(times) {
				if (times > 0) {
					const days = this.addZero(
							Math.floor(times / 1000 / 60 / 60 / 24)
					) // 天
					const hours = this.addZero(
							Math.floor((times / 1000 / 60 / 60) % 24)
					) // 时
					const minutes = this.addZero(
							Math.floor((times / 1000 / 60) % 60)
					) // 分
					const seconds = this.addZero(Math.floor((times / 1000) % 60)) // 秒
					var html = days !== '00' ? days + '天' : ''
					html += hours !== '00' ? hours + '小时' : ''
					html += minutes !== '00' ? minutes + '分钟' : ''
					html += seconds + '秒'
					return html
				} else {
					return '已超时'
				}
			},
			// 个位补零
			addZero(d) {
				return parseInt(d) < 10 ? '0' + d : d
			},
			goToMyStudy(item) {
				uni.redirectTo({
					url: '/pages/application/onlinexxks/my-study?STAGESTUDENTRELATION_ID=' + item.STAGESTUDENTRELATION_ID
				})
			},
			/** 成績查詢功能 */
			//切换选项卡初始化成績列表
			getScoreInit() {
				var _this = this;
				_this.initPageData()
				_this.scoreList = []
				_this.getScoreData()
			},
			//下拉刷新成績列表
			getScoreQuery(page) {
				var _this = this;
				_this.initPageData()
				_this.scoreList = []
				_this.getScoreData()
			},
			// 上滑加载更多
			scrolltolowerScore(page) {
				var _this = this;
				_this.turnPage()
				if (_this.totalPage >= _this.currentPage) {
					_this.getScoreData()
				}
			},
			getScoreData() {
				var _this = this;
				if (_this.isEnd) {
					return
				} else {
					this.isEnd = true;
				}
				uni.showLoading({
					title: "加载中..."
				}); //加载中动画
				uni.request({
					url: basePath + '/app/stagestudentrelation/pageTaskScoreByUser?showCount=' + _this.showCount + '&currentPage=' + _this.currentPage,
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						CORPINFO_ID: corpinfoId,
						USER_ID: loginUser.USER_ID,
						tm: new Date().getTime()
					},
					success: (res) => {
						uni.hideLoading(); //结束加载中动画
						if (res.data != null) {
							_this.totalPage = res.data.page.totalPage
							this.JOINNUM = 0
							this.PASSNUM = 0
							this.NOPASSNUM = 0
							res.data.varList.forEach((ele) => {
								if (ele.STAGEEXAMSTATE == '3'){
									this.JOINNUM++
									if (ele.STAGEEXAMSCORE >= ele.PASSSCORE) {
										this.PASSNUM++
									} else{
										this.NOPASSNUM++
									}
								}
							})
							// 从后端获取的数据，将这一步骤放到异步获取后端数据的地方，对后端返回的数据进行处理
							if (_this.scoreList.length == 0) {
								_this.scoreList = res.data.varList;
							} else {
								if (res.data.varList != null) {
									_this.list2 = res.data.varList;
									_this.scoreList = _this.scoreList.concat(_this.list2);
								}
							}
							_this.mescroll.endSuccess(res.data.varList.length, (res.data.page.totalPage > res.data.page.currentPage))
							_this.mescroll.endUpScroll(res.data.page.totalPage == res.data.page.currentPage)
						}
					},
					fail: () => {
						//  请求失败,隐藏加载状态
						_this.mescroll.endErr()
					}
				})
			},
			goToMyExamResult(item) {
				uni.navigateTo({
					url: '/pages/application/onlinexxks/my-exam-detail?STUDYTASK_ID=' + item.STUDYTASK_ID + '&STAGEEXAMPAPER_ID=' + item.STAGEEXAMPAPER_ID
				})
			}
		}
	}
</script>
