<template>
    <div class="scholar-db-container">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-user"></i> {{ $t('sidebar.expertDatabase') }}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="toolbar">
            <div class="filters">
                <el-form :inline="true" :model="query" size="small">
                    <el-form-item label="">
                        <el-cascader
                            ref="cascader"
                            @change="handleChange"
                            v-model="major_id"
                            :placeholder="$t('expertDatabase.fieldSelectPlaceholder')"
                            :options="options"
                            :props="getProps()"
                            style="width: 260px"
                        ></el-cascader>
                    </el-form-item>
                    <el-form-item label="">
                        <el-input
                            v-model="query.keyword"
                            :placeholder="$t('expertDatabase.keywordPlaceholder')"
                            clearable
                            style="width: 260px"
                        />
                    </el-form-item>
                 
                    <el-form-item label="">
                        <el-input
                            v-model="query.field"
                            :placeholder="$t('expertDatabase.fieldPlaceholder')"
                            clearable
                            style="width: 260px"
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" :loading="loading" @click="handleSearch">
                            {{ $t('expertDatabase.searchBtn') }}
                        </el-button>
                        <el-button @click="handleReset">{{ $t('expertDatabase.resetBtn') }}</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="actions">
                <el-button type="success" icon="el-icon-download" @click="handleExport" :loading="exportLoading">
                    {{ $t('expertDatabase.downloadExcelBtn') }}
                </el-button>
            </div>
        </div>

        <el-card class="table-card" shadow="never">
            <el-table :data="list" border stripe v-loading="loading" header-row-class-name="dark-table-header">
                <el-table-column type="index" :label="$t('expertDatabase.table.no')" width="70" align="center"></el-table-column>
                <el-table-column prop="name" :label="$t('expertDatabase.columns.baseInfo')" min-width="220">
                    <template slot-scope="scope">
                        <div>
                            <p class="info-row">
                                <span class="label">{{ $t('expertDatabase.fields.nameLabel') }}</span><span class="value bold">{{ scope.row.name }}</span>
                            </p>
                            <p class="info-row">
                                <span class="label">{{ $t('expertDatabase.fields.emailLabel') }}</span><span class="value link">{{ scope.row.email }}</span>
                            </p>
                            <p class="info-row" style="margin-top: 10px; font-size: 12px">
                                <span class="label">{{ $t('expertDatabase.fields.acquisitionTimeLabel') }}</span>
                                <span class="value time">{{ scope.row.ctime_text ? scope.row.ctime_text : $t('expertDatabase.emptyMark') }}</span>
                            </p>

                            <span class="custom-tag">{{ scope.row.state_text }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="country" :label="$t('expertDatabase.columns.country')" min-width="100" />
                <el-table-column prop="affiliation" :label="$t('expertDatabase.columns.affiliation')" min-width="460" />
                <el-table-column prop="fieldDisplay" :label="$t('expertDatabase.columns.researchAreas')" min-width="260">
                    <template slot-scope="scope">
                        <div v-for="(field, index) in scope.row.fields" :key="index">
                            <span>
                                <span style="color: #006699">{{ index + 1 }}.</span>
                                {{ field.field }}
                            </span>
                        </div>
                        <el-button
                            v-if="scope.row.fields && scope.row.fields.length"
                            type="text"
                            size="small"
                            class="view-all-btn"
                            @click.stop="openFieldDetail(scope.row)"
                        >
                            {{ $t('expertDatabase.viewAllInfo') }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog
                :title="$t('expertDatabase.detailDialogTitle')"
                :visible.sync="fieldDetailVisible"
                width="1200px"
                append-to-body
                destroy-on-close
                class="field-detail-dialog"
            >
                <p v-if="fieldDetailExpert" class="field-detail-name">
                    <span class="label">{{ $t('expertDatabase.fields.nameLabel') }}</span>
                    <span class="value bold">{{ fieldDetailExpert.name }}</span>
                </p>
                <el-table v-if="fieldDetailRows.length" :data="fieldDetailRows" border stripe size="small" max-height="420">
                    <el-table-column type="index" :label="$t('expertDatabase.table.no')" width="56" align="center" />
                    <el-table-column prop="field" :label="$t('expertDatabase.detailColField')" min-width="140"  />
                    <el-table-column prop="paper_title" :label="$t('expertDatabase.detailColPaper')" min-width="220"  />
                    <el-table-column prop="paper_journal" :label="$t('expertDatabase.detailColJournal')" min-width="140" />
                </el-table>
                <p v-else class="field-detail-empty">{{ $t('expertDatabase.noFieldDetail') }}</p>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="fieldDetailVisible = false">{{ $t('expertDatabase.detailClose') }}</el-button>
                </span>
            </el-dialog>

            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :page-sizes="[10, 20, 50]"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                />
            </div>
        </el-card>
    </div>
</template>

<script>
import Common from '@/components/common/common';
export default {
    name: 'expertDatabase',
    data() {
        return {
            mediaUrl: Common.mediaUrl,
            major_id: [],
            query: {
                major_id: null,
                keyword: '',
                field: '',
                pageIndex: 1,
                pageSize: 10
            },
            options: [],
            list: [],
            total: 0,
            loading: false,
            exportLoading: false,
            fieldDetailVisible: false,
            fieldDetailExpert: null,
            fieldDetailRows: []
        };
    },
    created() {
        this.loadFields();
        this.fetchList();
    },
    methods: {
        loadFields() {
            this.$api.post('api/Major/getMajorList', {}).then((res) => {
                const transformData = (data) => {
                    return data.map((item) => {
                        const transformedItem = {
                            ...item,
                            value: item.major_id,
                            label: `${item.major_title}`
                        };
                        if (item.children && item.children.length > 0) {
                            transformedItem.children = transformData(item.children);
                        }
                        return transformedItem;
                    });
                };
                const root = (res.data.majors || []).find((item) => item.major_id == 1);
                const data = root && root.children ? transformData(root.children) : [];
                this.options = [...data];
            });
        },
        handleChange() {
            this.$nextTick(() => {
                if (this.$refs.cascader && this.$refs.cascader.dropDownVisible !== undefined) {
                    this.$refs.cascader.dropDownVisible = false;
                }
                this.query.major_id = this.major_id[this.major_id.length - 1] || null;
                this.query.pageIndex = 1;
                this.fetchList();
            });
        },
        getProps() {
            return {
                value: 'value',
                label: 'label',
                children: 'children',
                checkStrictly: true,
                expandTrigger: 'hover'
            };
        },
        async fetchList() {
            this.loading = true;
            try {
                const params = {
                    major_id: this.query.major_id,
                    keyword: this.query.keyword,
                    field: this.query.field,
                    pageIndex: this.query.pageIndex,
                    pageSize: this.query.pageSize
                };
                const res = await this.$api.post('api/expert_manage/getList', params);
                if (res && res.code === 0 && res.data) {
                    const rawList = res.data.list || [];
                    this.list = rawList.map((item) => {
                        const fieldArray = item.fields || [];
                        const fieldNames = fieldArray.map((f) => f.field).join(', ');
                        return {
                            ...item,
                            fieldDisplay: fieldNames
                        };
                    });
                    this.total = res.data.total || 0;
                } else {
                    this.list = [];
                    this.total = 0;
                }
            } catch (e) {
                this.list = [];
                this.total = 0;
            } finally {
                this.loading = false;
            }
        },
        handleSearch() {
            this.query.pageIndex = 1;
            this.fetchList();
        },
        handleReset() {
            this.major_id = [];
            this.query = {
                major_id: null,
                keyword: '',
                field: '',
                pageIndex: 1,
                pageSize: 10
            };
            this.fetchList();
        },
        handleSizeChange(size) {
            this.query.pageSize = size;
            this.query.pageIndex = 1;
            this.fetchList();
        },
        handlePageChange(page) {
            this.query.pageIndex = page;
            this.fetchList();
        },
        openFieldDetail(row) {
            const empty = this.$t('expertDatabase.detailCellEmpty');
            this.fieldDetailExpert = row || null;
            const fields = (row && row.fields) || [];
            this.fieldDetailRows = fields.map((f) => ({
                field: (f && f.field) || empty,
                paper_title: (f && (f.paper_title || f.title)) || empty,
                paper_journal: (f && (f.paper_journal || f.journal)) || empty
            }));
            this.fieldDetailVisible = true;
        },
        async handleExport() {
            if (!this.query.major_id && !this.query.keyword && !this.query.field) {
                this.$message.warning(this.$t('expertDatabase.exportWarn'));
                return;
            }
            this.exportLoading = true;
            try {
                const params = {
                    major_id: this.query.major_id,
                    keyword: this.query.keyword,
                    field: this.query.field
                };
                const res = await this.$api.post('api/expert_manage/exportExcel', params);
                if (res && res.code === 0 && res.data && res.data.file_url) {
                    window.open(this.mediaUrl + res.data.file_url, '_blank');
                } else {
                    this.$message.error(res.msg || this.$t('expertDatabase.exportFailed'));
                }
            } catch (e) {
                this.$message.error(e.msg || this.$t('expertDatabase.exportFailed'));
            } finally {
                this.exportLoading = false;
            }
        }
    }
};
</script>

<style scoped>
.scholar-db-container {
    padding: 0 10px;
}
.toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
    margin-top: 15px;
}
.filters {
    flex: 1;
    margin: 0 20px;
    margin-left: 0;
}
.form-line-break {
    flex-basis: 100%;
    width: 100%;
    height: 0;
}
.actions {
    white-space: nowrap;
}
.table-card {
    margin-top: 10px;
}
.pagination {
    margin-top: 15px;
    text-align: right;
}
::v-deep .dark-table-header th {
    background-color: #f5f7fa;
    font-weight: 600;
}
::v-deep .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
    margin-bottom: 0;
}
.custom-tag {
    display: inline-block;
    position: absolute;
    right: 6px;
    top: 0px;
    color: #ce4f15;
    font-size: 12px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.info-row {
    margin-bottom: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    line-height: 1.2;
    font-family: Arial, sans-serif;
}
.label {
    color: #999;
    margin-right: 8px;
    flex-shrink: 0;
}
.value {
    color: #333;
}
.value.bold {
    font-weight: bold;
    font-size: 15px;
}
.value.link {
    color: #0066a1;
}
.value.time {
    color: #888;
}
.view-all-btn {
    margin-top: 8px;
    padding: 0;
}
.field-detail-name {
    margin: 0 0 12px;
    font-size: 14px;
}
.field-detail-empty {
    margin: 16px 0;
    color: #909399;
    font-size: 13px;
}
</style>

