<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row class="header-summary mb10">
                <div class="title">{{ t('progressReportRecord.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"
                        @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('progressReportRecord.form.projectName')">
                            <el-input v-model="queryForm.projectName"
                                :placeholder="t('progressReportRecord.placeholder.input')" style="width: 180px" />
                        </el-form-item>
                        <el-form-item :label="t('progressReport.form.projectImplementationUnit')">
                            <el-input v-model="queryForm.implementingBody"
                                :placeholder="t('progressReportRecord.placeholder.input')" style="width: 180px" />
                        </el-form-item>
                        <el-form-item :label="t('progressReportRecord.form.projectStatus')">
                            <el-select v-model="queryForm.projectStatus"
																			 :placeholder="t('progressReportRecord.placeholder.select')" style="width: 160px" clearable>
															<el-option v-for="item in projectStatusOptions" :key="item.value" :label="item.label" :value="item.value" ></el-option>
														</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('progressReportRecord.table.index')" width="60" />
                <el-table-column prop="annualReport" :label="t('progressReportRecord.table.reportDate')" min-width="120"
                    sortable />
                <el-table-column prop="projectName" :label="t('progressReportRecord.table.projectName')"
                    min-width="200" />
                <el-table-column prop="implementingBody"
                    :label="t('progressReportRecord.table.projectImplementationUnit')" min-width="200" />
                <el-table-column prop="isFinalApplication" :label="t('progressReportRecord.table.isLastDeclaration')"
																 min-width="160" >
									<template #default="{ row }">
												{{row.isFinalApplication === 1 ? t('planApply.common.yes') : t('planApply.common.no')}}
									</template>

								</el-table-column>
                <el-table-column prop="projectStatus" :label="t('progressReportRecord.table.projectStatus')"
																 min-width="120" >
									<template #default="{row}">
										{{projectStatusOptions.find((item:Enums) => item.value === row.projectStatus)?.label}}
									</template>
								</el-table-column>
                <el-table-column prop="constructionStage" :label="t('progressReportRecord.table.constructionStage')"
																 min-width="120" >
									<template #default="{row}">
										{{constructionStageOptions.find((item:Enums) => item.value === row.constructionStage)?.label}}
									</template>
								</el-table-column>
                <el-table-column prop="investmentPlanCompletionRate"
                    :label="t('progressReportRecord.table.currentYearPlannedImageTotal')" min-width="180" />
                <el-table-column prop="ytdRemainingInvestment"
                    :label="t('progressReportRecord.table.enterpriseCumulativeInvestmentToMonthEnd')" min-width="200" />
                <el-table-column prop="investmentCompletionRate"
                    :label="t('progressReportRecord.table.currentYearImageCompletion')" min-width="180" />
                <el-table-column prop="projectTotalAmount"
                    :label="t('progressReportRecord.table.totalInvestmentAmount')" min-width="160" />
                <el-table-column prop="cumulativeInvestmentToDate"
                    :label="t('progressReportRecord.table.cumulativeInvestmentToMonthEnd')" min-width="200" />
                <el-table-column prop="completionRate" :label="t('progressReportRecord.table.totalCompletionRate')"
                    min-width="140" />
                <el-table-column prop="achievements" :label="t('progressReportRecord.table.effectiveness')"
                    min-width="120" />
                <el-table-column prop="coordinationIssues" :label="t('progressReportRecord.table.coordinationMatters')"
                    min-width="160" />
                <el-table-column prop="nextWorkPlan"
                    :label="t('progressReportRecord.table.nextWorkArrangements')" min-width="160" />
                <el-table-column prop="updateBy" :label="t('progressReportRecord.table.lastUpdater')"
                    min-width="140" />
                <el-table-column prop="updateTime" :label="t('progressReportRecord.table.lastUpdateTime')"
                    min-width="180" />
                <el-table-column prop="status" :label="t('progressReportRecord.table.lastPushStatus')"
                    min-width="180">
                    <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('progressReportRecord.table.action')" width="240" fixed="right">
                    <template #default="{ row }">
                        <el-button link type="primary" @click="handleView(row)">{{ t('common.viewBtn') || '查看'
                        }}</el-button>
                        <el-button link type="warning" @click="handleResubmit(row)">
                            {{ row.lastPushStatus === 'pending' ? t('progressReportRecord.action.submit') :
                                t('progressReportRecord.action.resubmit') }}
                        </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>
        </div>

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

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import {
	InvestmentProjectsProgressQuery, getInvestmentProjectsProgressPageAPI, getInvestmentProjectsProgressViewAPI,
	investmentProjectsProgressSubmitAPI
} from "/@/api/investment/progressOfInvestmentProjects"
import { InvestmentProjectProgress } from '/@/views/invMid/progressReport/interface/type';
import {projectStatusOptions,constructionStageOptions,Enums} from "/@/hooks/enums"
import ProjectProgressReportFormDeatils from '/@/components/investment/common/ProjectProgressReportFormDeatils.vue';
interface ProgressReportRecordItem {
    id: number;
    reportDate: string;
    projectName: string;
    projectImplementationUnit: string;
    isLastDeclaration: string;
    projectStatus: string;
    constructionStage: string;
    currentYearPlannedImageTotal: string;
    enterpriseCumulativeInvestmentToMonthEnd: string;
    currentYearImageCompletion: string;
    totalInvestmentAmount: string;
    cumulativeInvestmentToMonthEnd: string;
    totalCompletionRate: string;
    effectiveness: string;
    coordinationMatters: string;
    nextWorkArrangements: string;
    lastUpdater: string;
    lastUpdateTime: string;
    lastPushStatus: 'submitted' | 'failed' | 'pending';
}

const createEmptyDetail = (): 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 { t } = useI18n();
const message = useMessage();

const queryForm = reactive<InvestmentProjectsProgressQuery>({
    projectName: '',
    implementingBody: '',
    projectStatus: '',
    size: 10,
    page: 1,
});

const total = ref(6532);
const originData = ref<InvestmentProjectProgress[]>([]);
const tableData = ref<InvestmentProjectProgress[]>([]);
const selectedRows = ref<InvestmentProjectProgress[]>([]);
const detailDrawerVisible = ref(false);
const detailFormData = reactive<InvestmentProjectProgress>(createEmptyDetail());

const resetDetailForm = () => {
    const empty = createEmptyDetail();
    Object.assign(detailFormData, empty);
};


const getDataList = async () => {
    try {
			const res =await getInvestmentProjectsProgressPageAPI(queryForm);
			tableData.value = res.data.records;
			total.value = res.data.total;
		}catch (error) {
			console.log(error);
		}
};

const handleSearch = () => {
    queryForm.page = 1;
    getDataList();
};

const handleReset = () => {
    queryForm.projectName = '';
    queryForm.implementingBody = '';
    queryForm.projectStatus = '';
    queryForm.page = 1;
    getDataList();
};

const handleExport = () => {
    message.info(t('progressReportRecord.message.exportInfo'));
};

const handleBatchDelete = () => {
    if (!selectedRows.value.length) return;
    message.success(t('progressReportRecord.message.deleteSuccess'));
    const ids = selectedRows.value.map(row => row.id);
    originData.value = originData.value.filter(row => !ids.includes(row.id));
    selectedRows.value = [];
    if (tableData.value.length === 0 && queryForm.page > 1) {
        queryForm.page -= 1;
    }
    getDataList();
};

const handleSelectionChange = (rows: ProgressReportRecordItem[]) => {
    selectedRows.value = rows;
};

const handleView = (row: ProgressReportRecordItem) => {
    resetDetailForm();
	getInvestmentProjectsProgressViewAPI(row.id).then(res=>{
		Object.assign(detailFormData,res.data);
	}).catch(error => {
		console.log(error);
	});
    detailDrawerVisible.value = true;
};

const handleResubmit = (row: ProgressReportRecordItem) => {
    // const action = row.lastPushStatus === 'pending' ? t('progressReportRecord.action.submit') : t('progressReportRecord.action.resubmit');
	investmentProjectsProgressSubmitAPI(row.id).then(()=>{
		message.success('报送国资成功');
	}).catch(error => {
		console.log(error,'280行');
	});
};

const handlePageChange = (page: number) => {
    queryForm.page = page;
    getDataList();
};

const handlePageSizeChange = (size: number) => {
    queryForm.size = size;
    queryForm.page = 1;
    getDataList();
};

const getStatusTagType = (status: ProgressReportRecordItem['lastPushStatus']) => {
    if (status === 'submitted') return 'success';
    if (status === 'failed') return 'danger';
    return 'info';
};

const getStatusLabel = (status: ProgressReportRecordItem['lastPushStatus']) => {
    if (status === 'submitted') return t('progressReportRecord.status.submitted');
    if (status === 'failed') return t('progressReportRecord.status.failed');
    return t('progressReportRecord.status.pending');
};

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%;
}

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

.progress-report-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>

