<template>
	<!-- 头部 -->
	<nav-bar height="328" backPath="workspace" title="材料采集" :filterPickerData="state.filterPickerData" :tabList="state.tabList" :onlyTitle="false" :showFilterPicker="true" :showTabs="true" rightWidth="0rpx" @CommonFilterData="CommonFilterData">
		<template #tabs_right_content>
			<view class="add_btn" @click="handleAddEdit('add')">
				<image class="add_icon" src="@/static/image/icon/plusempty.png"></image>
				<text class="add_text">新建</text>
			</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>
							<view class="need_shenhe" v-if="item.auditMechanism">
								<text>审</text>
							</view>
							<text class="meta_text textLength">{{ truncateText(item.departmentName, 5) }}</text>
							<text class="meta_text textLength">{{ truncateText(item.materialCategoryName, 5) }}</text>
							<text class="meta_text">{{ truncateText(item.createdBy, 5) }}</text>
						</view>
					</view>
					<!-- 任务底部 -->
					<view class="item_bottom">
						<view class="notice_stats">
							<text class="stats_text" v-if="item.taskStatus === 0">开始时间：{{ item.startTime }}</text>
							<text class="stats_text" v-else-if="item.taskStatus === 1">剩余时间：{{ remainingDays(item.endTime) }}天</text>
							<text class="stats_text" v-else>结束时间：{{ item.endTime }}</text>
						</view>
						<view class="notice_actions">
							<view class="action_btn delete" :class="{ disable: !!item.submitNum }" @click="handleDelete(item)">
								<text>删除</text>
							</view>
							<view class="action_btn edit" @click="handleAddEdit('edit',item)">
								<text>编辑</text>
							</view>
							<view class="action_btn edit" :class="{ disableLock: item.taskStatus === 0 }" @click="handleDetail(item.taskStatus,item.id)">
								<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>
	<!-- 删除确认框 -->
	<popupDialog ref="popupDelDialogRef" :showFootBorder="true" :content="state.popupDelDialog.content" @DialogConfirm="DialogDelConfirm" />
</template>

<script setup>
import { reactive,ref,nextTick, onMounted,onUnmounted } from 'vue';
import navBar from '@/components/navBar.vue';
import popupDialog from '@/components/popupDialog.vue';
import {findCollectionTask,getSchoolYearList,getCategoryList,deleteCollectionTask} from '@/reqApi/notification.js';
import { truncateText,remainingDays } from '@/common/common.js';
import { onShow } from '@dcloudio/uni-app';

