<template>
    <div class="applet-page">
        <div class="page-header">
            <div class="header-title">
                <span class="header-icon">🎯</span>
                <span class="header-text">小程序首页配置</span>
            </div>
            <span class="header-sub">管理小程序端首页展示内容</span>
        </div>

        <el-card shadow="never" class="applet-card">
            <el-tabs v-model="activeTab" class="applet-tabs">
                <el-tab-pane name="slideshow">
                    <template #label>
                        <span class="tab-label">
                            <el-icon>
                                <PictureFilled />
                            </el-icon>
                            轮播图管理
                        </span>
                    </template>
                </el-tab-pane>
                <el-tab-pane name="categories">
                    <template #label>
                        <span class="tab-label">
                            <el-icon>
                                <Grid />
                            </el-icon>
                            精选分类管理
                        </span>
                    </template>
                </el-tab-pane>
            </el-tabs>

            <!-- ========== 轮播图管理 ========== -->
            <div v-if="activeTab === 'slideshow'" v-loading="slideshowLoading" class="tab-content">
                <div class="toolbar">
                    <el-button type="primary" :icon="Plus" @click="handleSlideshowAdd">新增轮播图</el-button>
                    <span class="toolbar-count" v-if="slideshowList.length">共 {{ slideshowList.length }} 条</span>
                </div>

                <el-table :data="slideshowList" style="width: 100%" class="modern-table"
                    :header-cell-style="tableHeaderStyle">
                    <el-table-column label="序号" type="index" width="70" align="center" />
                    <el-table-column label="预览" align="center" width="140">
                        <template #default="scope">
                            <div class="img-preview" v-if="scope.row.ossUrl">
                                <el-image :src="scope.row.ossUrl" fit="cover" :preview-src-list="[scope.row.ossUrl]" />
                            </div>
                            <div class="img-empty" v-else>
                                <el-icon>
                                    <WarningFilled />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createByName" label="创建者" align="center" min-width="100" />
                    <el-table-column prop="createTime" label="创建时间" align="center" min-width="170" />
                    <el-table-column prop="updateByName" label="更新者" align="center" min-width="100" />
                    <el-table-column prop="updateTime" label="更新时间" align="center" min-width="170" />
                    <el-table-column label="操作" align="center" width="160" fixed="right">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleSlideshowEdit(scope.row)">编辑</el-button>
                            <el-divider direction="vertical" />
                            <el-button link type="danger" @click="handleSlideshowDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <div class="empty-block">
                            <el-icon :size="48">
                                <PictureFilled />
                            </el-icon>
                            <p>暂无轮播图</p>
                            <el-button type="primary" size="small" @click="handleSlideshowAdd">立即添加</el-button>
                        </div>
                    </template>
                </el-table>
            </div>

            <!-- ========== 精选分类管理 ========== -->
            <div v-if="activeTab === 'categories'" v-loading="categoriesLoading" class="tab-content">
                <div class="toolbar">
                    <span class="toolbar-count" v-if="categoriesList.length">共 {{ categoriesList.length }} 个分类</span>
                </div>
                <el-row :gutter="20" v-if="categoriesList.length">
                    <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in categoriesList" :key="item.id">
                        <div class="category-card" @click="handleCategoriesEdit(item)">
                            <div class="category-media">
                                <el-image v-if="item.backgroundUrl" :src="item.backgroundUrl" fit="cover" />
                                <div class="category-placeholder" v-else>
                                    <el-icon :size="36">
                                        <PictureFilled />
                                    </el-icon>
                                </div>
                                <div class="category-overlay">
                                    <el-icon :size="28">
                                        <Edit />
                                    </el-icon>
                                </div>
                            </div>
                            <div class="category-body">
                                <p class="category-title">{{ item.title }}</p>
                                <p class="category-remark">{{ item.remark || '暂无备注' }}</p>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <div class="empty-block" v-else>
                    <el-icon :size="48">
                        <Grid />
                    </el-icon>
                    <p>暂未配置精选分类</p>
                </div>
            </div>
        </el-card>

        <!-- ========== 轮播图弹窗 ========== -->
        <el-dialog v-model="slideshowDialog.visible" :title="slideshowDialog.title" width="480px"
            :close-on-click-modal="false" append-to-body @close="resetSlideshowForm">
            <el-form ref="slideshowFormRef" :model="slideshowForm" :rules="slideshowRules" label-width="90px">
                <el-form-item label="轮播图片" prop="ossId">
                    <image-upload v-model="slideshowForm.ossId" :limit="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button icon="Close" @click="slideshowDialog.visible = false">取消</el-button>
                <el-button :loading="slideshowDialog.loading" type="primary" icon="Check"
                    @click="submitSlideshowForm">保存</el-button>
            </template>
        </el-dialog>

        <!-- ========== 分类编辑弹窗 ========== -->
        <el-dialog v-model="categoriesDialog.visible" :title="'编辑分类'" width="520px" :close-on-click-modal="false"
            append-to-body @close="resetCategoriesForm">
            <el-form ref="categoriesFormRef" :model="categoriesForm" :rules="categoriesRules" label-width="90px">
                <el-form-item label="分类标题" prop="title">
                    <el-input v-model="categoriesForm.title" placeholder="请输入分类标题" maxlength="50" show-word-limit />
                </el-form-item>
                <el-form-item label="备注说明" prop="remark">
                    <el-input v-model="categoriesForm.remark" type="textarea" :rows="3" placeholder="请输入备注说明"
                        maxlength="200" show-word-limit />
                </el-form-item>
                <el-form-item label="背景图" prop="background">
                    <image-upload v-model="categoriesForm.background" :limit="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button icon="Close" @click="categoriesDialog.visible = false">取消</el-button>
                <el-button :loading="categoriesDialog.loading" type="primary" icon="Check"
                    @click="submitCategoriesForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Plus, PictureFilled, Grid, Edit, WarningFilled } from '@element-plus/icons-vue';
