<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <div class="page-title">{{ t('cooperationUnitLibrary.title') }}</div>
            <el-row class="toolbar-row ml10">
                <div class="left-actions">
                    <el-button icon="Download" @click="exportExcel">{{ $t('common.exportBtn') || '导出' }}</el-button>
                    <el-button plain :disabled="multiple" @click="handleBatchDelete(selectIds)" class="ml10"
                        icon="Delete" type="primary">
                        {{ $t('common.delBtn') }}
                    </el-button>
                </div>
                <div class="right-search">
                    <el-form :inline="true" :model="queryForm" @keyup.enter="getDataList" ref="queryRef">
                        <el-form-item :label="t('cooperationUnit.cooperationName')" prop="cooperationName">
                            <el-input :placeholder="t('cooperationUnit.inputCooperationNameTip')"
                                style="max-width: 180px" v-model="queryForm.cooperationName" />
                        </el-form-item>
                        <el-form-item :label="t('cooperationUnit.cooperationNature')" prop="cooperationNature">
                            <el-select
                                v-model="queryForm.cooperationNature"
                                clearable
                                style="max-width: 180px"
                                :placeholder="t('cooperationUnit.selectCooperationNatureTip')"
                            >
                                <el-option
                                    v-for="option of cooperationPartnerNatureOptions"
                                    :key="option.value"
                                    :label="option.label"
                                    :value="option.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="t('cooperationUnit.unitContact')" prop="unitContactPerson">
                            <el-input :placeholder="t('cooperationUnit.inputUnitContactTip')" style="max-width: 180px"
                                v-model="queryForm.unitContactPerson" />
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="getDataList" icon="Search" type="primary">{{ $t('common.queryBtn')
                                }}</el-button>
                            <el-button @click="resetQuery" icon="Refresh">{{ $t('common.resetBtn') }}</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-row>

            <el-table :data="dataList" @selection-change="handleSelectionChange" max-height="560" style="width: 100%"
                v-loading="loading" border>
                <el-table-column align="center" type="selection" width="40" />
                <el-table-column :label="t('cooperationUnit.index')" type="index" width="60" />
                <el-table-column :label="t('cooperationUnit.cooperationName')" prop="cooperationName" min-width="150"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.provinceCity')" prop="provinceCityLabel" min-width="120"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.cooperationNature')" prop="cooperationNature" header-class-name="red-header" min-width="140"
                    show-overflow-tooltip >
									<template #default="{row}">
										<span>{{cooperationPartnerNatureOptions.find((item:Enums) => item.value === row.cooperationNature)?.label}}</span>
									</template>
								</el-table-column>
                <el-table-column :label="t('cooperationUnit.industryField')" prop="cooperationIndustry" min-width="150"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.cooperationBusiness')" prop="proposedBusinessCooperation"
                    min-width="180" show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.cooperationAdvantage')" prop="cooperationAdvantage"
                    min-width="160" show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.cooperationStatus')" prop="cooperationStatus"
																 min-width="120" show-overflow-tooltip ></el-table-column>
                <el-table-column :label="t('cooperationUnit.cooperationStartTime')" prop="startTime" min-width="140"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.cooperationEndTime')" prop="endTime" min-width="140"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.unitAddress')" prop="unitAddress" min-width="200"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.unitContact')" prop="unitContactPerson" min-width="140"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.departmentPosition')" prop="contactPersonDept"
                    min-width="150" show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.phone')" prop="contactPersonPhone" min-width="150"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.potentialOpportunity')" prop="potentialCooperation"
                    min-width="180" show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.businessCompany')" prop="businessConnectionCompany"
                    min-width="160" show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.actualController')" prop="cooperationController"
                    header-class-name="red-header" min-width="140" show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.shareholdingRatio')" prop="shareholdingRatio"
                    header-class-name="red-header" min-width="120" show-overflow-tooltip />
                <!-- <el-table-column :label="t('cooperationUnitLibrary.status')" prop="status" min-width="120"
                    show-overflow-tooltip /> -->
                <el-table-column :label="t('cooperationUnit.reporter')" prop="createBy" min-width="120"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.reportingUnit')" prop="reportingUnit" min-width="120"
                    show-overflow-tooltip />
                <el-table-column :label="t('cooperationUnit.createTime')" prop="createTime" min-width="170"
                    show-overflow-tooltip />
                <!-- <el-table-column :label="t('cooperationUnit.updateTime')" prop="updateTime" min-width="170"
                    show-overflow-tooltip /> -->
            </el-table>
            <Pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="pagination" />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
    getExternalCooperationUnitsPageAPI,
    deleteExternalCooperationUnitsAPI,
    type ExternalCooperationUnitItemT,
} from '/@/api/investment/cooperationUnit';
import { useMessage, useMessageBox } from '/@/hooks/message';
import {cooperationPartnerNatureOptions, Enums, projectStatusOptions} from '/@/hooks/enums'

