<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row class="header-summary mb10">
                <div class="title">{{ t('reserveLibrary.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('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%" border @selection-change="handleSelectionChange"
                v-loading="tableLoading">
                <el-table-column type="selection" width="48" />
                <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" >
									<template #default="{ row }">
										<span>{{ investmentCategoryOptions.find((item:Enums) => item.value === row.investmentCategory)?.label }}</span>
									</template>
								</el-table-column>
                <el-table-column prop="projectNature" :label="t('reserveLibrary.table.projectNature')"
																 min-width="140" >
									<template #default="{ row }">
										<span>{{ projectNatureOptions.find((item:Enums) => item.value === row.projectNature)?.label }}</span>
									</template>
								</el-table-column>
                <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" >
									<template #default="{row}">
										<span>{{investmentAreaOptions.find((item:Enums) => item.value === row.investmentRegion)?.label}}</span>
									</template>
								</el-table-column>
                <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" >
								<template #default="{row}">
									<div v-if="row.keyProject === 'yes'|| row.keyProject === 'no'">
										<span>{{[{label:'yes',value:'是'},{label:'no',value:'否'}].find((item:Enums) => item.value === row.keyProject)?.label}}</span>
									</div>
									<div v-else>
										<span>{{yesOrNo.find((item:Enums) => item.value === row.keyProject)?.label}}</span>
									</div>
								</template>
							</el-table-column>
                <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.viewBtn') || '查看'
                            }}</el-button>
                        <el-button link type="primary" @click="handlePush(row)">{{
                            t('reserveLibrary.action.push')
                            }}</el-button>
                        <!-- <el-button link type="warning" @click="handleRollback(row)">{{
                            t('reserveLibrary.action.rollback')
                            }}</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="project-detail-drawer" direction="rtl" size="70%"
            :with-header="false" :close-on-click-modal="false">
            <div class="detail-header">
                <span class="detail-title">{{ t('reserveLibrary.detail.title') }}</span>
                <el-button class="close-btn" link icon="Close" @click="detailDrawerVisible = false" />
            </div>
            <div class="detail-content">
                <ProjectBasicInfoView :model-value="detailFormData" :main-title="t('reserveLibrary.detail.formTitle')" />
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage, useMessageBox } from '/@/hooks/message';
import ProjectBasicInfoView from '/@/components/investment/common/ProjectBasicInfoView.vue';
import type { ProjectBasicInfoFormData } from '/@/components/investment/common/ProjectBasicInfoForm.vue';
import {
    getReserveInvestmentProjectsPageAPI,
    getReserveInvestmentProjectDetailAPI,
    deleteReserveInvestmentProjectsAPI,
    type ReserveInvestmentProjectItem,
    submitReserveInvestmentProjectsAPI,
    normalizeDetailData,
} from '/@/api/investment/reserveRegistration';
import {Enums, investmentAreaOptions, investmentCategoryOptions, projectNatureOptions, yesOrNo} from '/@/hooks/enums'
import { ElMessage, ElMessageBox } from 'element-plus';

type ReserveProjectItem = ReserveInvestmentProjectItem & {
    projectMainUnit?: string;
    projectDirection?: string;
    projectStartDate?: string;
    projectEndDate?: string;
    investmentRegion?: string;
    lastUpdateTime?: string;
};

