<template>
	<div class="project-exit-plan-form">
		<div class="form-heading">
			<div class="form-title">{{ t('projectExitPlan.form.title') }}</div>
			<div class="form-meta">
				<div class="meta-item">
					<span>{{ t('projectExitPlan.form.applyDepartmentLabel') }}：</span>
					<el-input v-model="formData.applicationDept" size="small" :placeholder="t('projectExitPlan.placeholder.input')" />
				</div>
				<div class="meta-item">
					<span>{{ t('projectExitPlan.form.applyDateLabel') }}：</span>
					<span>{{new Date().toLocaleDateString('zh-CN')}}</span>
				</div>
			</div>
		</div>

		<el-form :model="formData" :rules="rules" ref="useForm" class="exit-plan-table">
			<el-form-item class="table-row" prop="projectName" required>
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.projectName') }}</div>
				</template>
				<div class="table-cell value project-name-cell">
					<el-input v-model="formData.projectName" :placeholder="t('projectExitPlan.form.projectNamePlaceholder')" readonly>
						<template #suffix>
							<el-icon class="cursor-pointer interactive-icon" @click="handleSelectProject">
								<FolderOpened />
							</el-icon>
						</template>
					</el-input>
				</div>
				<div class="table-cell action">
					<el-button text circle :icon="OfficeBuilding" class="action-btn" @click="handleSelectProject" />
				</div>
			</el-form-item>

			<el-form-item class="table-row" prop="exitRecommendation" required>
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.exitSuggestion') }}</div>
				</template>
				<div class="table-cell value">
					<el-input v-model="formData.exitRecommendation" :placeholder="t('projectExitPlan.placeholder.input')" />
				</div>
			</el-form-item>

			<el-form-item class="table-row">
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.exitMethod') }}</div>
				</template>
				<div class="table-cell value">
					<el-input v-model="formData.exitMethod" :placeholder="t('projectExitPlan.placeholder.input')" />
				</div>
			</el-form-item>

			<el-form-item class="table-row">
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.executionTask') }}</div>
				</template>
				<div class="table-cell value">
					<el-input v-model="formData.executionTask" :placeholder="t('projectExitPlan.placeholder.input')" />
				</div>
			</el-form-item>

			<el-form-item class="table-row">
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.taskDescription') }}</div>
				</template>
				<div class="table-cell value">
					<el-input v-model="formData.taskDescription" type="textarea" :rows="1" :placeholder="t('projectExitPlan.placeholder.input')" />
				</div>
			</el-form-item>

			<el-form-item class="table-row">
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.executor') }}</div>
				</template>
				<div class="table-cell value">
					<el-select v-model="formData.executor" clearable :placeholder="t('projectExitPlan.form.executorPlaceholder')">
						<el-option :label="t('projectExitPlan.form.executorPlaceholder')" value="executor-placeholder" />
					</el-select>
				</div>
			</el-form-item>

			<el-form-item class="table-row two-columns">
				<template #label>
					<div class="table-cell label">{{ t('projectExitPlan.form.taskStartTime') }}</div>
				</template>
				<div class="table-cell value">
					<el-date-picker
						v-model="formData.taskStartDate"
						type="date"
						value-format="YYYY-MM-DD"
						:placeholder="t('projectExitPlan.placeholder.select')"
						style="width: 100%"
					/>
				</div>
				<div class="table-cell label">{{ t('projectExitPlan.form.taskEndTime') }}</div>
				<div class="table-cell value">
					<el-date-picker
						v-model="formData.taskEndDate"
						type="date"
						value-format="YYYY-MM-DD"
						:placeholder="t('projectExitPlan.placeholder.select')"
						style="width: 100%"
					/>
				</div>
			</el-form-item>
		</el-form>
		<el-dialog width="80%" title="关联列表" v-model="visible" :close-on-click-modal="false">
			<template #header>
				<el-form inline>
					<el-form-item label="项目名称">
						<el-input v-model="queryForm.projectName" placeholder="请输入项目名称" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="getListSearch">筛选</el-button>
						<el-button @click="handleReset">重置</el-button>
					</el-form-item>
				</el-form>
			</template>
			<el-table :data="tableData" style="width: 100%" height="50vh" highlight-current-row border @current-change="handleSelectionChange">
				<el-table-column label="选择" width="80">
					<template #default="scope">
						<div class="options" :class="active === scope.$index ? 'active' : ''"></div>
					</template>
				</el-table-column>
				<el-table-column prop="projectName" :label="t('projectLibrary.table.projectName')" min-width="200" />
				<el-table-column prop="projectStartTime" :label="t('projectLibrary.table.projectImplementationStart')" min-width="160" />
				<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="projectOwnerUnit" :label="t('projectLibrary.table.projectOwnerUnit')" min-width="200" />
				<el-table-column prop="" label="项目实施单位" />
				<el-table-column prop="projectInvestmentDirection" :label="t('projectLibrary.table.projectDirection')" min-width="160" />
				<el-table-column prop="mainBusinessTypes" :label="t('planApply.applySection.mainBusinessType')" min-width="160">
					<template #default="{ row }">
						{{ mainBusinessOptions.find((item: Enums) => item.value === row.mainBusinessTypes)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="constructionStage" :label="t('projectLibrary.table.constructionStage')" min-width="120" />
				<el-table-column prop="investmentCategory" :label="t('projectLibrary.table.investmentCategory')" min-width="140">
					<template #default="{ row }">
						{{ investmentCategoryOptions.find((item: Enums) => item.value === row.investmentCategory)?.label }}
					</template>
				</el-table-column>
				<el-table-column prop="" label="操作" fixed="right" width="100">
					<template #default="{ row }">
						<el-button type="primary" link @click="handleDetail(row)">详情</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.size"
					v-model:current-page="queryForm.page"
					@size-change="handlePageSizeChange"
					@current-change="handlePageChange"
				/>
			</div>
			<template #footer>
				<el-button type="primary" @click="tableSubmit">确定</el-button>
				<el-button @click="visible = false">取消</el-button>
			</template>
		</el-dialog>
		<el-dialog v-model="visible2" width="80%" title="项目详情">
			<ProjectPlanApplyFormDetails v-model="detailFormData" :isEdit="false" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { FolderOpened, OfficeBuilding } from '@element-plus/icons-vue';
import { investmentProjectsPlanGetById, investmentProjectsPlanPage } from '/@/api/investment/investmentManagement';
import { investmentProjectsPlanList } from '/@/views/invMid/projectLibrary/interface/types';
import { ProjectPlanApplyFormItem } from '/@/components/investment/interface/types';
import { type Enums, investmentCategoryOptions, mainBusinessOptions, projectNatureOptions } from '/@/hooks/enums';
import type { ProjectTask } from '/@/views/invMid/projectExitPlan/interface/type';
import ProjectPlanApplyFormDetails from '/@/components/investment/common/ProjectPlanApplyFormDetails.vue';
import { type FormInstance, FormRules } from 'element-plus';
const { t } = useI18n();

const visible = ref<boolean>(false);
const visible2 = ref<boolean>(false);
const props = defineProps<{
	modelValue?: ProjectTask;
	rules:FormRules;
}>();
const useForm = ref<FormInstance | undefined>();
const emit = defineEmits<{
	(e: 'update:modelValue', value: ProjectTask): void;
}>();

const defaultForm: ProjectTask = {
	id: undefined,
	projectName: '',
	projectId: undefined,
	exitRecommendation: '',
	executionTask:'',
	taskDescription:'',
	executor:'',
	taskStartDate:new Date().toISOString().substring(0,10),
	taskEndDate:new Date().toISOString().substring(0,10),
};

const formData = reactive<ProjectTask>({ ...defaultForm, ...props.modelValue });
const total = ref<number>(0);
const queryForm = ref<investmentProjectsPlanList>({
	page: 1,
	size: 10,
	projectName: '',
});
const tableData = ref<ProjectPlanApplyFormItem[]>([]);
const handleSelectProject = () => {
	visible.value = true;
};
const getListOfProjects = async () => {
	try {
		const res = await investmentProjectsPlanPage(queryForm.value);
		total.value = res.data.total as number;
		tableData.value = res.data.records;
	} catch (error: any) {
		console.log(error);
	}
};
const handlePageSizeChange = (size: number) => {
	queryForm.value.size = size;
	getListOfProjects();
};
const handlePageChange = (page: number) => {
	queryForm.value.page = page;
	getListOfProjects();
};
getListOfProjects();
const getListSearch = () =>{
	queryForm.value.page = 1;
	getListOfProjects();
}
const handleReset = () =>{
	queryForm.value.projectName = '';
}
watch(
	formData,
	(newVal) => {
		console.log(newVal,'formData');
		emit('update:modelValue', { ...newVal });
	},
	{ deep: true }
);

watch(
	() => props.modelValue,
	(newVal) => {
		if (newVal) {
			console.log(newVal,'asdas');
			Object.assign(formData, newVal);
		}
	},
	{ immediate: true, deep: true }
);
const active = ref<number>(-1);
const selectItem = ref<string>('');
const selectId = ref<number>();
const handleSelectionChange = (val: any) => {
	active.value = tableData.value.findIndex((item) => item.id === val.id);
	selectItem.value = val.projectName;
	selectId.value = val.id;
	formData.deptId = val.deptId;
};
const tableSubmit = () => {
	visible.value = false;
	formData.projectName = selectItem.value;
	formData.projectId = selectId.value;
};
const detailFormData = ref<any>({});
const handleDetail = (row: any) => {
	visible2.value = true;
	investmentProjectsPlanGetById(row.id).then((res) => {
		detailFormData.value.entity = res.data;
		detailFormData.value.investmentProjects = res.data.projectInvestmentEntities;
	});
};
defineExpose({
	validateRef: () => {
		return useForm.value?.validate();
	},
})
</script>

<style scoped>
.project-exit-plan-form {
	background-color: #fff;
	border: 1px solid var(--el-border-color-lighter);
	border-radius: 4px;
	padding: 24px;
}

.form-heading {
	text-align: center;
	margin-bottom: 20px;
}

.form-title {
	font-size: 20px;
	font-weight: 600;
	margin-bottom: 8px;
}

.form-meta {
	display: flex;
	justify-content: center;
	gap: 40px;
	flex-wrap: wrap;
}

.meta-item {
	display: flex;
	align-items: center;
	gap: 8px;
}

.meta-item :deep(.el-input),
.meta-item :deep(.el-date-editor) {
	width: 180px;
}

.exit-plan-table {
	border: 1px solid var(--el-border-color);
	border-collapse: collapse;
}

.table-row {
	display: flex;
	border-top: 1px solid var(--el-border-color);
}

.table-row:first-of-type {
	border-top: none;
}

.table-cell {
	border-right: 1px solid var(--el-border-color);
	padding: 12px;
	display: flex;
	align-items: center;
}

.table-cell:last-of-type {
	border-right: none;
}

.table-cell.label {
	width: 180px;
	height: 100%;
	background-color: var(--el-fill-color-light);
	font-weight: 500;
}

.table-cell.label.required::after {
	content: '*';
	margin-left: 4px;
	color: var(--el-color-danger);
}

.table-cell.value {
	flex: 1;
}
.table-row {
	margin: 0;
}
.table-row.two-columns .table-cell.label {
	width: 160px;
}

.table-row.two-columns .table-cell.value {
	flex: 1;
}

.project-name-cell {
	flex: 1;
}

.table-cell.action {
	width: 80px;
	justify-content: center;
}

.interactive-icon {
	color: var(--el-color-primary);
}

.action-btn {
	font-size: 18px;
}

.exit-plan-table :deep(.el-input),
.exit-plan-table :deep(.el-select),
.exit-plan-table :deep(.el-textarea),
.exit-plan-table :deep(.el-date-editor) {
	width: 100%;
}
.options {
	width: 20px;
	height: 20px;
	cursor: pointer;
	border: 1px solid var(--el-border-color);
	border-radius: 50%;
}
.active {
	background-color: var(--el-color-primary);
	color: white;
}

:deep(.el-form-item--default .el-form-item__label) {
	height: 100%;
	position: relative;
}
:deep(.el-form-item__label:before) {
	left: 4px;
	position: absolute;
}
</style>
