<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>{{ $t('sidebar.tools') }}</el-breadcrumb-item>
                <el-breadcrumb-item>{{ $t('sidebar.scholarCrawlers') }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-card class="box-card">
                <el-form
                    ref="searchForm"
                    :model="form"
                    :rules="rules"
                    label-width="80px"
                    :inline="false"
                    class="search-form"
                    @submit.native.prevent
                >
                    <div class="search-bar">
                        <el-form-item label="Keyword" prop="keyword" class="search-input-item">
                            <el-input
                                v-model="form.keyword"
                                placeholder="Please input keyword"
                                clearable
                                @keyup.enter.native="handleSearch"
                            />
                        </el-form-item>
                        <div class="search-actions">
                            <el-button type="primary" icon="el-icon-search" :loading="loading" @click="handleSearch">
                                Search
                            </el-button>
                            <el-button
                                type="success"
                                icon="el-icon-download"
                                :loading="exportLoading"
                                :disabled="!form.keyword"
                                @click="handleExport"
                            >
                                Export Excel
                            </el-button>
                        </div>
                    </div>
                </el-form>
            </el-card>

            <el-card
                v-if="hasSearched"
                class="box-card"
                style="margin-top: 20px"
            >
                <div class="total-bar">
                    Total: <span class="total-number">{{ total }}</span>
                </div>
                <el-table
                    v-loading="loading"
                    :data="tableData"
                    border
                    stripe
                    style="width: 100%;"
                    class="table"
                    header-cell-class-name="table-header"
                    empty-text="No data, please search first"
                >
                    <el-table-column type="index" label="No." width="60" align="center" :index="tableIndex" />
                    <el-table-column
                        v-for="col in columns"
                        :key="col"
                        :prop="col"
                        :label="formatColumnLabel(col)"
                        :min-width="getColumnWidth(col)"
                        :width="getColumnFixedWidth(col)"
                    />
                    <el-table-column label="Paper Count" width="140" align="center">
                        <template slot-scope="scope">
                            <div class="paper-count-cell">
                                <span class="paper-count-number">{{ scope.row.paperCount }}</span>
                                <el-button
                                    v-if="scope.row.paperCount"
                                    type="primary"
                                    size="mini"
                                    plain
                                    @click="showPapers(scope.row)"
                                >
                                    Detail
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination
                        background
                        layout="total, sizes, prev, pager, next"
                        :total="total"
                        :current-page="page"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="per_page"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>

            <el-dialog title="Papers" :visible.sync="papersDialogVisible" width="70vw">
                <div class="paper-expert-info">
                    <div><strong>Name:</strong> {{ currentExpert.name || currentExpert.realname }}</div>
                    <div><strong>Email:</strong> {{ currentExpert.email }}</div>
                    <div><strong>Affiliation:</strong> {{ currentExpert.affiliation }}</div>
                </div>
                <el-table :data="currentPapers" border stripe style="width: 100%">
                    <el-table-column type="index" label="No." width="60" align="center" />
                    <el-table-column prop="article_id" label="Article ID" width="180" />
                    <el-table-column prop="journal" label="Journal" width="340" />
                    <el-table-column prop="title" label="Title" />
                </el-table>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="papersDialogVisible = false">Close</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
export default {
    name: 'scholarCrawlers',
    data() {
        return {
            form: {
                keyword: '',
            },
            rules: {
                keyword: [
                    {
                        required: true,
                        message: 'Please input keyword',
                        trigger: 'blur',
                    },
                ],
            },
            tableData: [],
            columns: [],
            loading: false,
            exportLoading: false,
            papersDialogVisible: false,
            currentPapers: [],
            currentExpert: {},
            total: 0,
            page: 1,
            per_page: 20,
            hasSearched: false,
        };
    },
    methods: {
        tableIndex(index) {
            return (this.page - 1) * this.per_page + index + 1;
        },
        handlePageChange(val) {
            this.page = val;
            this.doSearch();
        },
        handleSizeChange(val) {
            this.per_page = val;
            this.page = 1;
            this.doSearch();
        },
        doSearch() {
            this.loading = true;
            this.hasSearched = true;
            this.$api
                .post('/api/expert_finder/search', {
                    keyword: this.form.keyword,
                    page: this.page,
                    per_page: this.per_page,
                })
                .then((res) => {
                    if (res && res.code === 0 && res.data) {
                        const list =
                            Array.isArray(res.data.experts) && res.data.experts.length
                                ? res.data.experts
                                : [];
                        const listWithCount = list.map((item) => ({
                            ...item,
                            paperCount: Array.isArray(item.papers)
                                ? item.papers.length
                                : item.paper_count || item.paperCount || 0,
                        }));
                        this.tableData = listWithCount;
                        this.total = res.data.total != null ? Number(res.data.total) : listWithCount.length;
                        this.columns = listWithCount.length
                            ? Object.keys(listWithCount[0]).filter(
                                  (key) =>
                                      key !== 'papers' &&
                                      key !== 'paperCount' &&
                                      key !== 'paper_count'
                              )
                            : [];
                    } else {
                        this.tableData = [];
                        this.columns = [];
                        this.total = 0;
                        if (res && res.msg) {
                            this.$message.error(res.msg);
                        } else {
                            this.$message.error('No expert found, please try again');
                        }
                    }
                })
                .catch(() => {
                    this.tableData = [];
                    this.columns = [];
                    this.total = 0;
                    this.$message.error('Request error, please try again');
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        handleSearch() {
            this.$refs.searchForm.validate((valid) => {
                if (!valid) {
                    return;
                }
                this.page = 1;
                this.doSearch();
            });
        },
        async handleExport() {
            if (!this.form.keyword) {
                this.$message.warning('Please input keyword first');
                return;
            }
            this.exportLoading = true;
            try {
                const res = await this.$api.post('/api/expert_finder/export', {
                    keyword: this.form.keyword,
                    page: this.page,
                    per_page: this.per_page,
                });

                if (res && (res.code === 0 || res.status === 1)) {
                    const url =
                        (res.data && (res.data.url || res.data.link)) ||
                        res.url ||
                        (typeof res.data === 'string' ? res.data : '');

                    if (!url) {
                        this.$message.error('No download url returned from server');
                    } else {
                        const link = document.createElement('a');
                        link.href = url;
                        const parts = url.split('/');
                        link.download = parts[parts.length - 1] || `scholar_${this.form.keyword}.xlsx`;
                        link.target = '_blank';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        this.$message.success('Export success');
                    }
                } else {
                    this.$message.error((res && res.msg) || 'Export failed, please try again');
                }
            } catch (e) {
                this.$message.error('Request error, please try again');
            } finally {
                this.exportLoading = false;
            }
        },
        formatColumnLabel(key) {
            if (!key) return '';
            return key
                .split('_')
                .map((word) => (word ? word.charAt(0).toUpperCase() + word.slice(1) : ''))
                .join(' ');
        },
        getColumnWidth(key) {
            if (!key) return 140;
            const lower = key.toLowerCase();
            if (lower === 'name' || lower === 'realname') {
                return 180;
            }
            if (lower === 'affiliation' || lower === 'organization' || lower === 'institution') {
                return 420;
            }
            if (lower === 'email') {
                return 300;
            }
            return 140;
        },
        getColumnFixedWidth(key) {
            if (!key) return null;
            const lower = key.toLowerCase();
            if (lower === 'name' || lower === 'realname') {
                return 180;
            }
            if (lower === 'email') {
                return 300;
            }
            return null;
        },
        showPapers(row) {
            const papers = Array.isArray(row.papers) ? row.papers : [];
            if (!papers.length) {
                this.$message.info('No papers found');
                return;
            }
            this.currentExpert = row;
            this.currentPapers = papers;
            this.papersDialogVisible = true;
        },
    },
};
</script>

<style scoped>
.container {
    padding: 20px;
}

.box-card {
    margin-bottom: 10px;
}

.search-form {
    width: 100%;
}

.search-bar {
    display: flex;
    align-items: center;
    width: 100%;
}

.search-input-item {
    flex: 1;
    margin-bottom: 0;
}

.search-input-item .el-form-item__content {
    width: 100%;
}

.search-input-item .el-input {
    width: 100%;
}

.search-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-left: 16px;
}

.paper-count-cell {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.paper-count-number {
    font-weight: 700;
    font-size: 16px;
    color: #006699;
}

.table .cell {
    white-space: normal;
    word-break: break-word;
}

.paper-expert-info {
    margin-bottom: 15px;
    padding: 10px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-size: 13px;
    line-height: 1.6;
}

.paper-expert-info > div + div {
    margin-top: 4px;
}

.total-bar {
    margin-bottom: 10px;
    font-size: 13px;
    color: #666;
    text-align: right;
}

.total-number {
    font-weight: 600;
    color: #006699;
}

.pagination {
    margin-top: 16px;
    text-align: right;
}
</style>

