<template>
	<!-- autoList.length > 0 -->
	<view class="content header_bg" v-if="autoList.length > 0">
		<headers :showBack="true" :themeType="'white'">
			<view class="headerName"> {{ tabsListName[current] }} </view>
			<view class="right" @click="screenData()">
				<image class="scancode" src="@/static/bthgIcon/screen.png" mode=""></image>
			</view>
		</headers>
		<!-- <view class="nav-type">
			<movable-area style="width: 100%; height: 100%; overflow: hidden">
				<movable-view direction="horizontal" style="min-width: 100%; width: 100%; height: 100%">
					<uni-segmented-control :current="current" :values="tabs" @clickItem="switchItem" styleType="text"
						activeColor="#ffffff"></uni-segmented-control>
				</movable-view>
			</movable-area>
		</view> -->
		<swiper :current="current" :duration="300" @change="tabChange" :style="{ height: contentHeight + 'px' }">
			<swiper-item class="datas" v-for="(data, i) in pageData" :key="i">
				<scroll-view v-if="data.length > 0" class="scrool-more" :refresher-threshold="0"
					@scrolltolower="toNextPage" :scroll-top="scrollTo.current" @scroll="scroll" enablePullDownRefresh
					@scrolltoupper="() => {}" :show-scrollbar="true" :style="{ height: contentHeight + 'px' }"
					scroll-y="true" scroll-with-animation="true">
					<view class="process-item" v-for="(item, i) in data" :key="item.instanceId + i"
						@click="showInstance(item)">
						<view>
							<text>
								<!-- {{ (item.owner || item.staterUser || {}).name }}提交的 -->
								{{ item.processDefName }}</text>
							<uni-tag class="process-item-status" circle="true" :text="getStatus(item).text"
								:type="getStatus(item).type" inverted></uni-tag>
						</view>
						<view class="form-content">
							<view v-for="fd in item.formAbstracts || []" :key="fd.id" class="form-content-it">
								<text style="color: #b5b5b5">{{ fd.name }}: </text>
								<text class="over-tip">{{ getFormValText(fd) }}</text>
							</view>
						</view>
						<view class="process-item-footer">
							<avatar :name="(item.owner || item.staterUser).name"
								:src="getRes((item.owner || item.staterUser).avatar)" :size="30"></avatar>
							<text>在 {{ item.createTime || item.startTime }} 提交 </text>
						</view>
					</view>
					<uni-load-more :status="status" mode="scaleToFill" :showIcon="false"></uni-load-more>
				</scroll-view>
				<image v-else class="nodata" src="/static/image/noData.png" mode="widthFix"></image>
			</swiper-item>
		</swiper>
		<!-- closeable
      close-icon="arrow-down"
      close-icon-position="top-left" -->
		<!-- 底部弹出 -->
		<van-popup v-model:show="screenInfo.showBottom" :close-on-click-overlay="false" position="bottom" title="展示弹出层" :style="{ height: '70%' }">
			<view class="screen_main">
				<view class="screen_header">
					<van-icon name="arrow-down" @click="cancel"/>
					<view>筛选</view>
				</view>
				<view class="screen_container" @touchmove.stop @touch.stop>
					<view class="screen_Itembox">
						<view>状态</view>
						<view class="screen_Items">
							<view class="screen-item screen-item_active">全部</view>
						</view>
					</view>
					<view class="screen_Itembox">
						<view>表单</view>
						<view v-for="item in  screenInfo.groupModelsList" :key="item.id">
							<view class="screen_Item_header">{{ item.name }}</view>
							<view class="screen_Items">
								<view @click="onCodeActive(ele)" :class="{'screen-item_active': screenInfo.code == ele.formId}" class="screen-item" v-for="ele in item.items" :key="ele.formId">
									{{ ele.formName }}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="screen_footer">
					<view class="screen_footer-cancel" @click="cancel">取消</view>
					<view class="screen_footer-confirm" @click="confirm">确定</view>
				</view>
			</view>
		</van-popup>
	</view>
	<!-- <view v-else>
		<view v-if="!loading" class="nullText">您无权限查看</view>
	</view> -->
