<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row class="header-summary mb10">
				<div class="title">{{ t('projectLibrary.title') }}</div>
			</el-row>

			<el-row class="toolbar-row mb10">
				<div class="toolbar-left">
					<el-button icon="Download" @click="handleExport">{{ t('common.exportBtn') || '导出' }}</el-button>
					<el-button plain :disabled="!selectedRows.length" icon="Delete" type="primary" :loading="deleteLoading" @click="handleBatchDelete">{{
						t('common.delBtn') || '删除'
					}}</el-button>
				</div>
				<div class="toolbar-right">
					<el-form class="search-form" :inline="true" :model="queryForm" @submit.prevent>
						<el-form-item :label="t('projectLibrary.form.projectName')">
							<el-input v-model="queryForm.projectName" :placeholder="t('projectLibrary.placeholder.input')" style="width: 180px" />
						</el-form-item>
						<el-form-item :label="t('projectLibrary.form.projectMainUnit')">
							<el-input v-model="queryForm.projectMainUnit" :placeholder="t('projectLibrary.placeholder.input')" style="width: 180px" />
						</el-form-item>
						<el-form-item :label="t('projectLibrary.form.projectNature')">
							<el-select v-model="queryForm.projectNature" :placeholder="t('projectLibrary.placeholder.select')" style="width: 160px" clearable>
								<el-option v-for="item in projectNatureOptions" :key="item.value" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="Search" @click="handleSearch">{{ t('common.queryBtn') }}</el-button>
							<el-button icon="Refresh" @click="handleReset">{{ t('common.resetBtn') }}</el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-row>

			<el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="48" />
				<el-table-column type="index" :label="t('projectLibrary.table.index')" width="60" />
				<el-table-column prop="projectName" :label="t('projectLibrary.table.projectName')" min-width="200" />
				<el-table-column prop="projectMainEntity" :label="t('projectLibrary.table.projectMainUnit')" min-width="200" />
				<el-table-column prop="projectOwnerUnit" :label="t('projectLibrary.table.projectOwnerUnit')" min-width="200" />
				<el-table-column prop="constructionNature" :label="t('projectLibrary.table.constructionStage')" min-width="120" >
					<template #default="{ row }">
						{{ constructionStageOptions.find((item: Enums) => item.value === row.constructionNature)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="investmentCategory" :label="t('projectLibrary.table.investmentCategory')" min-width="140">
					<template #default="{ row }">
						{{ getInvestmentCategoryLabel(row.investmentCategory) }}
					</template>
				</el-table-column>
				<el-table-column prop="projectNature" :label="t('projectLibrary.table.projectNature')" min-width="140">
					<template #default="{ row }">
						{{ projectNatureOptions.find((item: Enums) => item.value === row.projectNature)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="projectInvestmentDirection" :label="t('projectLibrary.table.projectDirection')" min-width="160" >
					<template #default="{ row }">
						{{ projectDirectionOptions.find((item: Enums) => item.value === row.projectInvestmentDirection)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="projectStartTime" :label="t('projectLibrary.table.projectImplementationStart')" min-width="160" />
				<el-table-column prop="projectEndTime" :label="t('projectLibrary.table.projectImplementationEnd')" min-width="160" />
				<el-table-column prop="investmentArea" :label="t('projectLibrary.table.investmentRegion')" min-width="140">
					<template #default="{ row }">
						{{ investmentAreaOptions.find((item: Enums) => item.value === row.investmentArea)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="majorInvestmentProjects" :label="t('projectLibrary.table.majorInvestmentProject')" min-width="160" >
					<template #default="{ row }">
						{{ yesOrNo.find((item: Enums) => item.value === row.majorInvestmentProjects)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="keyProject" :label="t('projectLibrary.table.keyProject')" min-width="120">
					<template #default="{ row }">
						{{ projectImportantOptions.find((item: Enums) => item.value === row.keyProject)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="updateTime" :label="t('projectLibrary.table.lastUpdateTime')" min-width="180" />
				<el-table-column prop="reportTime" :label="t('projectLibrary.table.lastReportTime')" min-width="180" />
				<el-table-column prop="createBy" :label="t('projectLibrary.table.lastReporter')" min-width="140" />
				<el-table-column prop="lastPushStatus" :label="t('projectLibrary.table.lastPushStatus')" min-width="160">
					<template #default="{ row }">
						<el-tag :type="getStatusTagType(row.status)" effect="light">
							{{ getStatusLabel(row.status) }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column :label="t('projectLibrary.table.action')" width="250" fixed="right">
					<template #default="{ row }">
						<el-button link type="primary" @click="handleView(row)">{{ t('common.viewBtn') || '查看' }}</el-button>
						<el-button link type="warning" @click="handleReportCurrentYear(row)">{{ t('projectLibrary.action.reportCurrentYear') }}</el-button>
					</template>
				</el-table-column>
			</el-table>

			<div class="mt15 flex justify-end pagination-wrapper">
				<el-pagination
					background
					layout="sizes, prev, pager, next, jumper, total"
					:total="total"
					:page-sizes="[10, 20, 50, 100]"
					v-model:page-size="queryForm.pageSize"
					v-model:current-page="queryForm.page"
					@size-change="handlePageSizeChange"
					@current-change="handlePageChange"
				/>
			</div>
		</div>

		<el-drawer
			v-model="detailDrawerVisible"
			class="project-detail-drawer"
			direction="rtl"
			size="70%"
			:with-header="false"
			:close-on-click-modal="false"
		>
			<div class="detail-header">
				<span class="detail-title">{{ t('projectLibrary.detail.title') }}</span>
				<el-button class="close-btn" link icon="Close" @click="detailDrawerVisible = false" />
			</div>
			<div class="detail-content">
				<ProjectPlanApplyFormDetails v-model="detailFormData" />
			</div>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { ProjectPlanApplyFormData, ProjectPlanApplyFormItem } from '/@/components/investment/interface/types';
import {constructionStageOptions, Enums, projectDirectionOptions, yesOrNo} from '/@/hooks/enums';
import type { investmentProjectsPlanList, ProjectLibraryDetailT } from '/@/views/invMid/projectLibrary/interface/types';
import {
	investmentProjectsPlanDelete, investmentProjectsPlanGetById, investmentProjectsPlanPage,
	investmentProjectsPlanPush
} from '/@/api/investment/investmentManagement';
import {useRouter} from "vue-router"
import { investmentCategoryOptions, projectNatureOptions, investmentAreaOptions, projectImportantOptions } from '/@/hooks/enums';
import ProjectPlanApplyFormDetails from '/@/components/investment/common/ProjectPlanApplyFormDetails.vue';
const deleteLoading = ref(false);
const router = useRouter()
/**
 * 创建空的详情表单对象
 * @returns {ProjectPlanApplyFormData} 返回初始化的表单数据对象
 */
const createEmptyDetail = (): ProjectPlanApplyFormData => ({
	entity: {
		projectName: '',
		projectNature: '',
		groupCompany: '',
		projectOwnerUnit: '',
		projectMainEntity: '',
		projectDepartment: '',
		investmentCategory: '',
		investmentArea: '',
		projectAddress: '',
		projectAddressDetail: '',
		projectInvestmentDirection: '',
		totalInvestment: '',
		investmentDirectionSegmentation: '',
		projectBackground: '',
		constructionNature: '',
		constructionStage: '',
		keyProject: '',
		isMainBusiness: '',
		mainBusinessTypes: '',
		mainBusinessCode: '',
		isManufacturingIndustry: '',
		isStuckIndustry: '',
		urbanStrategy: '',
		projectSource: '',
		majorInvestmentProjects: '',
		isStrategicEmergingIndustries: '',
		projectStartTime: '',
		projectEndTime: '',
		projectConstructionContent: '',
		planInvestmentYear: '',
		annualPlanTotal: '',
		annualPlanInvestment: '',
		planPaymentLimit: '',
		plannedImageAmount: '',
		ownedFunds: '',
		financialFunds: '',
		externalFunding: '',
		externalRaisedCapital: '',
		otherFunds: '',
		governmentFundSourceDesc: '',
		otherFundSourceDesc: '',
		projectTotalAmount: '',
		lastYearCompleted: '',
		ourInvestmentTotalAmount: '',
		ourLastYearCompleted: '',
		projectDesc: '',
		promotionPlan: '',
		projectPreliminaryPlan: '',
		projectPreliminaryPlanAttachment: '',
		attachments: [],
		remark: '',
		decisionType: '',
		isProjectApprovalCompleted: '',
		isDecisionProcedureCompleted: '',
		projectApprovalFileNo: '',
		projectApprovalFileInfo: '',
		decisionProcedureFileNo: '',
		decisionFileInfo: '',
		submitUnitOpinion: '',
		groupInvestmentDeptOpinion: '',
		submitUnitLeadershipOpinion: '',
		submitUnitMainLeadershipOpinion: '',
		processInstanceId:'',
		status:0,
		deptId:0,
	},
	investmentProjects: [
		{
			plannedInvestmentYear: '',
			plannedImageAmount: '',
			plannedPaymentAmount: '',
			selfFunding: '',
			externalFunding: '',
			fiscalFunding: '',
			otherFunding: '',
			fiscalFundingSource: '',
			otherFundingSource: '',
		},
	],
});

const { t } = useI18n();
const message = useMessage();

const queryForm = reactive<investmentProjectsPlanList>({
	page: 1,
	size: 10,
	projectName: '',
	projectMainEntity: '',
	projectNature: '',
	majorInvestmentProjects: '',
});

const total = ref(0);
const tableData = ref<ProjectPlanApplyFormItem[]>([]);
const selectedRows = ref<ProjectLibraryDetailT[]>([]);
const detailDrawerVisible = ref(false);
const detailFormData = reactive<ProjectPlanApplyFormData>(createEmptyDetail());

const resetDetailForm = () => {
	const empty = createEmptyDetail();
	Object.assign(detailFormData, empty);
	if (detailFormData.investmentProjects) {
		detailFormData.investmentProjects.splice(0, detailFormData.investmentProjects.length);
		detailFormData.investmentProjects.push({
			plannedInvestmentYear: '',
			plannedImageAmount: '',
			plannedPaymentAmount: '',
			selfFunding: '',
			externalFunding: '',
			fiscalFunding: '',
			otherFunding: '',
			fiscalFundingSource: '',
			otherFundingSource: '',
		});
	}
};

/**
 * 获取列表数据
 * 发起请求获取投资项目计划分页数据
 */
const getDataList = async () => {
	const res = await investmentProjectsPlanPage(queryForm as any);
	tableData.value = res.data.records;
	total.value = res.data.total || 0;
};

/**
 * 处理搜索事件
 * 重置页码为第一页并重新获取数据
 */
const handleSearch = () => {
	queryForm.page = 1;
	getDataList();
};

/**
 * 处理重置事件
 * 清空查询条件并重新获取数据
 */
const handleReset = () => {
	queryForm.projectName = '';
	queryForm.projectMainEntity = '';
	queryForm.projectNature = '';
	queryForm.majorInvestmentProjects = '';
	queryForm.page = 1;
	getDataList();
};

/**
 * TODO
 * 处理导出事件
 * 显示导出提示信息
 */
const handleExport = () => {
	message.info(t('projectLibrary.message.exportInfo'));
};

/**
 * 处理批量删除事件
 * 删除选中的数据项并在删除成功后刷新列表
 */
const handleBatchDelete = () => {
	if (!selectedRows.value.length) return;
	useMessageBox()
		.confirm(t('common.deleteMessage.confirm'))
		.then(() => {
			deleteLoading.value = true;
			investmentProjectsPlanDelete(selectedRows.value.map((item) => item.id))
				.then(() => {
					deleteLoading.value = false;
					message.success(t('common.deleteMessage.success'));
					getDataList();
				})
				.catch((err: any) => {
					deleteLoading.value = false;
					message.error(err.msg);
				});
		});
};

/**
 * 处理选择变更事件
 * 当表格选择项发生变化时更新已选项状态
 * @param {ProjectLibraryDetailT[]} rows - 当前选中的行数据数组
 */
const handleSelectionChange = (rows: ProjectLibraryDetailT[]) => {
	selectedRows.value = rows;
};

/**
 * 处理查看详情事件
 * 根据指定行数据获取详细信息并显示在抽屉中
 * @param {ProjectLibraryDetailT} row - 当前行数据对象
 */
const handleView = (row: ProjectLibraryDetailT) => {
	resetDetailForm();
	investmentProjectsPlanGetById(row.id).then((res) => {
		Object.assign(detailFormData.investmentProjects, res.data.projectInvestmentEntities || []); // 年度投资计划
		Object.assign(detailFormData.entity, res.data); // 项目详情
	});
	detailDrawerVisible.value = true;
};
// /**
//  * 更新项目详情
//  * 跳转到项目计划申请页面
//  * */
// const handleEdit = (row: ProjectLibraryDetailT) => {
// 	router.push({
// 		path: '/invMid/planApply/index',
// 		query: {
// 			id: row.id,
// 		},
// 	});
// }
/**
 * 处理当前年度报告事件
 * 对指定项目执行当年报告操作
 * @param {ProjectLibraryDetailT} row - 当前行数据对象
 */
const handleReportCurrentYear = (row: ProjectLibraryDetailT) => {
	investmentProjectsPlanPush(row.id).then(() => {
		message.success(`推送成功`,);
	}).catch((err: any) => {
		message.error(err.msg);
	});
};

/**
 * 处理页码变更事件
 * 切换页面时更新当前页码并重新获取数据
 * @param {number} page - 目标页码
 */
const handlePageChange = (page: number) => {
	queryForm.page = page;
	getDataList();
};

/**
 * 处理页面大小变更事件
 * 调整每页显示条数时更新页面设置并重新获取数据
 * @param {number} size - 每页显示条数
 */
const handlePageSizeChange = (size: number) => {
	queryForm.size = size;
	queryForm.page = 1;
	getDataList();
};

/**
 * TODO
 * 获取状态标签类型
 * 根据推送状态返回对应的标签类型
 * @param {number} status - 推送状态
 * @returns {string} Element Plus标签类型(success/danger/info等)
 */
const getStatusTagType = (status: number) => {
	if (status === 1) return 'success';
	if (status === 0) return 'info';
	return 'info';
};

/**
 * 获取状态标签文本
 * 根据推送状态返回对应的显示文本
 * @param {any} status - 推送状态
 * @returns {string} 状态对应显示文本
 */
const getStatusLabel = (status: number) => {
	if (status === 1) return t('projectLibrary.status.submitted');
	if (status === 0) return t('projectLibrary.status.pending');
	return t('projectLibrary.status.pending');
};
/**
 * 投资类别
 * getInvestmentCategoryLabel
 * */
const getInvestmentCategoryLabel = (num: number | string) => {
	if (typeof num === 'number') num = num.toString();
	return investmentCategoryOptions.find((item) => item.value === num)?.label || '';
};
getDataList();
</script>

<style scoped>
.header-summary .title {
	margin: 0 auto;
	font-size: 20px;
	font-weight: 600;
	text-align: center;
}

.toolbar-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.toolbar-left {
	display: flex;
	align-items: center;
	gap: 12px;
}

.toolbar-right {
	display: flex;
	align-items: center;
}

.search-form :deep(.el-form-item) {
	margin-bottom: 0;
}

.pagination-wrapper {
	width: 100%;
}

.project-detail-drawer {
	--el-drawer-border-radius: 0;
}

.project-detail-drawer .detail-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 20px;
	border-bottom: 1px solid var(--el-border-color);
}

.detail-title {
	font-size: 18px;
	font-weight: 600;
	color: var(--el-text-color-primary);
}

.detail-content {
	padding: 0 20px 20px;
	overflow: auto;
	height: calc(100% - 48px);
}

.el-form-item--default {
	margin-bottom: 0;
}

.el-form.el-form--inline .el-form-item--default.el-form-item:last-of-type,
.el-form.el-form--inline .el-form-item--small.el-form-item:last-of-type {
	margin-bottom: 0 !important;
}
</style>
