<template>
	<view>
		<u-sticky>
			<HeaderNav title="任务"></HeaderNav>
		</u-sticky>
		<view class="todo-page">
			<!-- <view class="status-bar" :style="{'width': screenWidth + 'px'}"></view> -->
			<view class="main">
				<view class="swiper-wrap">
					<u-swiper :list="banners" height="110" radius="8" circular indicator indicatorActiveColor="#2979ff" indicatorInactiveColor="#D7D7D7" indicatorMode="dot" indicatorStyle="right: 20px;"
						@change="e => currentBanner = e.current">
					</u-swiper>
				</view>
				<view style="display: flex;flex-direction: row;height: 40px;align-items: center;margin-left: 10px;">
					<view @click="handleTab('1')" style="height: 100%;display: flex;border-radius: 15px;margin-right: 10px;flex-direction: column;">
						<view style="display: flex;flex-direction: row;height: 100%;">
							<view style="display: flex;flex-direction: column;height: 100%;justify-content: center;">
								<text style="margin: 0px 5px;display: flex;align-items: center;margin-bottom: 5px;"
									:style="{color:currentTab === '1' ? '#000' : '#999999',fontSize:'16px',fontWeight: currentTab === '1' ? 'bold' : 'normal'}">我的待办</text>
								<view v-if="currentTab === '1'" class="bottom-widget"></view>
							</view>
							<view style="display: flex;align-items: flex-start;">
								<u-badge type="error" max="99" :value="todoTotal" style="font-weight: bold;z-index: 999;display:flex;align-items: flex-start;"></u-badge>
							</view>
						</view>
					</view>
					<!-- <view @click="handleTab('2')"
						style="height: 100%;display: flex;border-radius: 15px;margin-right: 10px;flex-direction: column;">
						<view style="display: flex;flex-direction: row;height: 100%;">
							<view style="display: flex;flex-direction: column;height: 100%;justify-content: center;">
								<text style="margin: 0px 5px;display: flex;align-items: center;margin-bottom: 5px;"
									:style="{color:currentTab === '2' ? '#000' : '#999999',fontSize:'16px',fontWeight: currentTab === '2' ? 'bold' : 'normal'}">我的已办</text>
								<view v-if="currentTab === '2'" class="bottom-widget"></view>
							</view>
							
						</view>
					</view> -->

					<view @click="handleTab('3')" style="height: 100%;margin-right: 10px;display: flex;border-radius: 15px;">
						<view style="display: flex;flex-direction: row;height: 100%;">
							<view style="display: flex;flex-direction: column;height: 100%;justify-content: center;">
								<text style="margin: 0px 5px;display: flex;align-items: center;margin-bottom: 5px;"
									:style="{color:currentTab === '3' ? '#000' : '#999999',fontSize:currentTab === '3' ? '16px' : '16px',fontWeight: currentTab === '3' ? 'bold' : 'normal'}">我的消息</text>
								<view v-if="currentTab === '3'" class="bottom-widget"></view>
							</view>

							<view style="display: flex;align-items: flex-start;">
								<u-badge type="error" max="99" :value="noticeTotal" style="font-weight: bold;z-index: 999;display:flex;align-items: flex-start;"></u-badge>
							</view>
						</view>

					</view>
					<!-- <view style="display: flex;align-items: end;flex: 1;">
						<u-icon name="scan" size="26" @click="scan"></u-icon>
					</view> -->

					<!-- <view @click="handleTab('4')" style="height: 100%;display: flex;border-radius: 15px;" v-if="sameLists.length &&isJD">
						<view style="display: flex;flex-direction: row;height: 100%;">
							<view style="display: flex;flex-direction: column;height: 100%;justify-content: center;">
								<text style="margin: 0px 5px;display: flex;align-items: center;margin-bottom: 5px;"
									:style="{color:currentTab === '4' ? '#000' : '#999999',fontSize:currentTab === '4' ? '16px' : '16px',fontWeight: currentTab === '4' ? 'bold' : 'normal'}">岗位任务</text>
								<view v-if="currentTab === '4'" class="bottom-widgetmore"></view>
							</view>
						</view>

					</view> -->
				</view>
				<view v-if="currentTab == '1'||currentTab == '3' ||currentTab == '2'">
					<view v-if="!lists.length" class="empty-wrap">
						<u-empty text="暂无任务" icon="/static/empty@2x.png">
						</u-empty>
					</view>
					<view v-else class="content-list">
						<common-card :dataSource="item" v-for="(item, key) in lists" :key="key" icon @click="taskClisk">
						</common-card>
					</view>
				</view>
				<!-- <view v-if="currentTab == '4'">
					<view v-if="!sameLists.length" class="empty-wrap">
						<u-empty text="暂无任务" icon="/static/empty@2x.png">
						</u-empty>
					</view>
					<view v-else class="content-list">
						<same-card :dataSource="item" v-for="(item, key) in sameLists" :key="key" @click="userToDos(item)">
						</same-card>
					</view>
				</view> -->

			</view>
			<u-toast ref="uToast"></u-toast>
		</view>
	</view>

