<script setup lang="ts">
import { getReserveInvestmentProjectsPageAPI, type ReserveInvestmentProjectItem } from '/@/api/investment/reserveRegistration';
import { projectNatureOptions } from '/@/hooks/enums';
import { reactive, ref } from 'vue';
import { useMessage } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
const props = withDefaults(defineProps<{ visible: boolean,isSelect:boolean,selectedId:any }>(), { visible: false,isSelect:false,selectedId:'' });
type ReserveProjectItem = ReserveInvestmentProjectItem & {
	projectMainUnit?: string;
	projectDirection?: string;
	projectStartDate?: string;
	projectEndDate?: string;
	investmentRegion?: string;
	lastUpdateTime?: string;
};
const { t } = useI18n();
const message = useMessage();
const total = ref(0);
const tableData = ref<ReserveProjectItem[]>([]);
const selectedRows = ref<ReserveProjectItem>();
const tableLoading = ref(false);
const queryForm = reactive({
	projectName: '',
	projectMainEntity: '',
	projectNature: '',
	page: 1,
	size: 10,
});
const normalizeReserveProject = (item: ReserveInvestmentProjectItem): ReserveProjectItem => ({
	...item,
	projectMainUnit: item.projectMainEntity,
	projectDirection: item.projectInvestmentDirection,
	projectStartDate: item.projectStartTime,
	projectEndDate: item.projectEndTime,
	investmentRegion: item.investmentArea,
	majorInvestmentProject: item.majorInvestmentProjects ?? item.majorInvestmentProject ?? '',
	keyProject: item.keyProject ?? '',
	lastUpdateTime: item.updateTime || item.createTime || '',
	lastUpdater: item.updateBy || item.createBy || '',
	lastPushStatus: item.status || 'pending',
});

const fetchProjectList = async () => {
	tableLoading.value = true;
	try {
		const payload = {
			page: queryForm.page,
			size: queryForm.size,
			projectName: queryForm.projectName || undefined,
			projectMainEntity: queryForm.projectMainEntity || undefined,
			projectNature: queryForm.projectNature || undefined,
		};
		const res = await getReserveInvestmentProjectsPageAPI(payload);
		const records = (res as any)?.records ?? (res as any)?.data?.records ?? [];
		const totalCount = (res as any)?.total ?? (res as any)?.data?.total ?? 0;
		tableData.value = Array.isArray(records) ? records.map(normalizeReserveProject) : [];
		total.value = Number(totalCount) || 0;
	} catch (error: any) {
		message.error(error?.msg || error?.message || t('common.operateFail') || '获取列表失败');
	} finally {
		tableLoading.value = false;
	}
};
const handleSearch = () => {
	queryForm.page = 1;
	fetchProjectList();
};
const getStatusTagType = (status: ReserveProjectItem['lastPushStatus']) => {
	if (status === 'submitted') return 'success';
	if (status === 'failed') return 'danger';
	return 'info';
};
const handlePageSizeChange = (size: number) =>{
	queryForm.size = size;
	queryForm.page = 1;
	queryForm.projectMainEntity =  '';
	queryForm.projectNature = '';
	queryForm.projectName = '';
	fetchProjectList();
}
const handlePageChange = (page: number) => {
	queryForm.page = page;
	queryForm.projectMainEntity =  '';
	queryForm.projectNature = '';
	queryForm.projectName = '';
	queryForm.size = 10;
	fetchProjectList();
};
const getStatusLabel = (status: ReserveProjectItem['lastPushStatus']) => {
	if (status === 'submitted') return t('reserveLibrary.status.submitted');
	if (status === 'failed') return t('reserveLibrary.status.failed');
	return t('reserveLibrary.status.pending');
};

const handleReset = () => {
	queryForm.projectName = '';
	queryForm.projectMainEntity = '';
	queryForm.projectNature = '';
	queryForm.page = 1;
	fetchProjectList();
};
const handleSelectionChange = (rows: ReserveProjectItem) => {
	selectedRows.value = rows;
};
fetchProjectList()
const emits = defineEmits(['emit:confirm','emit:cancel','emit:select']);
const handleConfirm = ()=>{
	emits('emit:confirm',selectedRows.value);
}
const handleView = (row: ReserveProjectItem) =>{
	selectedRows.value = row;
}
</script>

