<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row :gutter="20" class="workbench-row mb20">
                <!-- 左侧：快捷入口 -->
                <el-col :span="12" class="workbench-col">
                    <QuickEntry @click="handleQuickEntryClick" />
                </el-col>
                <!-- 右侧：任务管理 -->
                <el-col :span="12" class="workbench-col">
                    <TaskManagement :pending-count="2" @tab-change="handleTabChange" @more="handleMore" />
                </el-col>
            </el-row>
				<!--	项目金额-->
					<el-card class="investment-overview-card" shadow="hover">
						<el-row :gutter="20">
							<el-col :span="12">
								<div class="summary-cards">
									<div v-for="card in summaryCards" :key="card.label" class="summary-card">
										<div class="summary-value">{{ card.value?.toFixed(2) || '0.00' }}{{card.unit}}</div>
										<div class="summary-label">{{ card.label }}</div>
									</div>
								</div>
								<v-chart  class="investment-bar-chart" :option="investmentBarOption" />
							</el-col>
							<el-col :span="12">
								<div class="warning-title">
									<span class="text-[16px] mr-2">{{ t('workbenchPage.warning.title') }}</span>
									<span class="text-[26px]">10 个</span>
								</div>
								<el-card class="h-auto w-auto">
									<div class="completion-header flex justify-between">
										<div class="flex font-bold text-[14px]">
											<div class="header-bar"></div>
											本年度项目数据统计
										</div>
										<div class="header-title">
											<el-select v-model="pieCategory" @change="projectAnnualFn" size="large" class="distribution-select">
												<el-option :label="t('workbenchPage.projectDistribution.selectNature')"
																	 value="nature" />
												<el-option :label="t('workbenchPage.projectDistribution.selectDirection')"
																	 value="direction" />
											</el-select>
										</div>
									</div>
									<div class="completion-body h-[285px]">
										<v-chart  ref="pieChartRef"  class="completion-chart-wrapper" :option="projectAnnualOption" />
										<div class="distribution-list">
											<div class="distribution-item" v-for="(item, index) in textList" :key="item.name">
												<div class="distribution-name">
													<span class="dot" :style="{ backgroundColor: pieColors[index] }"></span>
													{{ item.name }}
												</div>
												<div class="distribution-value">
													{{ item.value }}
													<span class="distribution-rate">{{ formatRate(item.value) }}</span>
												</div>
											</div>
										</div>
									</div>
								</el-card>
							</el-col>
						</el-row>
					</el-card>
					<el-row :gutter="20" class="mt20 completion-modules-row">
						<el-col v-for="item in completionModules" :key="item.title" :span="6">
							<el-card class="completion-module-card" shadow="hover">
								<div class="completion-header">
									<span class="header-bar"></span>
									<span class="header-title">{{ item.title }}</span>
								</div>
								<div class="completion-body">
									<div class="completion-chart-wrapper">
										<v-chart class="completion-ring-chart" :option="item.option" autoresize />
									</div>
									<div class="completion-info">
										<div class="completion-metric">
											<div class="metric-value"  style="color:#409EFF;">{{ item.totalInvestment }} 万元</div>
											<div class="metric-label">{{ t('workbenchPage.completion.totalInvestmentLabel') }}
											</div>
										</div>
										<div class="completion-metric">
											<div class="metric-value"  style="color:#409EFF;">{{ item.annualPlan }} 万元</div>
											<div class="metric-label">{{ t('workbenchPage.completion.annualPlanLabel') }}</div>
										</div>
										<div class="completion-metric">
											<div class="metric-value"  style="color:#409EFF;">{{ item.annualCompleted }} 万元</div>
											<div class="metric-label">{{ t('workbenchPage.completion.annualCompletedLabel') }}
											</div>
										</div>
									</div>
								</div>
							</el-card>
						</el-col>
					</el-row>
