<!-- 任务执行统计卡片组件 -->
<template>
	<div>
		<div class="text-left p-4 toolbarStyle ">
			<div class="formStyle">
				<el-form inline>
					<el-form-item>
						<el-text class="mx-1" style="color: #fff;">所属爬虫:</el-text>
					</el-form-item>
					<el-form-item>
						<div>
							<el-select v-model="searchCondition.spiders" placeholder="请选择" style="width: 220px">
								<el-option v-for="item in taskSelectOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</div>
					</el-form-item>
					<!-- <el-form-item>
					<el-text class="mx-1" style="color: #fff;">任务名称:</el-text>
				</el-form-item>
				<el-form-item>
					<el-input v-model="taskName" placeholder="请输入" style="width: 220px" />
				</el-form-item> -->
					<el-form-item>
						<el-space>
							<el-button type="primary" @Click="search">查询</el-button>
							<el-button type="primary" @Click="resetData">重置列表</el-button>
							<el-button type="primary" @click="openTaskDialog">新建任务</el-button>
						</el-space>
					</el-form-item>
				</el-form>
			</div>
		</div>

		<div class="cardStyle">
			<div class="taskCard p-6" v-for="task in taskList" :key="task.taskId">
				<div class="taskContent">
					<div>
						<el-form-item class="form-item">
							<span class="titleStyle">{{ task.kwargs.options === '' ? '无名称' : JSON.parse(task.kwargs.options).jobName
							}}</span>
						</el-form-item>
					</div>
					<div>
						<el-form-item class="form-item">
							<el-button type="primary" @click="editTask(task)" class="editButton">编辑</el-button>
							<el-button type="success" @click="goToTaskRecord" class="recordButton">执行记录 </el-button>
							<el-button type="danger" @click="deleteTask(task)" class="deleteButton">删除</el-button>
						</el-form-item>
					</div>
					<div class="wordStyle">
						<el-form-item class="form-item">
							<el-space>
								<span class="wordStyle">启用/停止: </span>
								<el-switch v-model="task.status" :active-value="'running'" :inactive-value="'paused'"
									@change="(newStatus: any) => changeStatus(task, newStatus)" />
							</el-space>
						</el-form-item>
					</div>
					<div class="wordStyle">
						<el-form-item class="form-item">
							<el-space>
								<span class="wordStyle">执行频率: {{ task.frequency }} </span>
								<span class="wordStyle">执行次数: {{ task.count }} </span>
							</el-space>
						</el-form-item>
					</div>
					<div class="wordStyle">
						<el-form-item class="form-item">
							<el-space>
								<span class="wordStyle">所属爬虫: {{ task.kwargs.spider }}</span>
							</el-space>
						</el-form-item>
					</div>
					<!-- <div class="wordStyle">
						<el-form-item class="form-item">
							<el-space>
								<span class="wordStyle">失败次数: </span>
								<span class="wordStyle">异常记录: </span>
							</el-space>
						</el-form-item>
					</div> -->
				</div>
			</div>
		</div>

		<addTaskDialog v-model:dialogVisible="showTaskDialog" @confirm="handleEdit" :mode="editMode" @getTaskList="getData"
			:jobId="jobId" :cron="frequency" :spiderType="belongSpiderType" :options="taskOptions" />

		<deleteDialog v-model:dialogVisible="showDeleteDialog" @get-user-list="getData" :jobId="jobId" />
	</div>




</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import addTaskDialog from './addTaskDialog.vue'
import { getSpiderTaskList, resumeSpiderTask, pauseSpiderTask, getTaskCount } from '@/api/spiderTask'
import { DeleteMode } from '@/components/Delete/enum.ts'
import { AddMode } from './enum'
import deleteDialog from './deleteDialog.vue'
import { CronExpressionParser } from 'cron-parser';
import { log } from 'echarts/types/src/util/log.js'
const props = defineProps({
	spiderType: {
		type: String,
		default: ''
	},
	failTask: {
		type: String,
		default: ''
	},
	unusualTask: {
		type: String,
		default: ''
	}
})
const taskSelectOptions = [
	{
		value: 'api_spider',
		label: 'api_spider',
	},
	{
		value: 'dsn_now',
		label: 'dsn_now',
	},
	{
		value: 'itu_space_explorer',
		label: 'itu_space_explorer',
	},
]
const searchCondition = ref({
	spiders: '',
	options: ''
})
const belongSpider = ref('')
const taskName = ref('')
const taskValue = ref('')
const belongSpiderType = ref('')
const router = useRouter()
const frequency = ref('')
const editMode = ref(AddMode.UPDATE_TASK)
const deleteMode = ref(DeleteMode.SINGLE_DELETE)
const showDeleteDialog = ref(false)
const showTaskDialog = ref(false)
const taskSwitch = ref(false)
const taskOptions = ref('')
const jobId = ref('')
const taskList = ref<any[]>([])