<template>
	<el-dialog v-model="props.visible" title="项目名称列表" width="80%" v-if="!isSelect">
		<el-row class="toolbar-row mb10">
			<div class="toolbar-right">
				<el-form class="search-form" :inline="true" :model="queryForm" @submit.prevent>
					<el-form-item :label="t('reserveLibrary.form.projectName')">
						<el-input v-model="queryForm.projectName" :placeholder="t('reserveLibrary.placeholder.input')" style="width: 180px" />
					</el-form-item>
					<el-form-item :label="t('reserveLibrary.form.projectMainUnit')">
						<el-input v-model="queryForm.projectMainEntity" :placeholder="t('reserveLibrary.placeholder.input')" style="width: 180px" />
					</el-form-item>
					<el-form-item :label="t('reserveLibrary.form.projectNature')">
						<el-select v-model="queryForm.projectNature" :placeholder="t('reserveLibrary.placeholder.select')" clearable style="width: 160px">
							<el-option v-for="item of projectNatureOptions" :key="item.value" :label="item.label" :value="item.value" />
						</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%;height: 50vh" border @current-change="handleSelectionChange" v-loading="tableLoading">
			<el-table-column width="60" label="选择">
				<template #default="scope">
					<div class="round" :class="{ 'active-row': selectedRows?.id === scope.row.id }"></div>
				</template>
			</el-table-column>
			<el-table-column type="index" :label="t('reserveLibrary.table.index')" width="60" />
			<el-table-column prop="projectName" :label="t('reserveLibrary.table.projectName')" min-width="200" />
			<el-table-column prop="projectMainUnit" :label="t('reserveLibrary.table.projectMainUnit')" min-width="200" />
			<el-table-column prop="investmentCategory" :label="t('reserveLibrary.table.investmentCategory')" min-width="140" />
			<el-table-column prop="projectNature" :label="t('reserveLibrary.table.projectNature')" min-width="140" />
			<el-table-column prop="projectDirection" :label="t('reserveLibrary.table.projectDirection')" min-width="160" />
			<el-table-column prop="projectStartDate" :label="t('reserveLibrary.table.projectStartDate')" min-width="160" />
			<el-table-column prop="projectEndDate" :label="t('reserveLibrary.table.projectEndDate')" min-width="160" />
			<el-table-column prop="investmentRegion" :label="t('reserveLibrary.table.investmentRegion')" min-width="140" />
			<el-table-column prop="majorInvestmentProject" :label="t('reserveLibrary.table.majorInvestmentProject')" min-width="160" />
			<el-table-column prop="keyProject" :label="t('reserveLibrary.table.keyProject')" min-width="120" />
			<el-table-column prop="lastUpdater" :label="t('reserveLibrary.table.lastUpdater')" min-width="140" />
			<el-table-column prop="lastUpdateTime" :label="t('reserveLibrary.table.lastUpdateTime')" min-width="180" />
			<el-table-column prop="lastPushStatus" :label="t('reserveLibrary.table.lastPushStatus')" min-width="160">
				<template #default="{ row }">
					<el-tag :type="getStatusTagType(row.lastPushStatus)" effect="light">
						{{ getStatusLabel(row.lastPushStatus) }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column :label="t('reserveLibrary.table.action')" width="140" fixed="right">
				<template #default="{ row }">
					<el-button link type="primary" @click="handleView(row)">{{ t('common.selectText') || '选择' }}</el-button>
				</template>
			</el-table-column>
		</el-table>

		<template #footer>
				<div class="flex justify-between align-center">
					<div>
						<el-button type="primary" @click="handleConfirm">{{ t('common.confirmB') }}</el-button>
						<el-button @click="()=>{emits('emit:cancel',false)}">{{ t('common.cancelB') }}</el-button>
					</div>
					<el-pagination
						style="margin-top: 0"
						background
						layout="sizes, prev, pager, next, jumper, total"
						:total="total"
						:page-sizes="[10, 20, 50, 100]"
						v-model:page-size="queryForm.size"
						v-model:current-page="queryForm.page"
						@size-change="handlePageSizeChange"
						@current-change="handlePageChange"
					/>
				</div>
		</template>
	</el-dialog>
	<el-select v-else v-model="props.selectedId" @change="(row:any)=>emits('emit:select', row)">
		<el-option v-for="item in tableData" :key="item.id" :label="item.projectName" :value="item" />
	</el-select>
</template>

<style scoped>
.round {
	width: 20px;
	height: 20px;
	border-radius: 50%;
	border: 1px solid var(--el-color-primary);
	cursor: pointer;
}
.active-row {
	background-color: var(--el-color-primary-light-5);
}
</style>
