<template>
    <el-row class="page-title-row mb10">
        <div class="page-title">{{ title ? title : t('progressReport.form.title') }}</div>
        <div class="page-report-time">{{ t('progressReport.form.reportTime') }}: {{formData.createTime || reportTime }}</div>
        <div class="page-unit">{{ t('progressReport.form.unit') }}</div>
    </el-row>
    <div class="project-progress-report-form">
        <div class="form-section-title">{{ t('progressReport.form.sectionTitle') }}</div>
        <el-form :model="formData" label-width="200px" class="progress-form" :rules="rules" ref="useForm">
            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.projectName')" required prop="projectName">
                    		<span>{{formData.projectName }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.projectStatus')" required prop="projectStatus">
                      	<span v-for="item in projectStatusOptions" :key="item.value">{{formData.projectStatus == item.value ? item.label : ''}}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.constructionStage')">
                        <span v-for="item in constructionStageOptions" :key="item.value">{{formData.constructionStage == item.value ? item.label : ''}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.projectImplementationUnit')">
                     	<span>{{formData.implementingBody}}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.totalInvestmentAmount')" required prop="projectTotalAmount">
                       <span>{{formData.projectTotalAmount }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.cumulativeInvestmentToMonthEnd')" required prop="cumulativeInvestmentToDate">
											<span>{{formData.cumulativeInvestmentToDate}}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.completionRate')" required prop="completionRate">
                     <span>{{formData.completionRate}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.cumulativePaymentToMonthEnd')">
                       <span>{{formData.cumulativePaymentToDate}}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="t('progressReport.form.paymentCompletionRate')">
                      <span>{{formData.paymentCompletionRate}}</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="plan-investment-block">
                <el-col :span="12">
                    <div class="plan-investment-panel left-panel">
                        <div class="panel-title">{{ t('progressReport.form.currentYearImageAmount') }}</div>
                        <div style="flex: 1;">
                            <el-form-item style="height: 82px;" :label="t('progressReport.form.reportYear')">
                             <span>{{formData.annualReport}}</span>
                            </el-form-item>
                            <el-form-item style="height: 82px;"
                                :label="t('progressReport.form.currentYearPlannedInvestment')" required prop="annualPlannedInvestment">
                                <span>{{formData.investmentTotalAmount ?? 0 + ' ' + t('progressReport.form.unitSuffix')}}</span>
                            </el-form-item>
                            <el-form-item style="height: 82px;"
                                :label="t('progressReport.form.enterpriseCumulativeInvestmentToMonthEnd')" required prop="ytdRemainingInvestment">
                                <span>{{ formData.ytdRemainingInvestment + ' ' + t('progressReport.form.unitSuffix')}}</span>
                            </el-form-item>
                            <el-form-item style="height: 82px;"
                                :label="t('progressReport.form.investmentCompletionRate')">
                               <span>{{formData.investmentCompletionRate}}%</span>
                            </el-form-item>
                        </div>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="plan-investment-panel right-panel">
                        <div class="panel-title">{{ t('progressReport.form.currentYearPlannedAmount') }}</div>
                        <div style="flex: 1;">
                            <el-form-item style="height: 82px;" :label="t('progressReport.form.plannedPaymentAmount')">
                                <span>{{formData.plannedPayment + ' ' + t('progressReport.form.unitSuffix')}}</span>
                            </el-form-item>
                            <el-form-item style="height: 82px;"
                                :label="t('progressReport.form.completedPaymentAmount')">
															<span>{{formData.actualPayment + ' ' + t('progressReport.form.unitSuffix')}}</span>
                            </el-form-item>
                            <el-form-item style="height: 82px;"
                                :label="t('progressReport.form.plannedAmountPaymentCompletionRate')">
															<span>{{formData.investmentPlanCompletionRate}} %</span>
                            </el-form-item>
                        </div>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.effectiveness')">
                       <span>{{formData.achievements}}</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.coordinationMatters')">
                        <span>{{formData.coordinationIssues}}</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.nextWorkArrangements')">
                        <span>{{formData.nextWorkPlan}}</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.currentStageEvidenceMaterials')">
											<uploadFile :modelValue="JSON.parse(formData.supportingDocuments || '[]') || []" @change="uploadChange" :fileSize="20" type="simple" :limit="10"
																	:isShowTip="false" disabled></uploadFile>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.remark')">
                        <span>{{formData.remarks}}</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="form-row">
                <el-col :span="24">
                    <el-form-item :label="t('progressReport.form.isLastDeclaration')">
											<span>{{formData.isFinalApplication == '1' ? t('progressReport.form.yes') : t('progressReport.form.no')}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, computed, watch, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { InvestmentProjectProgress } from '/@/views/invMid/progressReport/interface/type';
import { investmentProjectsPlanList } from '/@/views/invMid/projectLibrary/interface/types';
import { investmentProjectsPlanPage } from '/@/api/investment/investmentManagement';
import { ProjectPlanApplyFormItem } from '/@/components/investment/interface/types';
import { constructionStageOptions, projectStatusOptions } from '/@/hooks/enums';
import { type FormInstance, FormRules } from 'element-plus';
import uploadFile from '/@/components/Upload/index.vue';
const { t } = useI18n();

export interface ProjectProgressReportFormData {
    projectName: string;
    projectStatus: string;
    constructionStage: string;
    projectImplementationUnit: string;
    totalInvestmentAmount: string;
    cumulativeInvestmentToMonthEnd: string;
    completionRate: string;
    cumulativePaymentToMonthEnd: string;
    paymentCompletionRate: string;
    // 本年投资形象额
    reportYear: string;
    currentYearPlannedInvestment: string;
    enterpriseCumulativeInvestmentToMonthEnd: string;
    investmentCompletionRate: string;
    // 本年投资计划额
    plannedPaymentAmount: string;
    completedPaymentAmount: string;
    plannedAmountPaymentCompletionRate: string;
    // 其他字段
    effectiveness: string;
    coordinationMatters: string;
    nextWorkArrangements: string;
    currentStageEvidenceMaterials: any[];
    remark: string;
    isLastDeclaration: string;
}

const props = defineProps<{
    modelValue?: InvestmentProjectProgress;
		rules?:FormRules;
		title?: string;
}>();

const emit = defineEmits<{
    (e: 'update:modelValue', value: InvestmentProjectProgress): void;
}>();
const useForm = ref<FormInstance | undefined>()
const defaultForm = reactive<InvestmentProjectProgress>({
	id: undefined,
	projectName: '',
	projectId: undefined,
	projectStatus: '',
	constructionStage: '',
	implementingBody: '',
	projectTotalAmount: undefined,
	cumulativeInvestmentToDate: undefined,
	completionRate: undefined,
	cumulativePaymentToDate: undefined,
	paymentCompletionRate: undefined,
	annualReport: undefined,
	annualPlannedInvestment: undefined,
	ytdRemainingInvestment: undefined,
	investmentCompletionRate: undefined,
	plannedPayment: undefined,
	actualPayment: undefined,
	investmentPlanCompletionRate: undefined,
	achievements: '',
	coordinationIssues: '',
	nextWorkPlan: '',
	supportingDocuments: '',
	remarks: '',
	isFinalApplication: undefined,
	createBy: '',
	createTime: '',
	updateBy: '',
	updateTime: '',
	delFlag: '',
	processInstanceId: '',
	status: '',
})
const formData = reactive<InvestmentProjectProgress>({ ...defaultForm, ...props.modelValue });
const projectNameData = ref<ProjectPlanApplyFormItem[]>([]);
// 获取当前日期作为汇报时间
const reportTime = computed(() => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
});
const total = ref(0)
const queryForm = reactive<investmentProjectsPlanList>({
    page: 1,
    size: 10,
});
const getProjectNameList = async () => {
	try {
		const res = await investmentProjectsPlanPage(queryForm);
		projectNameData.value = res.data?.records || [];
		total.value = res.data?.total || 0;
	} catch (error) {
		console.error(error);
		projectNameData.value = []; // 出错时设置为空数组
	}
}
getProjectNameList();
/**
 * 初始化图片
 * */
const uploadChange = (_:any,data:any[]) =>{
	if (!data || Object.prototype.toString.call(data) !== '[object Array]' || data.length === 0){
		formData.supportingDocuments = [];
		return;
	}
	formData.supportingDocuments = data.map((item:any) => {
		return {
			name: item.name,
			url: item.url
		}
	})
}
// 监听 formData 变化，同步到父组件
watch(
    formData,
    (newVal) => {
        emit('update:modelValue', { ...newVal });
    },
    { deep: true }
);

// 监听 props.modelValue 变化，同步到 formData
watch(
    () => props.modelValue,
    (newVal) => {
        if (newVal) {
					if (typeof newVal.annualReport === 'number') newVal.annualReport = newVal.annualReport.toString()
            Object.assign(formData, defaultForm, newVal);
        }
    },
    { immediate: true, deep: true }
);
defineExpose({
	validate: async () => {
	 const isValid =	await useForm.value?.validate();
	 if (!isValid) return false
		return formData
	},
})
</script>

<style scoped>
.page-title-row {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-bottom: 20px;
}

.page-title {
    font-size: 20px;
    font-weight: 600;
    text-align: center;
}

.page-report-time {
    position: absolute;
    left: 0;
    font-size: 14px;
    color: var(--el-text-color-secondary);
}

.page-unit {
    position: absolute;
    right: 0;
    font-size: 14px;
    color: var(--el-text-color-secondary);
}

.project-progress-report-form {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    border: 1px solid var(--el-border-color-light);
}

.form-section-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0 0 20px;
    padding-left: 10px;
    border-left: 4px solid var(--el-color-primary);
}

.progress-form {
    width: 100%;
}

/* 表单 label 左对齐 */
.progress-form :deep(.el-form-item__label) {
    text-align: left;
    justify-content: flex-start;
}


.form-row {
    margin-bottom: 16px;
    margin-top: 16px;
}

.form-row:last-of-type {
    margin-bottom: 0;
}

.cursor-pointer {
    cursor: pointer;
}

.plan-investment-block {
    margin-top: 24px;
}

.plan-investment-panel {
    display: flex;
    flex-direction: row;
    align-items: center;
    background: #f0f7ff;
    padding: 16px;
    border-radius: 4px;
    min-height: 414px;
}

.panel-title {
    margin-right: 20px;
    padding-top: 0;
    margin-top: 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    white-space: nowrap;
}

.plan-investment-panel :deep(.el-form-item__label) {
    padding-top: 0;
    line-height: 32px;
}

.plan-investment-panel :deep(.el-form-item) {
    align-items: center;
}
</style>
