<!-- 任务执行统计卡片组件 -->
<template>
	<div>
		<div class="m-t-2" />
		<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.spider" :label="item.spider"
									:value="item.spider" />
							</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">执行频率: {{ parseCronExpression(task.kwargs.cron) }} </span>
							</el-space>
						</el-form-item>
					</div>
					<div class="wordStyle">
						<el-form-item class="form-item">
							<el-space>
								<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 { ElMessage } from 'element-plus'
import { getSpiderList } from '@/api/system.ts'

const props = defineProps({
	spiderType: {
		type: String,
		default: ''
	},
	failTask: {
		type: String,
		default: ''
	},
	unusualTask: {
		type: String,
		default: ''
	}
})

const taskSelectOptions = ref()
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) => {
	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
	frequency.value = '* * * * * *'
	showTaskDialog.value = true
}
// 获取任务列表的方法
const getData = async () => {
	const res = await getSpiderTaskList({ spiders: searchCondition.value.spiders ? [searchCondition.value.spiders] : [] })
	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 }) })
	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 search = async () => {
	if (searchCondition.value.spiders === '') {
		ElMessage.warning('请先选择爬虫')
		return
	}
	const res = await getSpiderTaskList({ spiders: searchCondition.value.spiders ? [searchCondition.value.spiders] : [], options: JSON.stringify({ jobName: taskName.value }) })
	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
}
// 解析cron表达式的方法
const parseCronExpression = (cronExpression: string) => {
	const res = cronExpression.split('*').length - 1
	if (res >= 5) {
		const aaa = cronExpression.split(' ')
		for (let i = 0; i < aaa.length; i++) {
			if (aaa[i] != '*') {
				if (i == 0) {
					if (aaa[i].length === 3) {
						return `每${aaa[i][2]}秒执行一次`
					} else {
						return `每${aaa[i][2] + aaa[i][3]}秒执行一次`
					}
				} else if (i == 1) {
					if (aaa[i].length === 3) {
						return `每${aaa[i][2]}分钟执行一次`
					} else {
						return `每${aaa[i][2] + aaa[i][3]}分钟执行一次`
					}
				} else if (i == 2) {
					if (aaa[i].length === 3) {
						return `每${aaa[i][2]}小时执行一次`
					} else {
						return `每${aaa[i][2] + aaa[i][3]}小时执行一次`
					}
				} else if (i == 3) {
					if (aaa[i].length === 3) {
						return `每${aaa[i][2]}天执行一次`
					} else {
						return `每${aaa[i][2] + aaa[i][3]}天执行一次`
					}
				} else if (i == 4) {
					if (aaa[i].length === 3) {
						return `每${aaa[i][2]}月执行一次`
					} else {
						return `每${aaa[i][2] + aaa[i][3]}月执行一次`
					}
				}
			}
		}
	}
}
const getSpiderTypeList = async () => {
	const res = await getSpiderList({ scrapydServerId: '1', project: 'spiders' })
	console.log(res,8888888888888);
	taskSelectOptions.value = res.data
	// taskSelectOptions.value = res.data
}
onMounted(() => {
	if (props.spiderType !== '') {
		searchCondition.value.spiders = props.spiderType
	}
	getData()
	getSpiderTypeList()

})


// 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>