<template>
    <div class="mixed-library-wrapper">
        <div class="layout-padding-auto layout-padding-view">
            <div class="page-title">{{ t('mixedLibrary.title') }}</div>
            <div class="page-header">
                <div>
                    <el-button type="primary" icon="Plus" @click="handleCreate">
                        {{ t('mixedLibrary.actions.createNew') }}
                    </el-button>
                    <el-button icon="Refresh" @click="handleCreateUpdate">
                        {{ t('mixedLibrary.actions.createUpdate') }}
                    </el-button>
                </div>
                <div class="filter-section">
                    <el-form :model="filters" inline>
                        <el-form-item :label="t('mixedLibrary.filters.projectName')">
                            <el-input v-model="filters.projectName"
                                :placeholder="t('mixedLibrary.placeholder.input')" />
                        </el-form-item>
                        <el-form-item :label="t('mixedLibrary.filters.companyName')">
                            <el-input v-model="filters.implementEnterprise"
                                :placeholder="t('mixedLibrary.placeholder.input')" />
                        </el-form-item>
                        <el-form-item :label="t('mixedLibrary.filters.companyCode')">
                            <el-input v-model="filters.enterpriseCreditCode"
                                :placeholder="t('mixedLibrary.placeholder.input')" />
                        </el-form-item>
                        <el-form-item class="filter-buttons">
                            <el-button type="primary" @click="handleQuery">
                                {{ t('mixedLibrary.actions.query') }}
                            </el-button>
                            <el-button @click="handleReset">
                                {{ t('mixedLibrary.actions.reset') }}
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>

            <el-card shadow="never">
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"
                    v-loading="tableLoading">
                    <el-table-column type="selection" width="48" />
                    <el-table-column type="index" :label="t('mixedLibrary.table.index')" width="60" />
                    <el-table-column prop="year" :label="t('mixedLibrary.table.year')" width="80" />
                    <el-table-column prop="projectName" :label="t('mixedLibrary.table.projectName')"
                        min-width="160" />
                    <el-table-column prop="companyName" :label="t('mixedLibrary.table.companyName')"
                        min-width="180" />
                    <el-table-column prop="companyCode" :label="t('mixedLibrary.table.companyCode')"
                        min-width="180" />
                    <el-table-column
                        prop="mode"
                        :label="t('mixedLibrary.table.mode')"
                        min-width="120"
                    >
                        <template #default="{ row }">
                            {{ mixedReformMethodOptions.find(item => item.value === row.mode)?.label || row.mode }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="partnerNature"
                        :label="t('mixedLibrary.table.partnerNature')"
                        min-width="140"
                    >
                        <template #default="{ row }">
                            {{ cooperationPartnerNatureOptions.find(item => item.value === row.partnerNature)?.label || row.partnerNature }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="partnerName" :label="t('mixedLibrary.table.partnerName')"
                        min-width="160" />
                    <el-table-column
                        prop="type"
                        :label="t('mixedLibrary.table.type')"
                        min-width="120"
                    >
                        <template #default="{ row }">
                            {{ mixedReformTypeOptions.find(item => item.value === row.type)?.label || row.type }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="progress" :label="t('mixedLibrary.table.progress')" min-width="120" />
                    <el-table-column prop="reportUnit" :label="t('mixedLibrary.table.reportUnit')"
                        min-width="140" />
                    <el-table-column prop="lastUpdateTime" :label="t('mixedLibrary.table.lastUpdateTime')"
                        min-width="160" />
                    <el-table-column prop="lastUpdater" :label="t('mixedLibrary.table.lastUpdater')"
                        min-width="120" />
                    <el-table-column prop="lastStatus" :label="t('mixedLibrary.table.lastStatus')" min-width="140">
                        <template #default="{ row }">
                            <el-tag v-if="row.lastStatus === 'success'" type="success">
                                {{ t('mixedLibrary.status.success') }}
                            </el-tag>
                            <el-tag v-else-if="row.lastStatus === 'failed'" type="danger">
                                {{ t('mixedLibrary.status.failed') }}
                            </el-tag>
                            <el-tag v-else>
                                {{ t('mixedLibrary.status.pending') }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="t('mixedLibrary.table.actions')" min-width="180" fixed="right">
                        <template #default="{ row }">
                            <el-button link type="primary" @click="handleView(row)">
                                {{ t('mixedLibrary.actions.view') }}
                            </el-button>
                            <el-button link type="primary" @click="handleResubmit(row)">
                                {{ t('mixedLibrary.actions.resubmit') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="table-footer">
                    <div class="total-text">
                        {{ t('mixedLibrary.pagination.total', { total: totalCount }) }}
                    </div>
                    <el-pagination background :current-page="pagination.page" :page-size="pagination.pageSize"
                        :total="totalCount" layout="prev, pager, next, jumper, ->, sizes"
                        :page-sizes="[10, 20, 50, 100]" @current-change="handlePageChange"
                        @size-change="handleSizeChange" />
                </div>
            </el-card>
        </div>
        <MixedReformDetailDrawer v-model="detailDrawerVisible" :detail="detailDrawerData" :items="detailItems"
            :title="detailDrawerTitle" :loading="detailLoading" :empty-text="t('common.noDataText') || '暂无数据'" />
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { useRouter } from 'vue-router';
import {
    getMixedReformPageAPI,
    getMixedReformDetailAPI,
    type MixedReformItem,
} from '/@/api/investment/mixedReform';
import MixedReformDetailDrawer from '/@/components/investment/mixedReform/MixedReformDetailDrawer.vue';
import { cooperationPartnerNatureOptions, mixedReformMethodOptions, mixedReformTypeOptions } from '/@/hooks/enums'

const { t } = useI18n();
const message = useMessage();
const router = useRouter();

const filters = reactive({
    projectName: '',
    implementEnterprise: '',
    enterpriseCreditCode: '',
});

interface MixedRow {
    id: number | string;
    year: string;
    projectName: string;
    companyName: string;
    companyCode: string;
    mode: string;
    partnerNature: string;
    partnerName: string;
    type: string;
    progress: string;
    reportUnit: string;
    lastUpdateTime: string;
    lastUpdater: string;
    lastStatus: 'success' | 'failed' | 'pending';
}

const tableData = ref<MixedRow[]>([]);
const tableLoading = ref(false);
const totalCount = ref(0);
const selection = ref<MixedRow[]>([]);
const detailDrawerVisible = ref(false);
const detailRow = ref<MixedRow | null>(null);
const detailLoading = ref(false);

const pagination = reactive({
    page: 1,
    pageSize: 10,
});

const mapPushStatus = (status?: string | null): MixedRow['lastStatus'] => {
    if (!status) return 'pending';
    /*const lower = status.toLowerCase?.() || '';
    if (
        lower.includes('success') ||
        lower.includes('pass') ||
        lower.includes('submit') ||
        status.includes('已推送') ||
        status.includes('已提交') ||
        status.includes('审批通过')
    ) {
        return 'success';
    }
    if (
        lower.includes('fail') ||
        lower.includes('error') ||
        lower.includes('reject') ||
        status.includes('失败') ||
        status.includes('驳回')
    ) {
        return 'failed';
    }*/
		if (status == '0') return 'pending'
		if (status == '1') return 'success'
    return 'pending';
};

const normalizeMixedRow = (item: MixedReformItem): MixedRow => ({
    id: item.id,
    year: item.projectYear ? String(item.projectYear) : '--',
    projectName: item.projectName || '--',
    companyName: item.implementEnterprise || '--',
    companyCode: item.enterpriseCreditCode || '--',
    mode: item.mixedReformMethod || '--',
    partnerNature: item.partnerNature || '--',
    partnerName: item.partnerName || '--',
    type: item.mixedReformType || '--',
    progress: item.progressStatus || '--',
    reportUnit: item.reportingUnit || '--',
    lastUpdateTime: item.updateTime || item.createTime || '--',
    lastUpdater: item.updateBy || item.createBy || '--',
    lastStatus: mapPushStatus(item.pushStatus),
});

const getStatusLabel = (status: MixedRow['lastStatus']) => {
    if (status === 'success') return t('mixedLibrary.status.success');
    if (status === 'failed') return t('mixedLibrary.status.failed');
    return t('mixedLibrary.status.pending');
};

const buildQueryParams = () => ({
    page: pagination.page,
    size: pagination.pageSize,
    projectName: filters.projectName || undefined,
    implementEnterprise: filters.implementEnterprise || undefined,
    enterpriseCreditCode: filters.enterpriseCreditCode || undefined,
});

const fetchMixedReformList = async () => {
    tableLoading.value = true;
    try {
        const params = buildQueryParams();
        const res = await getMixedReformPageAPI(params);
        const records = (res as any)?.records ?? (res as any)?.data?.records ?? [];
        const total = (res as any)?.total ?? (res as any)?.data?.total ?? 0;
        tableData.value = Array.isArray(records) ? records.map(normalizeMixedRow) : [];
        totalCount.value = Number(total) || 0;
    } catch (error: any) {
        message.error(error?.msg || error?.message || t('common.operateFail') || '获取列表失败');
    } finally {
        tableLoading.value = false;
    }
};

const handleSelectionChange = (rows: MixedRow[]) => {
    selection.value = rows;
};

const detailItems = computed(() => [
    { key: 'projectName', label: t('mixedLibrary.table.projectName') },
    { key: 'year', label: t('mixedLibrary.table.year') },
    { key: 'companyName', label: t('mixedLibrary.table.companyName') },
    { key: 'companyCode', label: t('mixedLibrary.table.companyCode') },
    { key: 'mode', label: t('mixedLibrary.table.mode') },
    { key: 'partnerNature', label: t('mixedLibrary.table.partnerNature') },
    { key: 'partnerName', label: t('mixedLibrary.table.partnerName') },
    { key: 'type', label: t('mixedLibrary.table.type') },
    { key: 'progress', label: t('mixedLibrary.table.progress') },
    { key: 'reportUnit', label: t('mixedLibrary.table.reportUnit') },
    { key: 'lastUpdateTime', label: t('mixedLibrary.table.lastUpdateTime') },
    { key: 'lastUpdater', label: t('mixedLibrary.table.lastUpdater') },
    { key: 'lastStatusLabel', label: t('mixedLibrary.table.lastStatus') },
]);

const detailDrawerTitle = computed(() => {
    if (!detailRow.value) return t('mixedLibrary.actions.view');
    return `${detailRow.value.projectName || '--'}`;
});

const detailDrawerData = computed(() => {
    if (!detailRow.value) return null;
    return {
        ...detailRow.value,
        lastStatusLabel: getStatusLabel(detailRow.value.lastStatus),
    };
});

const handleQuery = () => {
    pagination.page = 1;
    fetchMixedReformList();
};

const handleReset = () => {
    filters.projectName = '';
    filters.implementEnterprise = '';
    filters.enterpriseCreditCode = '';
    pagination.page = 1;
    fetchMixedReformList();
};

const handlePageChange = (page: number) => {
    pagination.page = page;
    fetchMixedReformList();
};

const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    pagination.page = 1;
    fetchMixedReformList();
};

const handleCreate = () => {
    router.push({ path: '/workbench/miOwLibr/ownershipCreate/index' });
};

const handleCreateUpdate = () => {
    message.info(t('mixedLibrary.messages.createUpdate'));
};

const fetchDetail = async (id: MixedRow['id'], fallback?: MixedRow) => {
    detailLoading.value = true;
    try {
        const res = await getMixedReformDetailAPI(id);
        const detail = (res as any)?.data ?? res;
        const normalized = normalizeMixedRow(detail as MixedReformItem);
        detailRow.value = {
            ...(fallback || detailRow.value || normalized),
            ...normalized,
        };
    } catch (error: any) {
        message.error(error?.msg || error?.message || t('common.operateFail') || '获取详情失败');
    } finally {
        detailLoading.value = false;
    }
};

const handleView = (row: MixedRow) => {
    detailRow.value = row;
    detailDrawerVisible.value = true;
    fetchDetail(row.id, row);
};

const handleResubmit = (row: MixedRow) => {
	// 报送国资

    message.info(`${row.projectName} ${t('mixedLibrary.messages.resubmit')}`);
};

onMounted(() => {
    fetchMixedReformList();
});
</script>

<style scoped>
.mixed-library-wrapper {
    width: 100%;
    height: 100%;
}

.page-title {
    font-size: 18px;
    font-weight: 600;
    text-align: center;
    margin-bottom: 12px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.filter-section {
    display: flex;
    justify-content: flex-end;
}

.filter-buttons :deep(.el-form-item__content) {
    display: flex;
    gap: 12px;
}

.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
}

.total-text {
    color: var(--el-text-color-secondary);
}
</style>