</template>

<script>
	import CommonCard from '@/components/custom/common-card2.nvue';
	import SameCard from '@/components/custom/same-card.vue';

	import {
		handleTaskStatus,
		getTodoData,
		FullGet,
		searchSame,
		userToDo
	} from '../../services/app'
	import {
		getEnum
	} from '../../services/common'
	import {
		GetNewRiskAreaInfo,
	} from '../../services/apply/subPages/SK/SKServices.js'
	import {
		initFilter,
		extendRule,
		extendInclude,
		ApproveCode,
		SourceFormcode
	} from '../../utils/common'
	import HeaderNav from '@/components/custom/head-nav.vue';

	// import '@/utils/showMsg.js'
	export default {
		components: {
			CommonCard,
			HeaderNav
		},
		data() {
			return {
				timingGet: undefined,
				affairType: '1',
				currentTab: '1',
				todoTotal: 0,
				doneTotal: 0,
				noticeTotal: 0,
				lists: [],
				sameLists: [],
				banners: [
					'../../static/banner02.png',
					'../../static/banner03.png',
					'../../static/banner04.png'
				],
				currentBanner: 0,
				text: '',
				statusBar: '54px',
				IsBrush: true,
				pageIndex: 1,
				isJD: false,
				comPickerInfo: {
					showPicker: false,
					columns: [],
					title: '',
					name: ''
				},
				currentIndex: 0,
			}
		},
		// mounted() {
		// 	 this.pushMessage()
		// },
		onShow() {
			// let allPages=getCurrentPages()
			// let lastPage=allPages-1
			// let option =allPages[lastPage].options 
			const orgId = uni.getStorageSync('orgId')
			if (orgId == '8b3c41aa-51b1-7ce9-1879-248a038c1b5c') {
				this.isJD = true
			}
			var areaLists = uni.getStorageSync('listAreas')
			if ((areaLists == null || areaLists == '') && orgId !== '') {
				this.loadAreaNew()
			}


			this.pageIndex = 1
			this.handleGetTodoData()
			// this.getSameTodo()
			this.timingGet = setInterval(() => {
				// this.getSameTodo()
				const d = getApp().globalData.noticeAndTask
				if (d.Msg > this.noticeTotal || d.Task > this.todoTotal) {
					this.pageIndex = 1
					this.handleGetTodoData()
				}
			}, 1500000)
			// const appInfoData = uni.getStorageSync('appInfo')
			// uni.setStorageSync('userId', appInfoData?.User?.ID )

		},
		onHide() {
			clearInterval(this.timingGet)
		},
		onLoad() {
			uni.getSystemInfo({
				success: e => {
					this.screenWidth = e.screenWidth
					// #ifndef H5
					this.statusBar = e.statusBarHeight
					// #endif
				}
			})
			this.handleGetTodoData()
		},
		onPullDownRefresh() {
			this.pageIndex = 1
			this.handleGetTodoData()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			scan() {
				// #ifdef APP-PLUS
				uni.scanCode({
					scanType: ['qrCode'],
					success: function(res) {
						uni.navigateTo({
							url: `/pages/my/subPages/webView?htmlPath=${res.result}`
						})
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
					}
				});
				// #endif
			},
			showToast() {
				this.$refs.uToast.show({
					type: 'default',
					message: "此任务请到电脑上操作!"
				})
			},
			async loadAreaNew() {
				const orgId = uni.getStorageSync('orgId')
				if (orgId && orgId != '') {
					const json = initFilter(orgId, "", "NAME", 0)
					json.Limit = 500
					json.SelectField = ['ID', 'CODE', 'NAME']
					await GetNewRiskAreaInfo(json).then(res => {
						if (res.IsSuccessful) {
							// var listA = res

							var listAreas = res
							uni.setStorageSync('listAreas', listAreas);
						}
					})
					var dataParm = {
						'name': "SKProductionUnit"
					}
					await getEnum(dataParm).then(res => {
						if (res != undefined && res.length > 0) {
							for (let i = 0; i < res.length; i++) {
								res[i].name = res[i].NAME
								res[i].code = res[i].ID
							}
						}
						var mineTypeStorage = res
						uni.setStorageSync('mineTypeStorage', mineTypeStorage);
					})
				}
			},
			changeSwiper(e) {
				this.currentIndex = e.detail.current
			},
			handleTab(t) {
				this.currentTab = t
				if (t !== '4') {
					this.affairType = t
					this.pageIndex = 1
				} else {
					this.getSameTodo()
				}

			},
			userToDos(e) {
				uni.navigateTo({
					url: `/pages/same/sameJob?sameData=${e.userID}&name=${e.userName}`
				})
			},
			getSameTodo() {
				const orgId = uni.getStorageSync('orgId')
				const appInfoData = uni.getStorageSync('appInfo')
				const userId = appInfoData?.User?.ID || ''

				const json = {
					Parameter1: userId,
					orgid: orgId
				}
				searchSame(json).then(res => {
					this.sameLists = res.users
				})
			},
			handleGetTodoData(isAdd = false) {
				if (!getApp().globalData.isOnline) {
					return false
				}
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", '', this.pageIndex)
				json.Parameter1 = this.affairType; // 1.待办事项 2.已办事项 3.今日新增 4.待办超时
				getTodoData(json).then(res => {
					this.total = res.TotalCount
					this.noticeTotal = res.todayNewCount
					this.todoTotal = res.todoCount
					this.doneTotal = res.doneCount
					// const options = {
					// 	cover: false,
					// 	sound: 'system',
					// 	title: '矿山安全生产标准化系统'
					// }
					// const pushUrl = `pages/apply/index`
					// const innerAudioContext = uni.createInnerAudioContext();
					// innerAudioContext.autoplay = true;
					// innerAudioContext.src =
					// 	'https://you.induschain.cn/audio/y913.mp3';
					// const content = '您有新的待办任务，快点完成吧'
					// plus.push.createMessage(content, pushUrl, options)

					const newRes = (res.newData || []).map(i => {
						const obj = {
							...i,
							title: i.NOTICE_TITLE,
							startTime: i.TASK_STARTDT,
							endTime: i.TASK_ENDDT,
							// status: i.NOTICE_STATUS,
							// statusText: i.NOTICE_STATUS
						}
						if (this.affairType === '1') {
							obj.status = i.OVER_TIME === '正常' ? 0 : 1
							obj.statusText = i.OVER_TIME
						}
						if (this.affairType === '2') {
							obj.status = i.OVER_TIME === '正常' ? 0 : 1
							obj.statusText = i.OVER_TIME
						}
						if (this.affairType === '3') {
							obj.status = i.NOTICE_STATUS
							obj.statusText = i.NOTICE_STATUS === 0 ? '未读' : '已办'
						}
						return obj
					})
					if (isAdd)
						this.lists = this.lists.concat(newRes)
					else
						this.lists = newRes
				})
			},
			// 动态设置tabBar
			// onSetTabBar() {
			//   uni.setTabBarItem({
			//     index: 2,
			//     text: 'text',
			//     pagePath: 'pages/my/index',
			//     iconPath: 'static/tabbar_user@2x.png',
			//     selectedIconPath: 'static/tabbar_user_activited@2x.png'
			//   })
			// }

			taskClisk(item) {
				if (this.affairType === '3') {
					const modalOption = {
						title: '消息',
						content: item.NOTICE_TITLE,
						success: e => {
							const {
								confirm,
								cancel
							} = e
							if (confirm) {
								if (item.NOTICE_STATUS === 0) {
									// 标记为已读
									const orgId = uni.getStorageSync('orgId')
									const json = initFilter(orgId, item.ID)
									handleTaskStatus(json).then(res => {
										if (res) {
											uni.showToast({
												title: '标记为已读'
											})
											this.pageIndex = 1
											this.handleGetTodoData()
										}
									})
								} else {
									// null
								}
							}
							if (cancel) {
								// cancel
							}
						}
					}
					if (item.NOTICE_STATUS === 0) {
						modalOption.cancelText = '确认'
						modalOption.confirmText = '标记已读'
					} else {
						modalOption.showCancel = false
					}
					uni.showModal(modalOption)
					return
				}
				let linkToUrl = ''
				if (item.SOURCE_FORMCODE == 'PF119') {
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId)
					extendRule(json, 'ID', 1, item.SOURCE_DATA_ID);
					extendInclude(json, "Nav_ApproveDetails")
					extendInclude(json, "Nav_ApproveDetails.Nav_ApproveUser")
					FullGet(json).then(res => {
						let okApi = res.CALLBACK_INTERFACE
						// api 请求 获取  APPROVE_CODE ID
						linkToUrl = ApproveCode(res.APPROVE_CODE)
						if (okApi && okApi.indexOf('New') > -1) {
							okApi = res.CALLBACK_INTERFACE
						} else {
							okApi = 'PF/Approve/Submit'
						}
						// //特殊处理
						// if (okApi === 'BS/BSSafeCheck/CheckAuditEnd' || okApi ===
						// 	'BS/BSSafeCheck/CheckPlanAuditEnd' || okApi === 'BS/BSRiskSubmit/Notice' ||
						// 	okApi === 'BS/BSRiskSubmit/DealEnd' || okApi ===
						// 	'BS/BSRiskSubmitDelayApply/DealEnd' || okApi === 'FO/FOJobEventRecord/BackUpdate'|| 
						// 	okApi === 'FO/FOCrucialLicenseJob/BackUpdate'||okApi ==='FO/FOCrucialLicenseJobOutsource/BackUpdate') {
						// 	okApi = res.CALLBACK_INTERFACE + 'New'
						// } else {
						// 	okApi = 'PF/Approve/Submit'
						// }
						if (linkToUrl != '') {
							linkToUrl += "?tableKey=" + this.affairType + "&ID=" + res.DATA_ID + "&ApproveID=" +
								item
								.SOURCE_DATA_ID + "&taskID=" +
								item.ID + '&isAudit=true&okApi=' + okApi + '&refuseApi=' + res
								.REJECT_INTERFACE
							this.$store.commit('updateAuditModel', res)
							uni.navigateTo({
								url: linkToUrl
							})
						} else {
							// uni.$showMsg('此任务请到电脑上操作!', 'error')
							this.showToast()
						}
					})
				} else {
					linkToUrl = SourceFormcode(item.SOURCE_FORMCODE)
					if (linkToUrl != '') {
						linkToUrl += "?tableKey=" + this.affairType + "&ID=" + item.SOURCE_DATA_ID + "&taskID=" + item.ID

						if (item.SOURCE_FORMCODE == 'SC034' || item.SOURCE_FORMCODE == 'SC030' || item.SOURCE_FORMCODE == 'SE050_SHOWPRINT') {
							linkToUrl += "&FORMCODE=" + item.SOURCE_FORMCODE //会议 纪要 load时 添加标识
						}

						uni.navigateTo({
							url: linkToUrl
						})
					} else {
						// uni.$showMsg('此任务请到电脑上操作!', 'error')
						this.showToast()
					}
				}
			},
		},
		watch: {
			affairType() {
				this.handleGetTodoData()
			}
		},
		onReachBottom() {
			if (this.affairType === '2') {
				if (this.doneTotal >= this.pageIndex * 10) {
					this.pageIndex++
					this.handleGetTodoData(true)
				}
			} else {
				if (this.total >= this.pageIndex * 10) {
					this.pageIndex++
					this.handleGetTodoData(true)
				}
			}
		}
	}