</template>

<script setup>
	import headers from "@/components/headers/headers.vue";
	import Avatar from "@/components/Avatar.vue";
	import {
		computed,
		nextTick,
		reactive,
		ref
	} from "vue";
	import taskApi from "@/api/task";
	import {
		getModuleAndMenuList,
		getGroupModelsByUser,
		getProcessCountData,
		getGroupModels
	} from "@/api/model.js";
	import {
		getFormValText,
		getRes
	} from "@/utils/tool.js";
	import {
		onLoad,
		onUnload,
		onPullDownRefresh,
		onReachBottom,
	} from "@dcloudio/uni-app";
	import {
		getTaskResult,
		getProcTag
	} from "@/utils/ProcessUtil.js";
	const tabsListName = ["待审批", "待催办", "已办结"];
	const tabs = computed(() => {
		const navs = ["待审批", "已审批", "已发起", "我的抄送"];
		let arr = JSON.parse(JSON.stringify(autoList.value));
		arr = arr.filter((item) => navs.includes(item));
		// pageData.value = arr.map(() => []);
		arr[current.value] =
			(arr[current.value] || "") + `-${datas.value.total || 0}`;
		return arr;
	});

	const contentHeight = computed(() => {
		return uni.getSystemInfoSync().windowHeight - uni.upx2px(200);
	});

	const scrollTo = ref({
		current: 0,
		old: 0,
	});
	const current = ref(0);
	const status = ref("more");
	const params = ref({
		pageSize: 10,
		pageNo: 1,
		code: "",
	});

	const screenInfo = reactive({
		showBottom: false,
    code: "",
		groupModelsList: [],
	});

	//点击打开筛选
	const screenData = () => {
		console.log("screenData");
    screenInfo.code = params.value.code;
		screenInfo.showBottom = true;
	};
  const onCodeActive = (item) => {
		console.log(item, "onCodeActive");
    if(screenInfo.code == item.formId) {
      screenInfo.code = "";
      return
    }
    screenInfo.code = item.formId
	};

  const cancel = () => {
		screenInfo.showBottom = false;
	};

  const confirm = () => {
    params.value.code = screenInfo.code;
    getDataList();
    screenInfo.showBottom = false;
   }

	const getGroupModelsList = () => {
		getGroupModels({}).then(rsp => {
			if (rsp.statusCode == 200) {
				screenInfo.groupModelsList = rsp.data;
			}
			console.log(rsp, "getGroupModelsList");
		})
	};
	//定义四组页面数据
	const pageData = ref([
		[],
		[],
		[],
		[]
	]);

	const datas = ref({
		pages: 1,
		size: 10,
		total: 0,
		records: [],
	});

	let autoList = ref([]);
	let loading = ref(true);
	const isHidden = ref(false);
	// onMounted(() => {
	// 	getPageData()
	// })
	// 临时效果-为了隐藏内容
	function getPageData() {
		const idSet = new Set();
		getGroupModelsByUser({}, {
				TenantId: JSON.parse(uni.getStorageSync("loginUser")).sn,
			})
			.then((rsp) => {})
			.catch(() => {
				isHidden.value = true;
			});

		getProcessCountData()
			.then((rsp) => {})
			.catch(() => {
				isHidden.value = true;
			});
	}

	function getStatus(item) {
		let navs = tabs.value[current.value];
		if (navs.indexOf("-") >= 0) {
			navs = navs.split("-")[0];
		}
		switch (navs) {
			case "待审批":
				return {
					text: "待处理",
						type: "warning",
				};
			case "已审批":
				return getTaskResult(item);
			case "已发起":
			case "我的抄送":
				return getProcTag(item.result);
		}
		// case 0:
		// 	return {
		// 		text: '待处理', type: 'warning'
		// 	};
		// case 1:
		// 	return getTaskResult(item);
		// case 2:
		// case 3:
		// 	return getProcTag(item.result);
	}

	function getAuto() {
		// 获取工作台显示权限
		let loginUser = JSON.parse(uni.getStorageSync("loginUser"));
		getModuleAndMenuList({
			projectSn: loginUser.sn,
			moduleType: 7,
			userId: loginUser.userId,
		}).then((res) => {
			// let list = [];
			let list = res.data.result.menuList;
			autoList.value = list.map((item) => item.name);
			let arr = JSON.parse(JSON.stringify(autoList.value));
			const navs = ["待审批", "已审批", "已发起", "我的抄送"];
			arr = arr.filter((item) => navs.includes(item));
			autoList.value = arr;
			pageData.value.length = arr.length;
			loading.value = false;
			console.log(autoList.value);
			getDataList();
		});
	}

	function switchItem(v) {
		current.value = v.currentIndex;
		params.value.pageNo = 1;
		getDataList();
		scrollToTop();
	}

	function scroll(e) {
		scrollTo.value.old = e.detail.scrollTop;
	}

	function scrollToTop() {
		scrollTo.value.current = scrollTo.value.old;
		nextTick(() => {
			scrollTo.value.current = 0;
		});
	}

	function tabChange(e) {
		let index = e.target.current || e.detail.current;
		switchItem({
			currentIndex: index,
		});
	}

	function getDataRequest() {
		// let navs = tabs.value[current.value];
		let navs = tabsListName[current.value];
		console.log(tabs.value, current.value);
		if (navs.indexOf("-") >= 0) {
			navs = navs.split("-")[0];
		}
		switch (navs) {
			case "待审批":
				return taskApi.getUserTodoList(params.value);
			case "已审批":
				return taskApi.getIdoList(params.value);
			case "已发起":
				return taskApi.getUserSubmittedList(params.value);
			case "我的抄送":
				return taskApi.getCcMeList(params.value);
			case "已办结":
				return taskApi.getUserSubmittedList({
					...params.value,
					customStatus: current.value,
				});
			case "待催办":
				return taskApi.getUserSubmittedList({
					...params.value,
					customStatus: current.value,
				});
		}
	}

	function getDataList() {
		status.value = "loading";
		try {
			getDataRequest().then((rsp) => {
					uni.stopPullDownRefresh();
					// console.log(JSON.stringify(rsp.data), 888999);
					datas.value.total = rsp.data.total;
					if (params.value.pageNo === 1) {
						//datas.value.records.length = 0
						pageData.value[current.value].length = 0;
					}
					pageData.value[current.value].push(...rsp.data.records);
					//datas.value.records.push(...rsp.data.records)
					status.value =
						params.value.pageNo * params.value.pageSize < datas.value.total ?
						"more" :
						"noMore";
				})
				.catch((err) => {
					uni.stopPullDownRefresh();
				});
		} catch (e) {
			//TODO handle the exception
			console.log(e);
		}
	}

	function showInstance(item) {
		uni.navigateTo({
			url: `/pages/instance/instancePreview?instanceId=${
      item.instanceId
    }&nodeId=${current.value === 0 ? item.nodeId : null}`,
		});
	}

	onLoad((v) => {
		console.log(JSON.stringify(v), 987);
		current.value = parseInt(v.current) || 0;
		uni.hideTabBar();
		getDataList();
		getAuto();
		getGroupModelsList();
		// uni.showToast({
		// 	title: '暂未开发，敬请期待',
		// 	icon: 'none'
		// })
	});

	// 监听事件，快速跳转到对应项
	uni.$on("to:workspace", (v) => {
		switchItem({
			currentIndex: v,
		});
	});

	onUnload(() => uni.$off("to:workspace"));

	onPullDownRefresh(() => {
		getDataList();
	});

	function toNextPage() {
		params.value.pageNo++;
		getDataList();
	}
