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

            <el-card shadow="never">
                <el-table :data="tableData" border style="width: 100%" @current-change="handleCurrentChange"
                    highlight-current-row v-loading="tableLoading">
                    <el-table-column type="index" :label="t('propertyManagement.table.index')" width="60" />
                    <el-table-column prop="enterpriseName" :label="t('propertyManagement.table.companyName')"
                        min-width="180" />
                    <el-table-column prop="creditCode" :label="t('propertyManagement.table.unifiedCode')"
                        min-width="200" />
                    <el-table-column prop="registrationDate" :label="t('propertyManagement.table.establishDate')"
                        min-width="140" />
                    <el-table-column prop="mainInvestorName" :label="t('propertyManagement.table.mainInvestorName')"
                        min-width="180" />
                    <el-table-column prop="mainInvestorCode" :label="t('propertyManagement.table.mainInvestorCode')"
                        min-width="200" />
                    <el-table-column prop="supervisorUnit" :label="t('propertyManagement.table.supervisingUnit')"
                        min-width="140" />
                    <el-table-column prop="supervisorUnitCode"
                        :label="t('propertyManagement.table.supervisingUnitCode')" min-width="200" />
                    <el-table-column prop="updateTime" :label="t('propertyManagement.table.lastUpdateTime')"
                        min-width="160" />
                    <el-table-column prop="updateBy" :label="t('propertyManagement.table.lastUpdater')"
                        min-width="120" />
                    <el-table-column prop="pushStatus" :label="t('propertyManagement.table.lastStatus')"
                        min-width="160">
                        <template #default="{ row }">
                            <el-tag v-if="row.pushStatus === 'success'" type="success">
                                {{ t('propertyManagement.status.success') }}
                            </el-tag>
                            <el-tag v-else-if="row.pushStatus === 'failed'" type="danger">
                                {{ t('propertyManagement.status.failed') }}
                            </el-tag>
                            <el-tag v-else>
                                {{ t('propertyManagement.status.pending') }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="t('propertyManagement.table.actions')" min-width="200" fixed="right">
                        <template #default="{ row }">
                            <el-button link type="primary" @click="handleView(row)">
                                {{ t('propertyManagement.actions.view') }}
                            </el-button>
                            <el-button link type="primary" @click="handleReport(row)">
                                {{ row.lastStatus === 'pending' ? t('propertyManagement.actions.report') :
                                    t('propertyManagement.actions.reReport') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="table-footer">
                    <div class="total-text">
                        {{ t('propertyManagement.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>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import {
    getPropertyManagementPageAPI,
    reportPropertyManagementAPI,
    type PropertyManagementItem,
} from '/@/api/investment/propertyManagement';
import { useRouter } from 'vue-router';

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

const filters = reactive({
    enterpriseName: '',
    creditCode: '',
});

const tableData = ref<PropertyManagementItem[]>([]);
const tableLoading = ref(false);
const totalCount = ref(0);
const currentRow = ref<PropertyManagementItem | null>(null);

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

const mapPushStatus = (status?: string | null): PropertyManagementItem['pushStatus'] => {
    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('失败') ||
        status.includes('驳回')
    ) {
        return 'failed';
    }
    return 'pending';
};

const buildQueryParams = () => ({
    page: pagination.page,
    size: pagination.pageSize,
    enterpriseName: filters.enterpriseName || undefined,
    creditCode: filters.creditCode || undefined,
});

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

const handleCurrentChange = (row: PropertyManagementItem | null) => {
    currentRow.value = row;
};

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

const handleReset = () => {
    filters.enterpriseName = '';
    filters.creditCode = '';
    pagination.page = 1;
    fetchPropertyList();
};

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

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

const handleCreate = () => {
    message.info(t('propertyManagement.messages.createNew'));
    // TODO: 跳转到新增页面
    router.push({ path: '/workbench/miOwLibr/ownershipCreate/index' });
};

const handleCreateUpdate = () => {
    message.info(t('propertyManagement.messages.createUpdate'));
    // TODO: 跳转到更新页面
};

const handleView = async (row: PropertyManagementItem) => {
    try {
        // TODO: 打开详情抽屉或跳转到详情页
        // const detail = await getPropertyManagementDetailAPI(row.id);
        message.info(`${row.enterpriseName} ${t('propertyManagement.messages.viewDetail')}`);
    } catch (error: any) {
        message.error(error?.msg || error?.message || '获取详情失败');
    }
};

const handleReport = async (row: PropertyManagementItem) => {
    try {
        await reportPropertyManagementAPI(row.id);
        message.success('报送成功');
        fetchPropertyList();
    } catch (error: any) {
        message.error(error?.msg || error?.message || '报送失败');
    }
};

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

<style scoped>
.property-management-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>