</script>

<style>
	.todo-page {
		position: relative;
	}

	.todo-page .status-bar {
		height: 120px;
		background-image: linear-gradient(to right, #CFECFF, #6EB6FF);
		position: absolute;
		top: 0;
		left: 0;
		z-index: -10;
	}

	.todo-page .main {
		padding: 10px 8px 62px 8px;
		position: relative;
		z-index: 10;
		background-size: 100% 120px;
		background-repeat: no-repeat;
	}

	.todo-page .swiper-wrap {
		margin-bottom: 16px;
	}

	.tabs-bar {
		display: flex;
		flex-direction: row;
	}

	.tabs-bar .tab {
		height: 40px;
		display: flex;
		align-items: center;
		position: relative;
		margin-right: 6px;
		padding-bottom: 6px;
	}

	.tabs-bar .tab .t {
		width: 55px;
		height: 50px;
		position: relative;
		/* overflow: inherit; */
	}

	.tabs-bar .tab .t .name {
		padding-top: 7px;
		padding-left: 8px;
		font-size: 18px;
		line-height: 22px;
		color: #999;
	}

	.bottom-widget {
		width: 74px;
		height: 2px;
		background-color: #2979ff;
		display: flex;
		justify-content: flex-start;
		align-items: flex-start;
	}

	.bottom-widgetmore {
		width: 74px;
		height: 2px;
		background-color: #2979ff;
		display: flex;
		justify-content: flex-start;
		align-items: flex-start;
	}

	.empty-wrap {
		margin-top: 60px;
	}

	.content-list {
		padding: 10px 0;
	}
</style>