</script>

<style lang="less" scoped>
	.screen_main {
		// display: flex;
		padding: 20rpx 32rpx;
		position: relative;

		.screen_header {
			display: flex;
			align-items: center;
      		padding-bottom: 20rpx;

			>view {
				text-align: center;
				flex: 1;
			}
		}

		.screen_container {
			overflow-y: scroll;
			height: 58vh;

			.screen_Itembox {
				margin-top: 30rpx;

				>view:first-child {
					font-size: 28rpx;
					color: #171717;
				}

				.screen_Item_header {
					font-size: 24rpx;
					color: #444444;
					margin-top: 20rpx;
					margin-left: 20rpx;
					position: relative;
				}

				.screen_Item_header::before {
					content: "";
					display: inline-block;
					width: 12rpx;
					height: 12rpx;
					background: #444444;
					border-radius: 50%;
					position: absolute;
					left: -20rpx;
					top: 50%;
					transform: translateY(-50%);
				}

				.screen_Items {
					display: flex;
					// justify-content: space-between;
					flex-wrap: wrap;

					.screen-item {
						font-size: 26rpx;
						color: #444444;
						margin-top: 20rpx;
						width: calc(30.8% - 20rpx);
						border-radius: 8rpx;
						border: 2rpx solid #F3F4FE;
						padding: 8rpx 10rpx;
						display: flex;
						justify-content: center;
						align-items: center;
					}

					.screen-item:not(:nth-child(3n + 1)) {
						margin-left: 20rpx;
					}

					.screen-item_active {
						background: #2F8FF3;
						color: white;
					}
				}


			}
		}

		.screen_container::-webkit-scrollbar {
			display: none; /* Chrome Safari */
		}

		.screen_footer {
			width: calc(100% - 40rpx);
			padding: 20rpx 0;
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			justify-content: space-between;

			.screen_footer-cancel {
				width: 45%;
				height: 60rpx;
				border-radius: 8rpx;
				border: 1px solid #F3F4FE;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.screen_footer-confirm {
				width: 45%;
				height: 60rpx;
				border-radius: 8rpx;
				background-color: #2D8EF3;
				color: white;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	/deep/ .right {
		font-size: 24rpx;
		position: absolute;
		right: 20rpx;
		top: 50%;
		z-index: 4;
		transform: translateY(-50%);

		.scancode {
			width: 44rpx;
			height: 44rpx;
		}
	}

	.header_bg {
		width: 100vw;
		min-height: 330rpx;
		background-image: url(/static/image/main_bg1.png);
		background-repeat: no-repeat;
		background-size: 100%;
		// background: linear-gradient(180deg, #2B8DF3 0%, #F4F5FD 100%);
		// position: absolute;
		// top: 0;
		position: relative;
	}

	page {
		background-color: #f4f5f7;
	}

	.nullText {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		font-size: 28rpx;
	}

	.nav-type {
		// position: fixed;
		// top: 0;
		width: 100%;
		height: 72rpx;

		// z-index: 999;
		// overflow-x: scroll;
		//   background-color: white;
		:deep(.segmented-control) {
			width: 100%;
			padding: 0 28rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.segmented-control__item {
				width: max-content;
				flex: none;
			}

			.segmented-control__item:not(:last-child) {
				margin-right: 50rpx;
			}

			.segmented-control__text {
				color: rgba(255, 255, 255, 0.7) !important;
			}

			.segmented-control__item--text {
				border-bottom: none;
				color: white !important;
			}
		}
	}

	.datas {
		position: relative;

		.nodata {
			width: 100%;
			height: auto;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}

		.process-item {
			margin: 32rpx;
			border-radius: 13rpx;
			background-color: white;
			padding: 26rpx 32rpx;
			position: relative;

			.uni-tag {
				font-weight: 400;
			}

			.process-item-status {
				position: absolute;
				right: 32rpx;
			}

			.form-content {
				font-size: 26rpx;
				color: #8b8b8b;
				margin: 16rpx 16rpx;

				.form-content-it {
					overflow-x: hidden;
					display: flex;
					flex-wrap: wrap;

					.over-tip {
						margin-left: 5px;
					}
				}
			}

			.process-item-footer {
				display: flex;
				align-items: center;
				justify-content: space-between;

				&>text:last-child {
					font-size: 22rpx;
					color: #8b8b8b;
				}
			}
		}
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>