<template>
	<!-- 头部 -->
	<nav-bar height="400" backPath="workspace" title="材料采集" :filterPickerData="state.filterPickerData" :tabList="state.tabList" :onlyTitle="false" :showFilterPicker="true" :showTabs="true" rightWidth="0rpx" @CommonFilterData="CommonFilterData">
		<template #tabs_top_content>
			<view class="task_status_list">
				<view :class="['item_status',{'active':item.value==state.params.taskStatus}]" v-for="item in state.taskStatusList" :key="item.value" @click="ChangeTaskStatus(item.value)">{{item.label}}</view>
			</view>
		</template>
	</nav-bar>
	<view class="page_content">
		<scroll-view
		    class="scroll_view_y"
			:scroll-top="state.scrollTop"
			scroll-y="true"
			:refresher-enabled="false" 
			:enable-back-to-top="true"
			:show-scrollbar="false" 
			:scroll-with-animation="true" 
			refresher-default-style="none"
			refresher-background="#F8F9FD" 
			:refresher-triggered="state.isRefreshing" 
			@scrolltolower="OnLoadMore"
			@refresherrefresh="OnRefresh"
			@scroll="OnScroll">
			<view class="refresh_loading" v-if="state.isRefreshing"><uni-load-more status="loading" /></view>
			<view class="notice_list">
				<view v-for="item in state.pageList" :key="item.id" class="notice_item">
					<!-- 任务内容 -->
					<view class="item_content">
						<view class="notice_title_row">
							<image class="notice_icon" src="@/static/image/materialCollection/docIcon.png" mode="aspectFit"></image>
							<text class="notice_title">{{ item.taskName }}</text>
						</view>
						<view class="notice_meta">
							<view class="status_tag" :class="statusClassMap[item.taskStatus] || ''">
								<text>{{ taskStatusMap[item.taskStatus] }}</text>
							</view>
							<text class="meta_text ">{{ truncateText(item.departmentName, 5) }}</text>
							<text class="meta_text ">{{ truncateText(item.materialCategoryName, 5) }}</text>
							<text class="meta_text">{{ truncateText(item.createdBy, 5) }}</text>
						</view>
					</view>
					<!-- 任务底部 -->
					<view class="item_bottom">
						<view class="notice_stats">
							<view class="status_tag" :class="state.params.auditStatus">
								<text>{{ tabStatusClassMap[state.params.auditStatus] }}：{{ item?.taskTargetVos?.length || 0 }}</text>
							</view>
							<text class="stats_text">
								<template v-if="remainingDays(item.endTime) > 0">剩余时间：{{remainingDays(item.endTime) }}天</template>
								<template v-else>结束时间：{{item.endTime }}</template>
							</text>
						</view>
						<view class="notice_actions">
							<view class="action_btn edit" @click="handleDetail(item)">
								<text>查看</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="no_data" v-if="!state.isLoading && state.pageList.length == 0">
				<image class="no_data_img" src="@/static/image/bg/no_data.png"></image>
				<text class="no_data_text">暂无数据</text>
			</view>
			<uni-load-more v-if="state.pageList.length > 0" :status="state.loadStatus" />
		</scroll-view>
	</view>
</template>

<script setup>
import { reactive,ref,nextTick, onMounted,onUnmounted } from 'vue';
import navBar from '@/components/navBar.vue';
import {findTeacherTaskTargetList,getSchoolYearList,getCategoryList} from '@/reqApi/notification.js';
import { truncateText,remainingDays } from '@/common/common.js';