import {
    listSlideshow, getSlideshow, addSlideshow, editSlideshow, delSlideshow
} from '@/api/system/applet/slideshow';
import { SlideshowVO, SlideshowForm } from '@/api/system/applet/slideshow/types';
import {
    listCategories, getCategories, editCategories
} from '@/api/system/applet/categories';
import { CategoriesVO, CategoriesForm } from '@/api/system/applet/categories/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const activeTab = ref<string>('slideshow');

const tableHeaderStyle = {
    background: '#fafbfc',
    color: '#4a5568',
    fontWeight: 600,
    fontSize: '13px',
    borderBottom: '2px solid #e2e8f0'
};

/* ==================== 轮播图 ==================== */
const slideshowLoading = ref(false);
const slideshowList = ref<SlideshowVO[]>([]);

const initSlideshowForm: SlideshowForm = { id: '', ossId: '' };
const slideshowForm = reactive<SlideshowForm>({ ...initSlideshowForm });
const slideshowFormRef = ref<ElFormInstance>();
const slideshowDialog = reactive({ visible: false, title: '', loading: false });

const slideshowRules = {
    ossId: [{ required: true, message: '请上传轮播图片', trigger: 'change' }]
};

const loadSlideshowList = async () => {
    slideshowLoading.value = true;
    try {
        const res = await listSlideshow();
        slideshowList.value = res.data || [];
    } finally {
        slideshowLoading.value = false;
    }
};

const handleSlideshowAdd = () => {
    resetSlideshowForm();
    slideshowDialog.title = '新增轮播图';
    slideshowDialog.visible = true;
};

const handleSlideshowEdit = async (row: SlideshowVO) => {
    const res = await getSlideshow(row.id);
    Object.assign(slideshowForm, { id: res.data.id, ossId: res.data.ossId || '' });
    slideshowDialog.title = '编辑轮播图';
    slideshowDialog.visible = true;
};

const handleSlideshowDelete = async (row: SlideshowVO) => {
    await proxy?.$modal.confirm(`确认删除该轮播图吗？`);
    await delSlideshow(row.id);
    proxy?.$modal.msgSuccess('删除成功');
    loadSlideshowList();
};

