<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">

            <!-- 标题 -->
            <el-row class="mb10 header-summary">
                <div class="title">{{ t('expertLibrary.title') }}</div>
            </el-row>

            <!-- 工具栏 + 搜索 -->
            <el-row class="toolbar-row mb10">
                <div class="left-actions">
                    <el-button icon="Download" @click="exportExcel">{{ t('common.exportBtn') || '导出' }}</el-button>
                    <el-button plain class="ml10" :disabled="multiple" icon="Delete" type="primary"
                        @click="handleBatchDelete(selectIds)">{{ t('common.delBtn') || '删除' }}</el-button>
                </div>
                <div class="right-search">
                    <el-form class="search-form" :inline="true" :model="queryForm" @keyup.enter="getDataList"
                        ref="queryRef">
                        <el-form-item :label="t('expertLibrary.form.name')" prop="expertName">
                            <el-input :placeholder="t('expertLibrary.placeholder.input')" style="max-width: 180px"
                                v-model="queryForm.expertName" />
                        </el-form-item>
                        <el-form-item :label="t('expertLibrary.form.field')" prop="technologyField">
                            <el-input :placeholder="t('expertLibrary.placeholder.input')" style="max-width: 180px"
                                v-model="queryForm.technologyField" />
                        </el-form-item>
                        <el-form-item :label="t('expertLibrary.form.status')" prop="externalStatus">
                            <el-select style="max-width: 160px" clearable v-model="queryForm.externalStatus"
                                :placeholder="t('expertLibrary.placeholder.select')">
                                <el-option :label="t('expertLibrary.status.pending')" value="0" />
                                <el-option :label="t('expertLibrary.status.reviewing')" value="1" />
                                <el-option :label="t('expertLibrary.status.approved')" value="2" />
                                <el-option :label="t('expertLibrary.status.rejected')" value="3" />
                            </el-select>
                        </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="tableData" border style="width: 100%;" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="48" />
                <el-table-column type="index" :label="t('expertLibrary.table.index')" width="60" />
                <el-table-column prop="expertName" :label="t('expertLibrary.table.name')" min-width="140" />
                <el-table-column prop="contactInformation" :label="t('expertLibrary.table.contact')" min-width="140" />
                <el-table-column prop="technologyField" :label="t('expertLibrary.table.field')" min-width="140" />
                <el-table-column prop="professionalTitle" :label="t('expertLibrary.table.title')" min-width="120" />
                <el-table-column prop="workUnit" :label="t('expertLibrary.table.company')" min-width="160" />
                <el-table-column prop="level" :label="t('expertLibrary.table.level')" min-width="100">
                    <template #default="{ row }">
<!--											<span>{{ levelLabel(row.level) }}</span>-->
                       <span>{{ level.find((item: Enums) => item.value === row.level)?.label }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="t('expertLibrary.table.status')" min-width="120">
                    <template #default="{ row }">
                        <el-tag :type="['info', 'primary', 'success', 'danger'][row.status]">{{ externalStatusLabel(row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="t('expertLibrary.table.action')" width="100" fixed="right">
                    <template #default="{ row }">
                        <el-button link type="primary" @click="handleView(row)">{{ t('common.viewBtn') || '查看'
                        }}</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="mt15 flex justify-end">
                <el-pagination background layout="sizes, prev, pager, next, jumper, total" :total="pagination.total"
                    :page-sizes="[10, 20, 50, 100]" v-model:page-size="pagination.size"
                    v-model:current-page="pagination.page" @size-change="handleSizeChange"
                    @current-change="handlePageChange" />
            </div>

            <ExpertDetailDialog v-model:visible="detailVisible" :detail="currentDetail" :meta="detailMeta" />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage, useMessageBox } from '/@/hooks/message';
import ExpertDetailDialog from '/@/components/investment/ExpertDetailDialog.vue';
import { getExpertInformationPageAPI, deleteExpertInformationsAPI } from '/@/api/investment/cooperationUnit';
import {Enums, level} from "/@/hooks/enums";

const { t } = useI18n();

// 查询与分页
const queryRef = ref();
const queryForm = reactive({
    expertName: '',
    technologyField: '',
    externalStatus: '',
});

const pagination = reactive({
    page: 1,
    size: 10,
    total: 0,
});

const loading = ref(false);
const tableData = ref<any[]>([]);

// 选择
const multiple = ref(true);
const selectIds = ref<(string | number)[]>([]);

const extractPageData = (response: any) => {
    const records = response?.records ?? response?.data?.records ?? [];
    const total = response?.total ?? response?.data?.total ?? 0;
    const page = response?.current ?? response?.page ?? response?.data?.current ?? pagination.page;
    const size = response?.size ?? response?.data?.size ?? pagination.size;
    return { records, total, page, size };
};

const getDataList = async () => {
    loading.value = true;
    try {
        const params = {
            page: pagination.page,
            size: pagination.size,
            ...queryForm,
        };
        const res = await getExpertInformationPageAPI(params);
        const { records, total, page, size } = extractPageData(res);
        tableData.value = records;
        pagination.total = total;
        pagination.page = page;
        pagination.size = size;
    } finally {
        loading.value = false;
    }
};

const resetQuery = () => {
    queryForm.expertName = '';
    queryForm.technologyField = '';
    queryForm.externalStatus = '';
    pagination.page = 1;
    getDataList();
};

const handleSelectionChange = (rows: any[]) => {
    selectIds.value = rows.map(r => r.id);
    multiple.value = selectIds.value.length === 0;
};

const handleBatchDelete = async (ids: (string | number)[]) => {
    if (!ids?.length) return;
    await useMessageBox().confirm(t('common.delConfirmText'));
    await deleteExpertInformationsAPI(ids);
    useMessage().success(t('common.delSuccessText'));
    getDataList();
};

const exportExcel = () => {
    useMessage().info(t('common.exportOkText') || '导出任务已提交');
};

// 详情查看
const detailVisible = ref(false);
const currentDetail = ref<any>({});
const detailMeta = reactive({
    reporter: 'xxx',
    unit: 'xxx',
    date: new Date().toISOString().slice(0, 10),
});
const handleView = (row: any) => {
    // 转换为详情组件需要的格式
    const attachmentUrl = row.attachmentUrl ? JSON.parse(row.attachmentUrl) : []
    const attachments = attachmentUrl.map((url: string) => {
        return { url, name: url.split('fileName=')[1] }
    })
    // 转换为详情组件需要的格式
    const testimonyMaterials = row.testimonyMaterials ? JSON.parse(row.testimonyMaterials) : []
    const evidences = testimonyMaterials.map((url: string) => {
        return { url, name: url.split('fileName=')[1] }
    })
    currentDetail.value = { ...row,
        attachments,
        evidences,
    };
    detailVisible.value = true;
};

const levelLabel = (val: string) => {
    if (val === 'national') return t('expertApply.level.national');
    if (val === 'provincial') return t('expertApply.level.provincial');
    if (val === 'city') return t('expertApply.level.city');
    return val || '-';
};
const externalStatusLabel = (val: string) => {
    return {
        '0': t('expertLibrary.status.pending'),
        '1': t('expertLibrary.status.reviewing'),
        '2': t('expertLibrary.status.approved'),
        '3': t('expertLibrary.status.rejected'),
    }[val] || 1
};

// 初始加载
const handleSizeChange = (val: number) => {
    pagination.size = val;
    pagination.page = 1;
    getDataList();
};

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

getDataList();
</script>

<style scoped>
.toolbar-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

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

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

.header-summary .title {
    margin: 0 auto;
    font-size: 18px;
    font-weight: 600;
}

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