const state = reactive({
	filterPickerData: [{
		valueIndex:0,//默认值索引
		defaultValue:'',//默认值
		list:[]
	},{
		valueIndex:0,//默认值索引
		defaultValue:'',//默认值
		list:[]
	},{
		valueIndex:0,//默认值索引
		defaultValue:'',//默认值
		list:[]
	}],
	tabList: [{
		label: '待提交',
		value: 'notSubmitList'
	}, {
		label: '审核中',
		value: 'notReviewList'
	}, {
		label: '已驳回',
		value: 'reviewReasonList'
	}, {
		label: '已提交',
		value: 'reviewList'
	}],
	taskStatusList:[{
		label:'进行中',
		value:1
	},{
		label:'已结束',
		value:2
	}],
	params:{//参数
		schoolYearCode: '',//学年
		schoolYearId:'',//学年id
		departmentId:'',//归属部门
		materialCategory:'',//材料类目
		taskName:'',//任务名称
		taskStatus:1,//任务状态 1-进行中 2-已结束
		auditStatus:'notSubmitList',//审核状态
		pageSize: 30,
		pageNum: 1,
	},
	pageLists:[],//全部数据
	pageList:[],//列表数据
	pages:0,
	scrollTop:0,
	oldScrollTop:0,
	isRefreshing:false,//设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
	isLoading:true,//加载中
	noMoreData:false,//没有更多数据了
	loadStatus:'more',//loading状态
})
const statusClassMap = {
	0: 'status_pending',
	1: 'status_published',
	2: 'status_closed'
};
const taskStatusMap = {
	0: '待开始',
	1: '进行中',
	2: '已结束'
}
const tabStatusClassMap = {
	'notSubmitList':'待提交',    // 待提交
	'notReviewList':'审核中',     // 审核中
	'reviewReasonList':'已驳回',      // 已驳回
	'reviewList':'已提交'      // 已提交
};
// 学年学期列表
const fetchSchoolYearList = async () => {
	try {
		const res = await getSchoolYearList();
		if (res.data && Array.isArray(res.data)) {
			const resData = res.data;
			state.filterPickerData[0].list = resData.map(item=>({
				...item,
				label:item.schoolYearName,
				value:item.id
			}))
			const schoolYearId = state.filterPickerData?.[0]?.list?.[0]?.value || '';
			const schoolYearCode = state.filterPickerData?.[0]?.list?.[0]?.schoolYearCode || '';
			state.filterPickerData[0].defaultValue = schoolYearId;
			state.params.schoolYearId = schoolYearId;//默认值学年id
			state.params.schoolYearCode = schoolYearCode;//默认值学年code
		}
	} catch (error) {
		console.error('获取学年学期列表失败:', error);
	}
};
// 归属分类
const fetchCategoryList = async () => {
	try {
		const res = await getCategoryList();
		if (res.data && Array.isArray(res.data)) {
			const categoryData = res.data;
			const categoryList = categoryData.map(item=>({
				...item,
				label:item.categoryName,
				value:item.id
			}))
			state.filterPickerData[1].list = [{label:'归属分类',value:''}].concat(...categoryList);
		}
	} catch (error) {
		console.error('获取分类列表失败:', error);
	}
};
//切换条件选择器
const CommonFilterData = (filterOptions,type) => {
	const {searchWord,filterOpts,tabsSelected} = filterOptions;
	const {valueIndex, index,filterPickerValue} = filterOpts;
	if(type == 'filterPicker'){
		state.params.departmentId = filterPickerValue[1];//归属部门
		state.params.materialCategory = filterPickerValue[2];//材料类目
		state.filterPickerData[index].valueIndex = valueIndex;
		if(index == 1){
			state.filterPickerData[2].valueIndex = 0;
			const parentData = state.filterPickerData[1].list;//分类归属
			const childrenData = parentData?.[valueIndex]?.childList || [];//材料类目
			const childrenList = childrenData.map(item=>({
				...item,
				label:item?.categoryName || '',
				value:item?.id ?? ''
			}))
			if(childrenList.length){
				childrenList.unshift({
					label:'材料类目',
					value:''
				})
			}
			state.filterPickerData[2].list = childrenList;
		}else if(index == 0){//学年
			state.params.schoolYearId = filterPickerValue[0];//学年id
			state.params.schoolYearCode = state.filterPickerData?.[index]?.list?.[valueIndex]?.schoolYearCode || '';//学年code
		}
	}else if(type == 'search'){
		state.params.taskName = searchWord;//任务名称
	}else{
		state.params.auditStatus = tabsSelected;//审核状态
	}
	OnLoadData(true);
}
//切换任务状态
const ChangeTaskStatus = (val) => {
	state.params.taskStatus = val;
	OnLoadData(true);
}
/*
*任务列表
* initPage:初始分页 从第一开始
*/
const OnLoadData = (initPage) => {
	// uni.showLoading({
	// 	title: '加载中'
	// });
	state.isLoading = true;
	state.loadStatus = 'loading';
	if (initPage) {
		state.params.pageNum = 1;//如果是下拉刷新、重新查询 默认加载第一页
		state.pageLists = [];
		state.pageList = [];
		const params = {
			schoolYearCode: state.params.schoolYearCode,
			schoolYearId: state.params.schoolYearId,
			departmentId: state.params.departmentId,
			materialCategory: state.params.materialCategory,
			taskName: state.params.taskName,
			taskStatus: state.params.taskStatus,
			pageNum: state.params.pageNum,
			pageSize: 999
		};
		findTeacherTaskTargetList(params).then(res=>{
			if (res.code == 200) {
				const tableData = res?.data?.[state.params.auditStatus] || [];
				state.pageLists = tableData;//全部数据
				const total = tableData?.length || 0;//总数
				state.pages = Math.ceil(total / state.params.pageSize);//总页数
				//默认加载
				state.pageList = state.pageLists.slice(0, state.params.pageSize);
				//没有更多了
				state.noMoreData = state.params.pageNum == state.pages;
				//分页+1
				state.params.pageNum++;
				state.isLoading = false;
				state.isRefreshing = false;//下拉刷新未被触发
				state.loadStatus = state.noMoreData?'no-more':'more';
			}
		}).finally(()=>{
			// uni.hideLoading();
			//返回到页面顶部
			if(initPage){
				GoTop();
			}
		});
	}else{
		const start = (state.params.pageNum - 1) * state.params.pageSize;
		const end = start + state.params.pageSize;
		const list = state.pageLists.slice(start, end);
		state.pageList = [...state.pageList, ...list];
		state.noMoreData = state.params.pageNum == state.pages;
		state.params.pageNum++;
		setTimeout(() => {
			state.isLoading = false;
			state.isRefreshing = false; //下拉刷新未被触发
			state.loadStatus = state.noMoreData?'no-more':'more';
		}, 0)
	}
};
// 自定义下拉刷新被触发	 下拉刷新
const OnRefresh = () =>{
	state.isRefreshing = true;//下拉刷新已经被触发
	OnLoadData(true);
}
//滚动到底部/右边 触发上拉刷新
const OnLoadMore = () => {
	if (state.isLoading || state.noMoreData) return;
	OnLoadData(false);
}
//	滚动时触发
const OnScroll = (e) => {
	state.oldScrollTop = e.detail.scrollTop;
}
//返回到顶部
const GoTop = () => {
	// 解决view层不同步的问题
	state.scrollTop = state.oldScrollTop;
	nextTick(() => {
		state.scrollTop = 0
	});
}
//任务详情
const handleDetail = (item) => {
	state.details = uni.setStorageSync('submitMaterialDetailInfo',item);
	if(item?.taskTargetVos?.length > 1){
		uni.navigateTo({
			url: `/pages/materialCollection/submitMaterial/taskDetail?taskId=${item.id}&auditStatus=${state.params.auditStatus}`
		});
	}else{
		const targetId = item?.taskTargetVos?.[0].id;
		uni.navigateTo({
			url: `/pages/materialCollection/submitMaterial/submitDetail?taskId=${item.id}&targetId=${targetId}`
		});
	}
};
onMounted(async () => {
	await fetchSchoolYearList();//学年学期列表
	fetchCategoryList();//归属分类
	OnLoadData(true);
});
onUnmounted(() => {
	uni.removeStorageSync('submitMaterialDetailInfo');//移除缓存
})
</script>