const submitSlideshowForm = async () => {
    const valid = await slideshowFormRef.value?.validate().catch(() => false);
    if (!valid) return;
    slideshowDialog.loading = true;
    try {
        if (slideshowForm.id) {
            await editSlideshow(slideshowForm);
        } else {
            await addSlideshow(slideshowForm);
        }
        proxy?.$modal.msgSuccess('保存成功');
        slideshowDialog.visible = false;
        loadSlideshowList();
    } finally {
        slideshowDialog.loading = false;
    }
};

const resetSlideshowForm = () => {
    Object.assign(slideshowForm, initSlideshowForm);
    slideshowFormRef.value?.resetFields();
};

/* ==================== 精选分类 ==================== */
const categoriesLoading = ref(false);
const categoriesList = ref<CategoriesVO[]>([]);

const initCategoriesForm: CategoriesForm = { id: '', title: '', remark: '', background: '' };
const categoriesForm = reactive<CategoriesForm>({ ...initCategoriesForm });
const categoriesFormRef = ref<ElFormInstance>();
const categoriesDialog = reactive({ visible: false, loading: false });

const categoriesRules = {
    title: [{ required: true, message: '分类标题不能为空', trigger: 'blur' }]
};

const loadCategoriesList = async () => {
    categoriesLoading.value = true;
    try {
        const res = await listCategories();
        categoriesList.value = res.data || [];
    } finally {
        categoriesLoading.value = false;
    }
};

const handleCategoriesEdit = async (item: CategoriesVO) => {
    const res = await getCategories(item.id);
    Object.assign(categoriesForm, {
        ...res.data,
        background: res.data.background || ''
    });
    categoriesDialog.visible = true;
};

const submitCategoriesForm = async () => {
    const valid = await categoriesFormRef.value?.validate().catch(() => false);
    if (!valid) return;
    categoriesDialog.loading = true;
    try {
        await editCategories(categoriesForm);
        proxy?.$modal.msgSuccess('保存成功');
        categoriesDialog.visible = false;
        loadCategoriesList();
    } finally {
        categoriesDialog.loading = false;
    }
};

const resetCategoriesForm = () => {
    Object.assign(categoriesForm, initCategoriesForm);
    categoriesFormRef.value?.resetFields();
};

/** tab切换时加载对应数据 */
watch(activeTab, (val) => {
    if (val === 'slideshow') loadSlideshowList();
    else if (val === 'categories') loadCategoriesList();
});

onMounted(() => {
    loadSlideshowList();
});
</script>

<style scoped>
.applet-page {
    width: 100%;
    height: 100%;
    padding: 20px 24px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    gap: 16px;
    background: #f7f8fc;
}

/* ==================== 页头 ==================== */
.page-header {
    display: flex;
    align-items: baseline;
    gap: 14px;
    flex-shrink: 0;
}

.header-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-icon {
    font-size: 22px;
    line-height: 1;
}

.header-text {
    font-size: 18px;
    font-weight: 700;
    color: #1a202c;
    letter-spacing: 0.3px;
}

.header-sub {
    font-size: 13px;
    color: #a0aec0;
}

/* ==================== 卡片 ==================== */
.applet-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    border-radius: 12px !important;
    border: none !important;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04), 0 4px 16px rgba(0, 0, 0, 0.03) !important;
    overflow: hidden;
}

.applet-card :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0 24px 20px;
    overflow: hidden;
}

/* ==================== Tabs ==================== */
.applet-tabs {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
}

.applet-tabs :deep(.el-tabs__header) {
    margin-bottom: 20px;
    padding: 0 4px;
    border-bottom: 1px solid #edf2f7;
}

.applet-tabs :deep(.el-tabs__nav-wrap::after) {
    display: none;
}

.applet-tabs :deep(.el-tabs__item) {
    height: 44px;
    line-height: 44px;
    font-size: 14px;
    color: #718096;
    padding: 0 20px;
    font-weight: 500;
}