const deleteTask = (task: any) => {
	console.log(task);
	jobId.value = task.id
	deleteMode.value = DeleteMode.SINGLE_DELETE
	showDeleteDialog.value = true
}
const editTask = (task: any) => {
	jobId.value = task.id
	taskOptions.value = JSON.stringify(JSON.parse(task.kwargs.options))
	belongSpiderType.value = task.kwargs.spider
	frequency.value = task.kwargs.cron
	editMode.value = AddMode.UPDATE_TASK
	showTaskDialog.value = true
	// console.log(JSON.stringify(JSON.parse(task.kwargs.options)));

}
const goToTaskRecord = () => {
	router.push({
		path: '/osTaskRecord/list',
		query: {
			jump: 'yes',
			mode: '任务信息'
		}
	})
}
const changeStatus = async (task: any, newStatus: string) => {
	if (newStatus === "running") {
		await resumeSpiderTask({ job_id: task.id });
	} else if (newStatus === "paused") {
		await pauseSpiderTask({ job_id: task.id });
	}
	// await getData();
};
const handleEdit = () => {

}
const openTaskDialog = () => {
	editMode.value = AddMode.ADD_TASK
	showTaskDialog.value = true
}
const getData = async () => {
	const res = await getSpiderTaskList({ spiders: searchCondition.value.spiders ? [searchCondition.value.spiders] : [] })
	// for (let i = 0; i < res.data.length; i++) {
	// 	const resId = await getTaskCount({id:res.data[i].id})
	// 	res.data[i].count = resId.data.count
	// }
	const resId = await getTaskCount({})
	for(let i = 0; i < res.data.length; i++){
		res.data[i].count = resId.data[res.data[i].id] === undefined ? 0 : resId.data[res.data[i].id]
	}
	taskList.value = res.data

}
const resetData = async () => {
	searchCondition.value.spiders = ''
	const res = await getSpiderTaskList({ spiders: [], options: JSON.stringify({ jobName: taskName.value }) })
	taskList.value = res.data
}
const search = async () => {
	const res = await getSpiderTaskList({ spiders: searchCondition.value.spiders ? [searchCondition.value.spiders] : [], options: JSON.stringify({ jobName: taskName.value }) })
	taskList.value = res.data
}
onMounted(() => {
	if (props.spiderType !== '') {
		searchCondition.value.spiders = props.spiderType
	}
	getData()
	const interval = CronExpressionParser.parse('*/2 * * * *');
	console.log(interval);

})


// const parseCronExpression=(cronExpression: string)=> {
//   try {
//     const interval = cronParser.parseExpression(cronExpression);
//     const nextDate = interval.next().toDate();
//     const hours = nextDate.getHours();
//     const minutes = nextDate.getMinutes();
//     const seconds = nextDate.getSeconds();
//     return {
//       hours,
//       minutes,
//       seconds
//     };
//   } catch (err) {
//     console.error('Error parsing cron expression:', err);
//     return null;
//   }
// }
</script>

<style lang="scss" scoped>
.cardStyle {
	display: flex;
	flex-wrap: wrap;
	margin-top: 1.5%;
	padding: 18px;
	gap: 15px;
	width: auto !important;
	justify-content: space-between;
}



.taskContent {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
	gap: 6px;
	/* 进一步减小项目之间的间距 */
	padding: 5px 0;
}

/* 任务卡片样式 */
.taskCard {
	margin-left: 1%;
	background-image: url("@/assets/picture/box2.png");
	background-size: 100% 100%;
	background-repeat: no-repeat;
	margin-bottom: 10px;
	width: 380px;
	font-size: 20px;
	min-height: 240px;
	border-radius: 7px;
	display: flex;
	flex-direction: column;

}

/* 减小表单的间距 */
.form-item {
	margin-bottom: 3px !important;
}

.taskCard .titleStyle {
	font-size: 22px;
	color: #FFFFFF;
}

.taskCard .wordStyle {
	font-size: 16px;
	color: #FFFFFF;
}

/* 按钮样式微调 */
.editButton,
.recordButton,
.deleteButton {
	margin: 0 3px !important;
}


/* 工具栏样式 */
.toolbarStyle {
	background-image: url("@/assets/picture/box3.png");
	background-size: 100% 100%;
	background-repeat: no-repeat;
}

/* 表单样式 */
.formStyle {
	display: flex;
	justify-content: space-around;
	margin-top: 0.5%;
	padding: 2px;
}

// 去除按钮边框
.el-button:focus {
	outline: none;
	color: #ffffff;
	border: none;
}
</style>

<style>
/* .el-button{
	color: #ffffff;
	border: none;
} */

.el-input {
	color: #FFFFFF;
}

.el-select__placeholder {
	color: #FFFFFF;
}
</style>