<template>
    <div class="country-manage">
        <div class="crumbs">
            <el-breadcrumb separator="/">
               
                <el-breadcrumb-item> <i class="el-icon-place"></i> {{ $t('countryManagement.title') }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="toolbar">
            <el-form :inline="true" :model="query" size="small">
                <el-form-item>
                    <el-input
                        v-model="query.keyword"
                        clearable
                        :placeholder="$t('countryManagement.keywordPlaceholder')"
                        style="width: 260px"
                    />
                </el-form-item>
                <el-form-item>
                    <el-select
                        v-model="query.partition"
                        clearable
                        :placeholder="$t('countryManagement.partitionAll')"
                        style="width: 140px"
                        @change="onPartitionChange"
                    >
                        <el-option :label="$t('countryManagement.partitionAll')" value="" />
                        <el-option :label="$t('countryManagement.partition1')" value="1" />
                        <el-option :label="$t('countryManagement.partition2')" value="2" />
                        <el-option :label="$t('countryManagement.partition3')" value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" :loading="loading" @click="handleSearch">
                        {{ $t('countryManagement.searchBtn') }}
                    </el-button>
                    <el-button @click="handleReset">{{ $t('countryManagement.resetBtn') }}</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-card shadow="never" class="table-card">
            <el-table :data="list" border stripe v-loading="loading" header-row-class-name="dark-table-header">
                <el-table-column type="index" :label="$t('countryManagement.table.no')" width="70" align="center" />
                <el-table-column prop="zh_name" :label="$t('countryManagement.table.zhName')" min-width="140" show-overflow-tooltip />
                <el-table-column prop="en_name" :label="$t('countryManagement.table.enName')" min-width="160" show-overflow-tooltip />
                <el-table-column prop="code" :label="$t('countryManagement.table.code')" width="100" align="center" />
                <el-table-column prop="partition" :label="$t('countryManagement.table.partition')" width="100" align="center" />
                <el-table-column :label="$t('countryManagement.table.actions')" width="220" align="center" fixed="right">
                    <template slot-scope="scope">
                        <div class="table-row-actions">
                            <el-button
                                type="primary"
                                plain
                                size="mini"
                                icon="el-icon-edit"
                                class="action-btn action-btn--edit"
                                @click="openEdit(scope.row)"
                            >
                                {{ $t('countryManagement.edit') }}
                            </el-button>
                            <el-button
                                type="danger"
                                plain
                                size="mini"
                                icon="el-icon-delete"
                                class="action-btn action-btn--delete"
                                @click="handleDelete(scope.row)"
                            >
                                {{ $t('countryManagement.delete') }}
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

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

        <el-dialog
            :title="$t('countryManagement.editTitle')"
            :visible.sync="editVisible"
            width="580px"
            append-to-body
            destroy-on-close
            @closed="resetForm"
        >
            <el-form ref="editForm" :model="form" :rules="rules" label-width="150px" size="small" class="country-edit-form">
                <el-form-item :label="$t('countryManagement.form.zhName')" prop="zh_name">
                    <el-input v-model="form.zh_name" />
                </el-form-item>
                <el-form-item :label="$t('countryManagement.form.enName')" prop="en_name">
                    <el-input v-model="form.en_name" />
                </el-form-item>
                <el-form-item :label="$t('countryManagement.form.code')" prop="code">
                    <el-input v-model="form.code" />
                </el-form-item>
                <el-form-item :label="$t('countryManagement.form.partition')" prop="partition">
                    <el-select v-model="form.partition" style="width: 100%">
                        <el-option :label="$t('countryManagement.partition1')" value="1" />
                        <el-option :label="$t('countryManagement.partition2')" value="2" />
                        <el-option :label="$t('countryManagement.partition3')" value="3" />
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">{{ $t('countryManagement.cancel') }}</el-button>
                <el-button type="primary" :loading="saveLoading" @click="submitEdit">{{ $t('countryManagement.save') }}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'countryManagement',
    data() {
        return {
            query: {
                keyword: '',
                partition: '',
                page: 1,
                per_page: 10
            },
            list: [],
            total: 0,
            loading: false,
            editVisible: false,
            saveLoading: false,
            form: {
                country_id: '',
                zh_name: '',
                en_name: '',
                code: '',
                partition: '1'
            },
            rules: {}
        };
    },
    created() {
        this.rules = {
            zh_name: [{ required: true, message: this.$t('countryManagement.ruleZhName'), trigger: 'blur' }],
            en_name: [{ required: true, message: this.$t('countryManagement.ruleEnName'), trigger: 'blur' }],
            code: [{ required: true, message: this.$t('countryManagement.ruleCode'), trigger: 'blur' }],
            partition: [{ required: true, message: this.$t('countryManagement.rulePartition'), trigger: 'change' }]
        };
        this.fetchList();
    },
    methods: {
        countryRowId(row) {
            if (!row) return '';
            return row.country_id != null ? String(row.country_id) : row.id != null ? String(row.id) : '';
        },
        normalizeListResponse(res) {
            const d = res && res.data;
            if (!d) return { list: [], total: 0 };
            const list = d.list || d.data || d.rows || [];
            const total = Number(d.total != null ? d.total : d.count != null ? d.count : list.length) || 0;
            return { list: Array.isArray(list) ? list : [], total };
        },
        async fetchList() {
            this.loading = true;
            try {
                const params = {
                    keyword: this.query.keyword || '',
                    partition: this.query.partition === '' || this.query.partition == null ? '' : String(this.query.partition),
                    page: this.query.page,
                    per_page: this.query.per_page
                };
                const res = await this.$api.post('api/Country/getList', params);
                if (res && res.code === 0) {
                    const { list, total } = this.normalizeListResponse(res);
                    this.list = list;
                    this.total = total;
                } else {
                    this.list = [];
                    this.total = 0;
                    if (res && res.msg) this.$message.warning(res.msg);
                }
            } catch (e) {
                this.list = [];
                this.total = 0;
                this.$message.error(this.$t('countryManagement.loadFailed'));
            } finally {
                this.loading = false;
            }
        },
        handleSearch() {
            this.query.page = 1;
            this.fetchList();
        },
        /** 切换分区即请求列表，无需再点搜索 */
        onPartitionChange() {
            this.query.page = 1;
            this.fetchList();
        },
        handleReset() {
            this.query = {
                keyword: '',
                partition: '',
                page: 1,
                per_page: 10
            };
            this.fetchList();
        },
        handleSizeChange(size) {
            this.query.per_page = size;
            this.query.page = 1;
            this.fetchList();
        },
        handlePageChange(page) {
            this.query.page = page;
            this.fetchList();
        },
        openEdit(row) {
            const id = this.countryRowId(row);
            this.form = {
                country_id: id,
                zh_name: (row && row.zh_name) || '',
                en_name: (row && row.en_name) || '',
                code: (row && row.code) || '',
                partition: row && row.partition != null && row.partition !== '' ? String(row.partition) : '1'
            };
            this.editVisible = true;
            this.$nextTick(() => {
                if (this.$refs.editForm) this.$refs.editForm.clearValidate();
            });
        },
        resetForm() {
            this.form = {
                country_id: '',
                zh_name: '',
                en_name: '',
                code: '',
                partition: '1'
            };
        },
        submitEdit() {
            this.$refs.editForm.validate(async (valid) => {
                if (!valid) return;
                this.saveLoading = true;
                try {
                    const params = {
                        country_id: String(this.form.country_id),
                        zh_name: this.form.zh_name,
                        en_name: this.form.en_name,
                        code: this.form.code,
                        partition: String(this.form.partition)
                    };
                    const res = await this.$api.post('api/Country/edit', params);
                    if (res && res.code === 0) {
                        this.$message.success(this.$t('countryManagement.saveSuccess'));
                        this.editVisible = false;
                        this.fetchList();
                    } else {
                        this.$message.error((res && res.msg) || this.$t('countryManagement.opFailed'));
                    }
                } catch (e) {
                    this.$message.error(this.$t('countryManagement.opFailed'));
                } finally {
                    this.saveLoading = false;
                }
            });
        },
        handleDelete(row) {
            const id = this.countryRowId(row);
            if (!id) {
                this.$message.warning(this.$t('countryManagement.missingId'));
                return;
            }
            this.$confirm(this.$t('countryManagement.deleteConfirm'), this.$t('countryManagement.deleteTitle'), {
                type: 'warning',
                confirmButtonText: this.$t('countryManagement.confirm'),
                cancelButtonText: this.$t('countryManagement.cancel')
            })
                .then(async () => {
                    try {
                        const res = await this.$api.post('api/Country/delete', { country_id: String(id) });
                        if (res && res.code === 0) {
                            this.$message.success(this.$t('countryManagement.deleteSuccess'));
                            this.fetchList();
                        } else {
                            this.$message.error((res && res.msg) || this.$t('countryManagement.opFailed'));
                        }
                    } catch (e) {
                        this.$message.error(this.$t('countryManagement.opFailed'));
                    }
                })
                .catch(() => {});
        }
    }
};
</script>

<style scoped>
.country-manage {
    padding: 0 10px;
}
.crumbs {
    margin-bottom: 10px;
}
.toolbar {
    /* margin-bottom: 15px; */
    margin-top: 20px;
}
.table-card {
    margin-top: 0;
}
.pagination {
    margin-top: 15px;
    text-align: right;
}
::v-deep .dark-table-header th {
    background-color: #f5f7fa;
    font-weight: 600;
}
.table-row-actions {
    display: inline-flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 8px;
}
.table-row-actions .action-btn {
    margin: 0;
    padding: 7px 12px;
    border-radius: 4px;
    font-weight: 500;
}
.table-row-actions .action-btn--edit {
    background-color: #ecf5ff;
    border-color: #b3d8ff;
    color: #409eff;
}
.table-row-actions .action-btn--edit:hover {
    background-color: #d9ecff;
    border-color: #409eff;
    color: #409eff;
}
.table-row-actions .action-btn--delete {
    background-color: #fef0f0;
    border-color: #fbc4c4;
    color: #f56c6c;
}
.table-row-actions .action-btn--delete:hover {
    background-color: #fde2e2;
    border-color: #f56c6c;
    color: #f56c6c;
}
</style>