.applet-tabs :deep(.el-tabs__item.is-active) {
    color: #2563eb;
    font-weight: 600;
}

.applet-tabs :deep(.el-tabs__active-bar) {
    background-color: #2563eb;
    height: 3px;
    border-radius: 3px 3px 0 0;
}

.tab-label {
    display: flex;
    align-items: center;
    gap: 6px;
}

.applet-tabs :deep(.el-tabs__content) {
    flex: 1;
    overflow-y: auto;
}

/* ==================== 工具栏 ==================== */
.toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
}

.toolbar .el-button {
    border-radius: 8px;
    font-weight: 500;
}

.toolbar-count {
    font-size: 13px;
    color: #a0aec0;
}

/* ==================== 现代化表格 ==================== */
.modern-table {
    border-radius: 10px;
    overflow: hidden;
}

.modern-table :deep(.el-table__header th) {
    border-bottom: 2px solid #e2e8f0 !important;
    border-right: none !important;
}

.modern-table :deep(.el-table__body td) {
    border-right: none !important;
    border-bottom: 1px solid #f1f5f9 !important;
}

.modern-table :deep(.el-table__row:hover > td) {
    background: #f8fafc !important;
}

.modern-table :deep(.el-table__body-wrapper) {
    border-bottom: 1px solid #f1f5f9;
}

.modern-table :deep(.el-table) {
    border: none !important;
}

.modern-table :deep(.el-table::before) {
    display: none;
}

.modern-table :deep(.el-table__inner-wrapper::before) {
    display: none;
}

/* 图片预览 */
.img-preview {
    width: 88px;
    height: 56px;
    border-radius: 8px;
    overflow: hidden;
    display: inline-block;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.img-preview .el-image {
    width: 100%;
    height: 100%;
    display: block;
}

.img-empty {
    width: 88px;
    height: 56px;
    border-radius: 8px;
    background: #f1f5f9;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #cbd5e1;
}

/* 操作列分割线 */
.modern-table .el-divider--vertical {
    height: 14px;
    margin: 0 4px;
    border-color: #e2e8f0;
}

/* ==================== 空状态 ==================== */
.empty-block {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    color: #cbd5e1;
}

.empty-block p {
    margin: 14px 0 18px;
    font-size: 14px;
    color: #a0aec0;
}

/* ==================== 分类卡片 ==================== */
.category-card {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    cursor: pointer;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04), 0 2px 8px rgba(0, 0, 0, 0.03);
    transition: all 0.28s cubic-bezier(0.25, 0.8, 0.25, 1.2);
    margin-bottom: 20px;
}

.category-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(37, 99, 235, 0.06);
}

.category-media {
    position: relative;
    width: 100%;
    padding-top: 64%;
    background: #f1f5f9;
    overflow: hidden;
}

.category-media .el-image {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
}

.category-placeholder {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #cbd5e1;
    background: #f8fafc;
}

.category-overlay {
    position: absolute;
    inset: 0;
    background: linear-gradient(to top, rgba(0, 0, 0, 0.45) 0%, transparent 50%);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.25s;
    color: #fff;
}

.category-card:hover .category-overlay {
    opacity: 1;
}

.category-body {
    padding: 14px 16px 16px;
}

.category-title {
    font-size: 15px;
    font-weight: 600;
    color: #1a202c;
    margin: 0 0 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.category-remark {
    font-size: 13px;
    color: #a0aec0;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* ==================== 弹窗优化 ==================== */
:deep(.el-dialog) {
    border-radius: 14px;
    overflow: hidden;
}

:deep(.el-dialog__header) {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #f1f5f9;
    margin-right: 0;
}

:deep(.el-dialog__title) {
    font-size: 16px;
    font-weight: 700;
    color: #1a202c;
}

:deep(.el-dialog__body) {
    padding: 24px;
}

:deep(.el-dialog__footer) {
    padding: 12px 24px 20px;
    text-align: right;
}

:deep(.el-dialog__footer .el-button) {
    border-radius: 8px;
    padding: 8px 24px;
    font-weight: 500;
}
</style>