const createEmptyDetail = (): ProjectBasicInfoFormData => ({
    applicant: '',
    applicationUnit: '',
    projectName: '',
    projectMainUnit: '',
    projectStartDate: '',
    investmentCategory: '',
    projectManagerName: '',
    projectSource: '',
    keyProject: '',
    withinMainBusiness: '',
    mainBusinessType: '',
    projectDirection: '',
    strategicEmergingIndustry: '',
    isManufacturing: '',
    projectAddress: '',
    isControllingShareholder: '',
    totalInvestmentAmount: '',
    ourTotalInvestmentAmount: '',
    projectDesc: '',
    progressDesc: '',
    projectProposal: '',
    applicationDate: '',
    projectOwnerUnit: '',
    projectEndDate: '',
    projectNature: '',
    contactNumber: '',
    constructionNature: '',
    majorInvestmentProject: '',
    mainBusinessCode: '',
    directionSubdivision: '',
    urbanStrategy: '',
    investmentRegion: '',
    projectDetailedAddress: '',
    ourShareholdingRatio: '',
    cumulativeInvestmentLastYear: '',
    ourCumulativeInvestmentLastYear: '',
    enterpriseSelfFund: '',
    externalRaisedFund: '',
    governmentInvestmentFund: '',
    otherFunds: '',
    partnerInfos: [],
    decisionType: '',
    isCompleteEstablishmentProcedures: '',
    establishmentDocumentNumber: '',
    establishmentDocumentInfo: '',
    decisionProgramDocumentNumber: '',
    decisionDocumentInfo: '',
    isCompleteDecisionProcedures: '',
    processInstanceId: '',
    reviewOpinions: {
        submitUnitOpinion: '',
        groupInvestmentDeptOpinion: '',
        submitUnitLeadershipOpinion: '',
        submitUnitMainLeadershipOpinion: '',
    },
});

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

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

const total = ref(0);
const tableData = ref<ReserveProjectItem[]>([]);
const selectedRows = ref<ReserveProjectItem[]>([]);
const detailDrawerVisible = ref(false);
const detailFormData = reactive<ProjectBasicInfoFormData>(createEmptyDetail());
const tableLoading = ref(false);
const detailLoading = ref(false);

const resetDetailForm = () => {
    const empty = createEmptyDetail();
    Object.assign(detailFormData, empty);
    detailFormData.partnerInfos.splice(0, detailFormData.partnerInfos.length);
    detailFormData.reviewOpinions && Object.assign(detailFormData.reviewOpinions, empty.reviewOpinions);
    detailFormData.projectProposal = '';
};

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.pushStatus == '1' ? 'submitted' : item.pushStatus == '0' ? 'pending' : 'failed',
});

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 handleReset = () => {
    queryForm.projectName = '';
    queryForm.projectMainEntity = '';
    queryForm.projectNature = '';
    queryForm.page = 1;
    fetchProjectList();
};

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

const handleBatchDelete = async () => {
    const ids = selectedRows.value
        .map((item) => item.id)

    if (!ids.length) {
        message.warning(t('common.selectDataTip') || '请选择数据');
        return;
    }

    try {
        await messageBox.confirm(t('common.delConfirmText'));
    } catch {
        return;
    }

    tableLoading.value = true;
    try {
        await deleteReserveInvestmentProjectsAPI(ids);
        message.success(t('common.delSuccessText') || '删除成功');
        selectedRows.value = [];
        fetchProjectList();
    } catch (error: any) {
        message.error(error?.msg || error?.message || t('common.operateFail') || '删除失败');
    } finally {
        tableLoading.value = false;
    }
};

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

const handleView = async (row: ReserveProjectItem) => {
    if (!row?.id) {
        message.warning(t('common.selectDataTip') || '请选择数据');
        return;
    }
    resetDetailForm();
    detailDrawerVisible.value = true;
    detailLoading.value = true;
    try {
        const res = await getReserveInvestmentProjectDetailAPI(row.id);
        const detail = (res as any)?.data ?? res;
        const detailData = normalizeDetailData(detail as ReserveInvestmentProjectItem);
        Object.assign(detailFormData, detailData)
        detailFormData.partnerInfos.splice(0, detailFormData.partnerInfos.length);
    } catch (error: any) {
        message.error(error?.msg || error?.message || t('common.operateFail') || '获取详情失败');
    } finally {
        detailLoading.value = false;
    }
};
const pusing = ref(false)
const handlePush = (row: ReserveProjectItem) => {
    if (pusing.value) return
    ElMessageBox.confirm('确定要报送国资吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        pusing.value = true
        try {
            const res = await submitReserveInvestmentProjectsAPI(row.id)
            if (res.ok) {
                ElMessage({
                    type: 'success',
                    message: '已报送国资',
                })
            }
        } finally {
            pusing.value = false
        }
    })
}
const handleRollback = (row: ReserveProjectItem) => {
    message.info(`${t('reserveLibrary.message.rollbackHint')}: ${row.projectName}`);
};

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

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

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

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');
};

onMounted(() => {
    fetchProjectList();
});
</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% - 52px);
}

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