<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') + ` (${pendingCount})`" 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";
import request from "/@/utils/request";
import {examineDict} from "/@/hooks/enums";

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);


/**
 * 根据类型获取审批页面路由
 * @param type 任务类型
 * @param taskId 任务ID
 * @returns 路由路径
 */
const getApprovalRoute = (type: string, taskId: string): string => {
    const routeMap: Record<string, string> = {
        investment: '/invMid/planApplyExamine/index', // 投资申报审批
        expert: '/workbench/expertApproval/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) => {
		console.log(row);
    const taskId = row.taskId || row.id;
    const route = getApprovalRoute(row.flowType, taskId);
	const routePath = examineDict[row.flowType]
	if (!routePath){
		useMessage().error('未定义的审批类型！')
		return
	}
	console.log(routePath)
    // 跳转到对应的审批页面
    router.push({
        path: routePath,
        query: {
					processInstanceId: row.processInstanceId,
            tab: activeTab.value, // 传递当前标签页信息，用于返回时定位
        },
    });
};
// request('admin/sys/code/list',{
// 	method:'get',
// }).then(res=>{
// 	console.log('test',res)
// })
const getQueryMineTask = () =>{
	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
		}
		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>