const state = reactive({
	filterPickerData: [{
		valueIndex:0,//默认值索引
		defaultValue:'',//默认值
		list:[]
	},{
		valueIndex:0,//默认值索引
		defaultValue:'',//默认值
		list:[]
	},{
		valueIndex:0,//默认值索引
		defaultValue:'',//默认值
		list:[]
	}],
	tabList: [{//0-待开始 1-进行中 2-已结束 全部-null
		label: '全部',
		value: ''
	}, {
		label: '待开始',
		value: 0
	}, {
		label: '进行中',
		value: 1
	}, {
		label: '已结束',
		value: 2
	}],
	params:{//参数
		schoolYearCode: '',//学年
		schoolYearId:'',//学年id
		departmentId:'',//归属部门
		materialCategory:'',//材料类目
		taskName:'',//任务名称
		taskStatus:null,//任务状态 0-待开始 1-进行中 2-已结束 全部-null
		pageSize: 30,
		pageNum: 1,
	},
	pageList:[],//列表数据
	scrollTop:0,
	oldScrollTop:0,
	isRefreshing:false,//设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
	isLoading:true,//加载中
	noMoreData:false,//没有更多数据了
	loadStatus:'more',//loading状态
	popupDelDialog:{//删除确认框
		content:'',
		id:''
	}
})
const popupDelDialogRef = ref(null);
const statusClassMap = {
	0: 'status_pending',
	1: 'status_published',
	2: 'status_closed'
};
const taskStatusMap = {
	0: '待开始',
	1: '进行中',
	2: '已结束'
};
// 学年学期列表
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.taskStatus = tabsSelected;//任务状态 0-待开始 1-进行中 2-已结束 全部-null
	}
	OnLoadData(true);
}
/*
*任务列表
* initPage:初始分页 从第一开始
*/
const OnLoadData = (initPage) => {
	// uni.showLoading({
	// 	title: '加载中'
	// });
	if (initPage) state.params.pageNum = 1;//如果是下拉刷新、重新查询 默认加载第一页
	state.isLoading = true;
	state.loadStatus = 'loading';
	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: state.params.pageSize
	};
	findCollectionTask(params).then(res=>{
		if (res.code == 200) {
			const total = Number(res?.data?.total) || 0;//总数
			const pages = Math.ceil(total / state.params.pageSize);//总页数
			const recordsData = res?.data?.records || []
			state.pageList = initPage ? recordsData : [...state.pageList,...recordsData];
			state.noMoreData = state.params.pageNum == pages;
			state.params.pageNum++;
		}
	}).finally(()=>{
		// uni.hideLoading();
		state.isLoading = false;
		state.isRefreshing = false;//下拉刷新未被触发
		if(state.noMoreData){
			state.loadStatus = 'no-more';
		}else{
			state.loadStatus = 'more';
		}
		//返回到页面顶部
		if(initPage){
			GoTop();
		}
	});
};
// 自定义下拉刷新被触发	 下拉刷新
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 handleDelete = (item) => {
	if(!!item.submitNum) return false
	state.popupDelDialog.content = `确定要删除当前任务吗？`;
	state.popupDelDialog.id = item.id;
	popupDelDialogRef.value.OpenDialog();
}
//确定删除
const DialogDelConfirm = () => {
	deleteCollectionTask(state.popupDelDialog.id).then(res=>{
		if(res.code == 200){
			uni.showToast({
				title: '删除成功!',
				icon: 'none'
			});
			OnLoadData(true);
		}else{
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
		}
	})
}
//新建、编辑
const handleAddEdit = (type,item) => {
	uni.removeStorageSync('taskTargetsTreeData');//移除缓存
	uni.navigateTo({
		url: `/pages/materialCollection/taskOverview/addEdit?taskId=${item?.id || ''}`
	});
};
//查看任务
const handleDetail = (taskStatus,id) => {
	if (taskStatus === 0) return;
	uni.navigateTo({
		url: `/pages/materialCollection/taskOverview/taskDetail?taskId=${id}&taskStatus=${taskStatus}`
	});
};
onMounted(async () => {
	await fetchSchoolYearList();//学年学期列表
	fetchCategoryList();//归属分类
	OnLoadData(true);
});
onShow(()=>{
	const isLoadCollectTaskOverview = uni.getStorageSync('isLoadCollectTaskOverview');
	if(isLoadCollectTaskOverview){
		OnLoadData(true);
	}
})
onUnmounted(()=>{
	uni.setStorageSync('isLoadCollectTaskOverview', false);
	uni.removeStorageSync('taskTargetsTreeData');//移除缓存
})
</script>

<style lang="scss" scoped>
.page_content{
	height: calc(100% - 464rpx);
	.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;
				}
			}
			.need_shenhe {
				width: 48rpx;
				height: 48rpx;
				background: rgba(245,108,108,0.1);
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				font-size: 24rpx;
				color: #F56C6C;
				display: inline-flex;
				align-items: center;
				justify-content: center;
			}
			.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;

			.stats_text {
				font-size: 24rpx;
				color: #999999;

				&:first-child {
					margin-right: 32rpx;
				}
			}
		}

		.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;
				}
			}
			
		}
	}

	&:last-child {
		margin-bottom: 0;
	}
}
: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;
	}
	
}
.add_btn{
	width: 148rpx;
	height: 72rpx;
	background-color: #2E64FA;
	border-radius: 8rpx;
	border: 2rpx solid #2E64FA;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	.add_icon{
		width: 28rpx;
		height: 28rpx;
		margin-right: 8rpx;
	}
	.add_text{
		font-weight: 500;
		font-size: 28rpx;
		color: #FFFFFF;
	}
}
</style>
