<template>
    <div class="task-management">
        <div class="task-header">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                <el-tab-pane :label="t('workbench.task.pendingReview') + ` (${pendingTotal})`" name="pending"
                    class="task-tab-pane">
                </el-tab-pane>
                <el-tab-pane :label="t('workbench.task.saved')" name="saved"></el-tab-pane>
                <el-tab-pane :label="t('workbench.task.myInitiated')" name="myInitiated"></el-tab-pane>
                <el-tab-pane :label="t('workbench.task.reviewed')" name="reviewed" class="task-tab-pane"></el-tab-pane>
            </el-tabs>
            <a class="more-link" @click="handleMore">{{ t('workbench.task.more') }} ></a>
        </div>
        <el-table :data="tableData" border style="width: 100%" @row-click="handleRowClick" v-loading="loading">
            <el-table-column type="index" :label="t('workbench.task.table.index')" width="80" />
            <el-table-column prop="title" :label="t('workbench.task.table.name')" min-width="200">
                <template #default="{ row }">
                    <span class="table-name-link">{{ row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="rootUserName" :label="t('workbench.task.table.initiator')" min-width="120" />
            <el-table-column prop="startTime" :label="t('workbench.task.table.initiationTime')" min-width="180" />
        </el-table>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import {queryMineStarted, queryMineTask} from "/@/api/flow/task";
import {useMessage} from "/@/hooks/message";

const { t } = useI18n();
const router = useRouter();

const props = defineProps<{
    pendingCount?: number;
}>();

const emit = defineEmits<{
    (e: 'tab-change', tab: string): void;
    (e: 'more'): void;
}>();

const activeTab = ref('pending');
const tableData = ref<any[]>([]);
const loading = ref(false);
const pendingTotal = ref(0);
/**
 * 根据任务名称判断类型
 * @param name 任务名称
 * @returns 任务类型
 */
const getTaskType = (name: string): string => {
    if (name.includes('投资申报') || name.includes('项目投资')) {
        return 'investment';
    }
    if (name.includes('专家') || name.includes('专家登记')) {
        return 'expert';
    }
    if (name.includes('投资储备') || name.includes('储备')) {
        return 'reserve';
    }
    if (name.includes('合作单位') || name.includes('合作')) {
        return 'cooperation';
    }
    // 默认类型
    return 'default';
};

/**
 * 根据类型获取审批页面路由
 * @param type 任务类型
 * @param taskId 任务ID
 * @returns 路由路径
 */
const getApprovalRoute = (type: string, taskId: string): string => {
    const routeMap: Record<string, string> = {
        investment: '/invMid/planApplyExamine/index', // 投资申报审批
        expert: '/investment/expertApplyExamine/index', // 专家信息登记审批
        reserve: '/workbench/reserveApproval/index', // 投资储备审批
        cooperation: '/workbench/cooperationApproval/index', // 合作单位审批
        default: '/workbench/approvalDetail', // 默认审批详情页
    };
    const baseRoute = routeMap[type] || routeMap.default;
    return `${baseRoute}?id=${taskId}&type=${type}`;
};

/**
 * 处理表格行点击事件
 * @param row 行数据
 */
const handleRowClick = (row: any) => {
    const taskType = row.type || getTaskType(row.name);
    const taskId = row.taskId || row.id;
    const route = getApprovalRoute(taskType, taskId);

    // 跳转到对应的审批页面
    router.push({
        path: route.split('?')[0],
        query: {
            id: taskId,
            type: taskType,
            tab: activeTab.value, // 传递当前标签页信息，用于返回时定位
        },
    });
};
const getQueryMineTask = (): Promise<any> => {
	return new Promise((resolve, reject) => {
		queryMineTask({
			title: '',
			processName: '',
			taskTime: undefined,
			flowType: '',
			size: 5,
			current: 1
		}).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}
const getQueryMineStarted = () =>{
	return new Promise((resolve, reject) =>{
		queryMineStarted({
			title: '',
			processName: '',
			taskTime: undefined,
			flowType: '',
			size:5,
			current: 1
		}).then(res=>{
			resolve(res)
		}).catch(err=>{
			reject(err)
		})
	})
}
const loadData = async (tab: string) => {
	try {
		let res;
		loading.value = true;
		if (tab === 'pending') {
			const response = await getQueryMineTask()
			res = response?.data?.records
			pendingTotal.value = response?.data?.total || 0
		}
		if (tab === 'myInitiated') {
		const	response = await getQueryMineStarted()
			res = response?.data?.records.map((item:any) =>{
				const userInfo = JSON.parse(item.formData)
				return {
					...item,
					title:item.name,
					rootUserName:userInfo.root[0].name,
					startTime:item.createTime
				}
			})
		}
		tableData.value = res || [];
	}catch (error){
		useMessage().error('数据获取失败！')
	}finally {
		loading.value = false;
	}
};

const handleTabChange = (tab: string) => {
    loadData(tab);
    emit('tab-change', tab);
};

const handleMore = () => {
    emit('more');
};

watch(
    () => props.pendingCount,
    () => {
        // 可以在这里更新待审核数量
    },
    { immediate: true }
);

// 初始加载
loadData('pending');
</script>

<style scoped>
.task-management {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.task-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-shrink: 0;
}

.task-management :deep(.el-table) {
    flex: 1;
}

.table-name-link {
    color: var(--el-color-primary);
    cursor: pointer;
}

.table-name-link:hover {
    text-decoration: underline;
}

:deep(.el-table__row) {
    cursor: pointer;
}

:deep(.el-table__row:hover) {
    background-color: var(--el-table-row-hover-bg-color);
}

.more-link {
    color: var(--el-color-primary);
    cursor: pointer;
    text-decoration: none;
    font-size: 14px;
}

.more-link:hover {
    text-decoration: underline;
}

:deep(.el-tabs__header) {
    margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
    &::after {
        display: none;
    }
}

:deep(.el-tabs__item) {
    padding: 8px 16px !important;
    margin-right: 8px !important;
    border-radius: 20px !important;
    background: #f5f7fa !important;
    color: #606266 !important;
    border: none !important;
    transition: all 0.3s !important;
}

:deep(.el-tabs__item:hover) {
    color: #409eff !important;
    background: #f5f7fa !important;
}

:deep(.el-tabs__item.is-active) {
    background: #409eff !important;
    color: #fff !important;
}

:deep(.el-tabs__item.is-active:hover) {
    background: #409eff !important;
    color: #fff !important;
}

:deep(.el-tabs__active-bar) {
    display: none;
}
</style>