<!--					表格-->
					<el-card class="mt20 investment-progress-card" shadow="never">
						<div class="progress-card-header">
							<div class="tab-list-wrapper">
								<div class="tab-list">
									<div v-for="tab in progressTabs" :key="tab.id"
											 :class="['progress-tab', { active: activeProgressTab === tab.id }]"
											 @click="handleProgressTabChange(tab.id)">
										{{ tab.label }}
									</div>
								</div>
							</div>
						</div>
						<el-table :data="filteredProgressData" border style="width: 100%" @row-click="handleProgressRowClick">
							<el-table-column prop="projectName" :label="t('workbenchPage.progress.table.projectName')"
															 min-width="120">
								<template #default="{ row }">
									<el-link type="primary" :underline="false">{{ row.projectName }}</el-link>
								</template>
							</el-table-column>
							<el-table-column prop="department" :label="t('workbenchPage.progress.table.department')"
															 min-width="140" />
							<el-table-column prop="constructionNature"
															 :label="t('workbenchPage.progress.table.constructionNature')" min-width="100" />
							<el-table-column prop="totalInvestment" :label="t('workbenchPage.progress.table.totalInvestment')"
															 min-width="140" />
							<el-table-column prop="cumulativeInvestmentLastYear"
															 :label="t('workbenchPage.progress.table.cumulativeInvestmentLastYear')" min-width="160" />
							<el-table-column prop="planQuota" :label="t('workbenchPage.progress.table.planQuota')"
															 min-width="140" />
							<el-table-column prop="completedQuota" :label="t('workbenchPage.progress.table.completedQuota')"
															 min-width="150" />
							<el-table-column prop="completionRate" :label="t('workbenchPage.progress.table.completionRate')"
															 min-width="120">
								<template #default="{ row }">
									<span>{{ row.completionRate }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="plannedPayment" :label="t('workbenchPage.progress.table.plannedPayment')"
															 min-width="140" />
							<el-table-column prop="cumulativePayment"
															 :label="t('workbenchPage.progress.table.cumulativePayment')" min-width="140" />
							<el-table-column prop="paymentRate" :label="t('workbenchPage.progress.table.paymentRate')"
															 min-width="120" />
						</el-table>
					</el-card>
					<el-card class="mt20 project-investment-plan-card" shadow="never">
						<div class="plan-card-header">
							<div class="plan-title">{{ t('workbenchPage.projectPlan.title') }}</div>
							<el-button text type="primary" class="plan-more-btn" @click="router.push('/invMid/projectLibrary/index')">
								{{ t('workbenchPage.projectPlan.more') }}
								<el-icon class="el-icon--right">
									<ArrowRight />
								</el-icon>
							</el-button>
						</div>
						<el-table :data="projectPlanData" border style="width: 100%" @row-click="handleProjectPlanRowClick">
							<el-table-column prop="projectName" :label="t('workbenchPage.projectPlan.table.projectName')"
															 min-width="120">
								<template #default="{ row }">
									<el-link type="primary" :underline="false">{{ row.projectName }}</el-link>
								</template>
							</el-table-column>
							<el-table-column prop="department" :label="t('workbenchPage.projectPlan.table.department')"
															 min-width="140" />
							<el-table-column prop="mainUnit" :label="t('workbenchPage.projectPlan.table.mainUnit')"
															 min-width="140" />
							<el-table-column prop="projectOverview"
															 :label="t('workbenchPage.projectPlan.table.projectOverview')" min-width="140" />
							<el-table-column prop="investmentDirection"
															 :label="t('workbenchPage.projectPlan.table.investmentDirection')" min-width="120" />
							<el-table-column prop="majorProject" :label="t('workbenchPage.projectPlan.table.majorProject')"
															 min-width="100" />
							<el-table-column prop="projectStartTime"
															 :label="t('workbenchPage.projectPlan.table.projectStartTime')" min-width="160" />
							<el-table-column prop="projectEndTime" :label="t('workbenchPage.projectPlan.table.projectEndTime')"
															 min-width="160" />
							<el-table-column prop="annualPlanImage"
															 :label="t('workbenchPage.projectPlan.table.annualPlanImage')" min-width="130" />
							<el-table-column prop="investmentRegion"
															 :label="t('workbenchPage.projectPlan.table.investmentRegion')" min-width="110" />
							<el-table-column prop="projectTotalInvestment"
															 :label="t('workbenchPage.projectPlan.table.projectTotalInvestment')" min-width="140" />
							<el-table-column prop="cumulativeInvestment"
															 :label="t('workbenchPage.projectPlan.table.cumulativeInvestment')" min-width="160" />
							<el-table-column prop="imageTotal" :label="t('workbenchPage.projectPlan.table.imageTotal')"
															 min-width="120" />
							<el-table-column prop="paymentTotal" :label="t('workbenchPage.projectPlan.table.paymentTotal')"
															 min-width="120" />
							<el-table-column prop="capitalSource" :label="t('workbenchPage.projectPlan.table.capitalSource')"
															 min-width="140" />
							<el-table-column prop="effectiveness" :label="t('workbenchPage.projectPlan.table.effectiveness')"
															 min-width="100" />
							<el-table-column prop="coordination" :label="t('workbenchPage.projectPlan.table.coordination')"
															 min-width="150" />
							<el-table-column prop="nextStep" :label="t('workbenchPage.projectPlan.table.nextStep')"
															 min-width="150" />
							<el-table-column prop="remark" :label="t('workbenchPage.projectPlan.table.remark')"
															 min-width="120" />
						</el-table>
					</el-card>
				</div>
    </div>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue';
import {useI18n} from 'vue-i18n';
import VChart from 'vue-echarts';
import {use} from 'echarts/core';
import {BarChart, PieChart} from 'echarts/charts';
import {GridComponent, LegendComponent, TooltipComponent,TitleComponent ,GraphicComponent} from 'echarts/components';
import {CanvasRenderer} from 'echarts/renderers';
import {useMessage} from '/@/hooks/message';
import QuickEntry from '/@/components/workbench/QuickEntry.vue';
import TaskManagement from '/@/components/workbench/TaskManagement.vue';
import {useRouter} from "vue-router";
import {
	AnnualImage,
	cumulativeImageQuota,
	emergingIndustries,
	plannedImageQuota,
	projectAnnual,
	projectTotal
} from "/@/api/workbench/summaryCards";

use([TooltipComponent, LegendComponent, GridComponent, BarChart, PieChart, CanvasRenderer, TitleComponent,GraphicComponent]);
const router = useRouter();
const { t } = useI18n();
const handleQuickEntryClick = (item: any) => {
    router.push(item.path);
};
const dictionary = ref<string>('pending');
const dictionaryPathMap:{[key:string]:string} = {
	pending:'/workbench/pending-items/index',
	saved:'/workbench/temporaryStorageItems/index',
	myInitiated:'/workbench/my-initiated/index',
	reviewed:'/workbench/reviewed-items/index'
}
const handleTabChange = (path:string) => {
	dictionary.value = path;
};
const handleMore = () => {
	router.push(dictionaryPathMap[dictionary.value]);
};
const summaryCards = ref([
	{ label: '项目总投资金额', value: 0 ,unit:'万元'},
	{ label: '本年计划形象额度', value: 0 ,unit:'万元'},
	{ label: '本年累计完成形象额度', value: 0 ,unit:'万元'},
	{ label: '本年形象完成率', value: 0,unit:'%' },
]);

// 在数据获取后计算完成率
const updateCompletionRate = () => {
	const planValue = summaryCards.value[0].value;
	const finishValue = summaryCards.value[2].value;
	if (planValue && finishValue) {
		summaryCards.value[3].value = ((finishValue / planValue) * 100);
	} else {
		summaryCards.value[3].value = 0;
	}
};
// 获取项目总投资金额
const getProjectTotal = async ()=>{
	try {
		const {data} = await projectTotal();
		summaryCards.value[0].value = data || 0;
	}catch (error:any) {
		useMessage().error(error.msg);
	}
}
// 获取未完成形象额度
const getCompletedImageQuota = async () => {
	try {
		const {data} = await cumulativeImageQuota(); // 获取未完成额度
		// 计算已完成额度：计划额度 - 未完成额度
		summaryCards.value[2].value = summaryCards.value[0].value - (data || 0);
		// 更新完成率
		updateCompletionRate();
	} catch (error: any) {
		useMessage().error(error.msg);
	}
}

const getPlannedImageQuota = async () => {
	try {
		const {data} = await plannedImageQuota();
		summaryCards.value[1].value = data || 0;
		// 在计划额度获取后，重新计算已完成额度
		await getCompletedImageQuota();
	} catch (error: any) {
		useMessage().error(error.msg);
	}
}
getProjectTotal();
getPlannedImageQuota();
// 柱状图
const investmentBarOption = ref({
	color: ['#246EFF', '#00B2FF'],
	tooltip: {
		trigger: 'axis',
		axisPointer: {
			type: 'shadow',
		},
		textStyle: {
			fontSize: 16,
		},
	},
	legend:{
		data: ['本年计划形象总额', '本年累计完成形象总额'],
		left:0,
		itemWidth:10,
		itemHeight:10,
		borderRadius: 5,
	},
	grid: {
		left: '3%',
		right: '4%',
		bottom: '5%',
		containLabel: true,
	},
	xAxis: {
		type: 'category',
		data: [new Date().getFullYear()],
		axisTick: { show: false },
	},
	yAxis: {
		type: 'value',
	},
	series: [
		{
			name: '本年计划形象总额',
			type: 'bar',
			barWidth: 36,
			data: [summaryCards.value[0].value],
			itemStyle: { borderRadius: [4, 4, 0, 0] },
		},
		{
			name: '本年累计完成形象总额',
			type: 'bar',
			barWidth: 36,
			data: [summaryCards.value[2].value],
			itemStyle: { borderRadius: [4, 4, 0, 0] },
		},
	],
});
watch(() => summaryCards.value,(value)=>{
	investmentBarOption.value.series[0].data = [value[0].value];
	investmentBarOption.value.series[1].data = [value[2].value];
},{deep: true, immediate: true})
// 饼图
const pieCategory = ref<'nature' | 'direction'>('nature');
const pieColors = ['#5C7CFA', '#91CC75', '#73C0DE', '#FAC858', '#EE6666'];
const  pieChartRef = ref();
const projectAnnualOption = ref({
	color: pieColors,
	title: {
		text: '总计',
		left: 'center',
		top: '40%',
		textStyle: { fontSize: 12,color:'#737373' },
	},
	series: [
		{
			type: 'pie',
			radius: ['60%', '85%'],
			center: ['50%', '50%'],
			label: { show: false },
			labelLine: { show: false },
			data: [] as { name: string; value: number}[],
		},
	],
	graphic: {
		elements: [{
			type: 'text',
			left: 'center',
			top: '50%',
			style: {
				text: '',
				textAlign: 'center',
				fill: '#333',
				fontSize: 22,
				lineHeight: 28,
				fontWeight: 600,
			},
		}],
	},
});
const textList = ref<any[]>([])
const totalProjects = ref(0);
const projectAnnualFn = (value: string) => {
	projectAnnual(value === 'nature' ? 1 : 2).then((res) => {
		textList.value = res.data.length > 0
				? res.data.map((item: any) => ({ name: item.name, value: item.num }))
				: [
					{ name: '功能性项目', value: 12 },
					{ name: '经营性项目', value: 22 },
					{ name: '综合性项目', value: 12 },
				];
		totalProjects.value = textList.value.reduce((acc, cur) => acc + cur.value, 0);
		projectAnnualOption.value.series[0].data = textList.value;
		projectAnnualOption.value.graphic.elements[0].style.text = `${totalProjects.value}`;
	});
};
const formatRate = (value: number) => {
	const total = totalProjects.value || 1;
	return `${((value / total) * 100).toFixed(1)}%`;
};
projectAnnualFn('nature');
// --------------------------------------
const createCompletionOption = (rateText: string) => {
	const rate = Number(rateText.replace('%', '')) || 0;
	return {
		title: {
			show: true,
			text: `${rate}%`,
			left: 'center',
			top: '45%',
			textStyle: {
				fontSize: 18,
				fontWeight: 600,
				color: '#111827',
			},
		},
		series: [
			{
				type: 'pie',
				radius: ['60%', '85%'],
				center: ['50%', '50%'],
				silent: true,
				label: { show: false },
				labelLine: { show: false },
				data: [
					{
						value: rate,
						itemStyle: {
							color: '#f97316',
						},
					},
					{
						value: 100 - rate,
						itemStyle: {
							color: '#fee2e2',
						},
					},
				],
			},
		],
	};
};

const completionModuleKeys = [
	{ titleKey: 'workbenchPage.completion.modules.strategicEmerging' },
	{ titleKey: 'workbenchPage.completion.modules.functional' },
	{ titleKey: 'workbenchPage.completion.modules.operational' },
	{ titleKey: 'workbenchPage.completion.modules.comprehensive' },
];
const completion = reactive([
	{title: '', totalInvestment:0, annualPlan:0, annualCompleted:0, completionRate:0, option:{},},
	{title: '', totalInvestment:0, annualPlan:0, annualCompleted:0, completionRate:0, option:{},},
	{title: '', totalInvestment:0, annualPlan:0, annualCompleted:0, completionRate:0, option:{},},
	{title: '', totalInvestment:0, annualPlan:0, annualCompleted:0, completionRate:0, option:{},},
]);
const completionModules = computed(() => {
	return completion.map((item,index) => {
		return {
			title: t(completionModuleKeys[index].titleKey),
			totalInvestment:item.totalInvestment,
			annualPlan:item.annualPlan,
			annualCompleted:item.annualCompleted,
			completionRate: item.completionRate,
			option: createCompletionOption(item.completionRate + '%'),
		};
	});
});
const getEmergingIndustries = async () => {
 try {
	const {data} = await emergingIndustries();
	 completion[0] = initPieListItem(0,data);
} catch (error: any) {
	useMessage().error(error.msg);
}
}
getEmergingIndustries();
const getAnnualImage = (index: number,num:1|2|3) =>{
	AnnualImage(num).then((res) => {
		const {data} = res;
		completion[index] = initPieListItem(index,data);
	});
}
getAnnualImage(1,1)
getAnnualImage(2,2)
getAnnualImage(3,3)
function initPieListItem(index:number,data:any):any {
	const item = completion[index]
	return {
		...item,
		totalInvestment: data.projectTotal  || 0,
		annualPlan: data.plannedImageQuota  || 0,
		annualCompleted: data.cumulativeImageQuota || 0,
		completionRate: (item.annualPlan / item.annualCompleted) || 0
	}
}

</script>

<style scoped>
.layout-container .layout-padding {
    height: auto !important;
    overflow: visible !important;
}

.layout-container .layout-padding-view {
    height: auto !important;
    overflow: auto;
}

:deep(.layout-container .layout-padding) {
    height: auto !important;
    overflow: visible !important;
}

:deep(.layout-container .layout-padding-view) {
    height: auto !important;
    overflow: visible !important;
}

.workbench-row {
    display: flex;
    align-items: stretch;
}

.workbench-col {
    display: flex;
    flex-direction: column;
}

.workbench-col>* {
    height: 100%;
}

.investment-overview-card {
    height: 100%;
}

.summary-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin-bottom: 20px;
}