<style lang="scss" scoped>
.page_content{
	height: calc(100% - 536rpx);
	.scroll_view_y{
		height: 100%;
		.refresh_loading{
			padding: 10rpx 0;
		}
	}
}
.notice_list {
	width: 100%;
	display: flex;
	flex-direction: column;
}
.notice_item {
	background-color: #F9FAFF;
	border-radius: 20rpx;
	margin-top: 24rpx;
	border: 2rpx solid #E4E7ED;
	&:first-child{
		margin-top: 16rpx;
	}

	.item_content {
		padding: 24rpx 16rpx;

		.notice_title_row {
			display: flex;
			align-items: center;
			margin-bottom: 16rpx;

			.notice_icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 16rpx;
			}

			.notice_title {
				flex: 1;
				font-weight: 500;
				font-size: 28rpx;
				color: #333333;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.notice_meta {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			gap: 16rpx;

			.status_tag {
				font-size: 24rpx;
				height: 48rpx;
				width: 96rpx;
				text-align: center;
				line-height: 48rpx;
				border-radius: 4rpx;
				font-weight: 400;
				border-radius: 8rpx;

				&.status_pending {
					background: rgba(46, 100, 250, 0.1);
					color: #2E64FA;
				}

				&.status_published {
					background: rgba(82, 196, 26, 0.1);
					color: #2BC644;
				}

				&.status_closed {
					background: #6666661a;
					color: #666666;
				}
			}
			.meta_text {
				font-size: 24rpx;
				color: #999999;
				line-height: 48rpx;
			}
			.textLength {
				max-width: 160rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}

	.item_bottom {
		border-top: 2rpx solid #E4E7ED;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 16rpx;

		.notice_stats {
			display: flex;
			align-items: center;
			gap: 16rpx;
			.stats_text {
				font-size: 24rpx;
				color: #999999;
			}

			.status_tag{
				font-size: 24rpx;
				text-align: center;
				padding: 8rpx 12rpx;
				// height: 48rpx;
				// line-height: 48rpx;
				font-weight: 400;
				border-radius: 8rpx;
				flex-shrink: 0;
				&.notSubmitList {
					background: rgba(46,100,250,0.1);
					color: #2E64FA;
				}
				&.notReviewList {
					background: rgba(251,159,52,0.1);
					color: #FB9F34;
				}
				&.reviewReasonList {
					background: rgba(245,108,108,0.1);
					color: #F56C6C;
				}
				&.reviewList {
					background: rgba(43,198,68,0.1);
					color: #2BC644;
				}
			}
		}

		.notice_actions {
			display: flex;
			justify-content: flex-end;
			gap: 16rpx;
			flex-shrink: 0;
			.action_btn {
				font-size: 24rpx;
				padding: 12rpx 24rpx;
				border-radius: 8rpx;
				border: 2rpx solid transparent;
				&.delete {
					border-color: #F56C6C;
					color: #F56C6C;
					background-color: #FFFFFF;

					&.disabled {
						border-color: #C0C4CC;
						color: #C0C4CC;
						background-color: #FFFFFF;
					}
				}

				&.edit {
					border-color: #2E64FA;
					color: #2E64FA;
					background-color: #FFFFFF;

					&.disabled {
						border-color: #C0C4CC;
						color: #C0C4CC;
						background-color: #FFFFFF;
					}
				}

				&.disable {
					color: #C0C4CC !important;
					cursor: not-allowed;
					border-color: #C0C4CC !important;
				}
				&.disableLock{
					color: #C0C4CC !important;
					cursor: not-allowed;
					background-color: #F3F3F3 !important;
					border-color: #F3F3F3 !important;
				}
			}
			
		}
	}
}
:deep(.scroll_tabs){
	height: 72rpx;
	align-items: center;
	.scroll_tabs_view{
		height: 56rpx;
	}
}
:deep(.filter_picker){
	gap: 16rpx !important;
	.item_filter_picker{
		width: calc((100% - 16rpx * 2) / 3) !important;
	}
}
.task_status_list{
	margin-top: 24rpx;
	padding: 0 24rpx;
	display: flex;
	width: 100%;
	gap:24rpx 30rpx;
	box-sizing: border-box;
	.item_status{
		flex: 1;
		display: inline-flex;
		justify-content: center;
		align-items: center;
		height: 64rpx;
		background-color: #FFFFFF;
		border-radius: 8rpx;
		border: 2rpx solid #DCDFE6;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		&.active{
			background-color: rgba(46,100,250,0.1);
			border: 2rpx solid #2E64FA;
			color: #2E64FA;
		}
	}
}
</style>