const { t } = useI18n();

interface CooperationUnitLibraryItem extends ExternalCooperationUnitItemT {
    provinceCityLabel?: string;
}

const queryRef = ref();
const loading = ref(false);
const dataList = ref<CooperationUnitLibraryItem[]>([]);
const selectIds = ref<string[]>([]);
const multiple = ref(true);
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0,
});

const queryForm = reactive({
    cooperationName: '',
    cooperationNature: '',
    unitContactPerson: '',
});

const formatProvinceCity = (province?: string | number, city?: string | number) => {
    const values = [province, city].filter((item) => item !== undefined && item !== null && item !== '');
    return values.length ? values.join('/') : '--';
};

const extractPageData = <
    T extends {
        records?: U[];
        total?: number;
        current?: number;
        size?: number;
        page?: number;
        data?: { records?: U[]; total?: number; current?: number; size?: number; page?: number };
    },
    U,
>(
    response: T
) => {
    const records = (response.records || response.data?.records || []) as U[];
    const total = response.total ?? response.data?.total ?? 0;
    const current = response.current ?? response.page ?? response.data?.current ?? response.data?.page;
    const size = response.size ?? response.data?.size;
    return { records, total, current, size };
};

const getDataList = async () => {
    loading.value = true;
    try {
        const params = {
            ...queryForm,
            page: pagination.current,
            size: pagination.size,
        };
        const res = await getExternalCooperationUnitsPageAPI(params);
        const { records, total, current, size } = extractPageData<typeof res, ExternalCooperationUnitItemT>(res);
        dataList.value = records.map((item) => ({
            ...item,
            provinceCityLabel: formatProvinceCity(item.province, item.city),
        }));
        const numericTotal = typeof total === 'number' && !Number.isNaN(total) ? total : records.length;
        pagination.total = numericTotal;
        pagination.current = current || pagination.current;
        pagination.size = size || pagination.size;
    } finally {
        loading.value = false;
    }
};
const currentChangeHandle = (val: number) => {
    pagination.current = val;
    getDataList();
};
const sizeChangeHandle = (val: number) => {
    pagination.size = val;
    getDataList();
};
const resetQuery = () => {
    queryRef.value?.resetFields();
    getDataList();
};
const handleSelectionChange = (rows: Array<{ id: string | number }>) => {
    selectIds.value = rows.map(({ id }) => String(id));
    multiple.value = !rows.length;
};
const handleBatchDelete = async (ids: string[]) => {
    if (!ids?.length) return;
    await useMessageBox().confirm(t('common.delConfirmText'));
    await deleteExternalCooperationUnitsAPI(ids);
    useMessage().success(t('common.delSuccessText'));
    getDataList();
};
const exportExcel = () => {
    useMessage().info('导出功能由后端流式返回，已接入统一导出按钮');
};

getDataList();
</script>

<style scoped>
.page-title {
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 16px 0;
}

.toolbar-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.left-actions {
    display: flex;
    align-items: center;
}

.right-search {
    display: flex;
    align-items: center;
}

.red-text {
    color: var(--el-color-danger);
}

:deep(.el-table th.red-header .cell) {
    color: var(--el-color-danger);
}
</style>