.summary-card {
    background: linear-gradient(135deg, #eef2ff, #f5f8ff);
    border-radius: 12px;
    padding: 16px;
    text-align: center;
    box-shadow: inset 0 0 10px rgba(92, 124, 250, 0.05);
}

.summary-card:nth-child(2) {
    background: linear-gradient(135deg, #e0f2ff, #f1fbff);
}

.summary-card:nth-child(3) {
    background: linear-gradient(135deg, #e8f6f0, #f4fff8);
}

.summary-card:nth-child(4) {
    background: linear-gradient(135deg, #fef5e6, #fffaf2);
}

.summary-value {
    font-size: 20px;
    font-weight: 600;
    color: #5563c1;
}

.summary-label {
    margin-top: 4px;
    color: #707070;
}

.chart-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
}

.investment-bar-chart {
    height: 280px;
}

.chart-legend {
    display: flex;
    gap: 20px;
    margin-top: 12px;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #666;
}

.dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
}

.dot-plan {
    background-color: #5c7cfa;
}

.dot-finish {
    background-color: #91cc75;
}

.project-insight-column {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.warning-title {
    font-size: 16px;
    margin-bottom: 8px;
	height: 60px;
	text-align: center;
	line-height: 60px;
	background-color: #FFF7ED;
	color: #FF3433;
}

.warning-value {
    font-size: 36px;
    font-weight: 700;
}

.warning-value span {
    font-size: 16px;
    margin-left: 4px;
}

.project-distribution-card {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.distribution-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.distribution-title {
    font-size: 16px;
    font-weight: 600;
}

.distribution-select {
    width: 180px;
}

.distribution-body {
    display: flex;
    height: 100%;
}

.project-pie-chart {
    width: 55%;
    height: 260px;
}

.distribution-list {
    width: 45%;
    display: flex;
    flex-direction: column;
    gap: 14px;
    padding-left: 12px;
    border-left: 1px solid var(--el-border-color-lighter);
}

.distribution-item {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: var(--el-text-color-primary);
}

.distribution-name {
    display: flex;
    align-items: center;
    gap: 6px;
}

.distribution-value {
    font-weight: 600;
}

.distribution-rate {
    font-weight: normal;
    margin-left: 6px;
    color: var(--el-text-color-secondary);
}

.completion-modules-row {
    margin-top: 24px;
}

.completion-module-card {
    height: 100%;
}

.completion-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.completion-header .header-bar {
    width: 4px;
    height: 18px;
    background-color: #3b82f6;
    border-radius: 2px;
    margin-right: 8px;
}

.completion-header .header-title {
    font-size: 14px;
    font-weight: 600;
    color: var(--el-text-color-primary);
}

.completion-body {
    display: flex;
    align-items: center;
}

.completion-chart-wrapper {
    width: 40%;
}

.completion-ring-chart {
    width: 100%;
    height: 160px;
}

.completion-info {
    width: 60%;
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding-left: 12px;
}

.completion-rate {
    text-align: left;
}

.completion-rate .rate-value {
    font-size: 20px;
    font-weight: 600;
    color: #111827;
    margin-right: 8px;
}

.completion-rate .rate-label {
    font-size: 12px;
    color: #6b7280;
}

.completion-metric .metric-value {
    font-size: 16px;
    font-weight: 600;
    color: #2563eb;
}

.completion-metric .metric-label {
    font-size: 12px;
    color: #6b7280;
    margin-top: 2px;
}

.investment-progress-card {
    margin-top: 24px;
}

.progress-card-header {
    margin-bottom: 12px;
}

.tab-list-wrapper {
    overflow-x: auto;
    padding-bottom: 4px;
}

.tab-list {
    display: flex;
    gap: 12px;
    min-width: max-content;
}

.progress-tab {
    padding: 6px 18px;
    border: 1px solid var(--el-border-color);
    border-radius: 20px;
    cursor: pointer;
    white-space: nowrap;
    color: var(--el-text-color-regular);
    transition: all 0.2s ease;
    background: #fff;
}

.progress-tab.active {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
    background: rgba(64, 158, 255, 0.08);
}

.plan-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.plan-title {
    font-size: 16px;
    font-weight: 600;
}

.plan-more-btn {
    display: flex;
    align-items: center;
    font-size: 14px;
}
</style>