<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <view class="custom_activities">
            <view class="info-card">
                <view class="content-title">
                    <view v-t="'Home.page_customer.item6'"></view>
                </view>

                <!-- 主要内容 -->
                <view class="main-content">
                    <scroll-view class="tab" scroll-y :scroll-top="scrollTop" @scrolltolower="loadMore"
                        refresher-enabled :refresher-triggered="refreshing" @refresherrefresh="onRefresh">

                        <!-- 加载状态 -->
                        <view v-if="pictLoading" class="loading-mask">
                            <view class="loading-content">
                                <uni-icons type="spinner-cycle" size="30" color="#007aff" class="spin"></uni-icons>
                                <text class="loading-text">{{ t('common.loading') }}</text>
                            </view>
                        </view>

                        <!-- 遍历静态活动配置 -->
                        <ActivityCard v-for="activity in visibleStaticActivities" :key="activity.id" :config="activity"
                            :state="activityState" :lang="lang" @action="handleActivityAction" />

                        <!-- 动态活动列表 -->
                        <ActivityCard v-for="item in tableData" :key="'dynamic-' + item.id"
                            :config="createDynamicConfig(item)" :state="activityState" :lang="lang"
                            @action="handleActivityAction" />

                        <!-- 赠送活动列表 -->
                        <ActivityCard v-for="item in tableDataGive" :key="'give-' + item.id"
                            :config="createGiveConfig(item)" :state="activityState" :lang="lang"
                            @action="handleActivityAction" />

                        <!-- 加载更多状态 -->
                        <view v-if="loadingMore" class="loading-more">
                            <uni-icons type="spinner-cycle" size="20" color="#999" class="spin"></uni-icons>
                            <text>{{ t('common.loadingMore') }}</text>
                        </view>

                        <!-- 没有更多数据 -->
                        <view v-if="!hasMore && tableData.length > 0" class="no-more">
                            <text>{{ t('common.noMore') }}</text>
                        </view>
                    </scroll-view>
                </view>

                <!-- 分页 -->
                <!-- <view class="crm_pagination" v-if="pagerInfo.rowTotal">
                    <view class="pagination">
                        <view class="page-item prev" :class="{ disabled: pagerInfo.current === 1 }"
                            @click="handlePrevPage">
                            <uni-icons type="arrowleft" size="16" color="#666"></uni-icons>
                            <text>{{ t('common.prev') }}</text>
                        </view>
                        <view class="page-numbers">
                            <view v-for="page in visiblePages" :key="page" class="page-number"
                                :class="{ active: pagerInfo.current === page }" @click="handlePageChange(page)">
                                {{ page }}
                            </view>
                        </view>
                        <view class="page-item next" :class="{ disabled: pagerInfo.current === pagerInfo.pageTotal }"
                            @click="handleNextPage">
                            <text>{{ t('common.next') }}</text>
                            <uni-icons type="arrowright" size="16" color="#666"></uni-icons>
                        </view>
                    </view>
                </view> -->

                <!-- 所有弹窗组件 -->
                <ActivityDialogs :visible="dialogState" :form-data="formData" :login-options="loginOptions"
                    :surplus-options="surplusOptions" @update:visible="updateDialogVisible"
                    @action="handleDialogAction" />
            </view>
        </view>
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import ActivityCard from './components/ActivityCard.vue'
import ActivityDialogs from './components/ActivityDialogs.vue'
import { useActivityData } from './composables/useActivityData'
import { useActivityActions } from './composables/useActivityActions'
import { staticActivityConfigs } from './config/activityConfigs'
import Config from '@/config/index'

const { t } = useI18n()
const { Host80 } = Config

// ==================== 数据逻辑 ====================
const {
    pictLoading,
    tableData,
    tableDataGive,
    pagerInfo,
    loginOptions,
    activityState,
    lang,
    country,
    isSupportedCountry,
    isGuoQin,
    overdue,
    timeExpireJx,
    isAfterSeptember30,
    refreshAllActivities,
    handlePageChange
} = useActivityData()

// ==================== 操作逻辑 ====================
const {
    // 弹窗状态
    dialogChinaUnionPay,
    dialogChinaUnionPay1,
    dialogChinaUnionPayJX,
    dialogDealResult,
    dialogDealResultJx,
    dialogDealResultJxVip,
    dialogDealResultCpt,
    dialogDealResultJxJYB,
    dialogDealResultNoWorries,
    dialogNoWorries,
    dialogNoWorriesApply,
    dialogNewTask,
    dialogNewTaskDraw,
    dialogSurplusActivity,
    dialogSurplusActivity1,
    openCalculatorFlag,

    // 表单数据
    dialogDealResult_form,
    dialogDealResultJx_form,
    dialogDealResultJx_formVip,
    dialogDealResultJx_formJYB,
    dialogDealResultCpt_form,
    dialogDeal_formNoWorries,
    selectedAccount,
    valueInfo,
    surplusActivityOptions,
    surplusActivityLoading,
    selectedSurplusActivity,

    // 页面跳转
    toSingle,
    toDeposit,
    toActivity24nianzhong,
    toActivity24Trading,
    toHistoryLuckyDraw,
    toTaskList,
    goSurplusTaskList,
    goMonthlyTaskList,
    toDocumentary,
    backActivity,

    // PDF打开
    openPdf,

    // 活动操作
    toApply23Open,
    toApply23,
    toApply23Cancel,
    toTransform,
    toTransformActive,
    toRealization,
    toRealizationActive,
    toApply23Jx,
    toApply23JxCancel,
    toApply23JxVip,
    toApply23JxCancelVip,
    toRealizationJx,
    toRealizationJxVip,
    toApplyCpt,
    toApplyCptCancel,
    toApply24JYBVip,
    toApply24JYBCancelVip,
    toRealization24JYBVip,
    toApplyNoWorries,
    toApplyNoWorriesCancel,
    realizationNoWorries,
    getSurplusActivityOptions,
    confirmSurplusActivity,
    confirmSurplusActivity1,
    closedialogNewTaskDraw,
    toOpenSingle,
    cashBack,
    calculateIncome
} = useActivityActions(activityState, loginOptions, ref(''), refreshAllActivities)

// ==================== 分页相关 ====================
const refreshing = ref(false)
const loadingMore = ref(false)
const scrollTop = ref(0)
const hasMore = ref(true)

// 计算显示的页码
const visiblePages = computed(() => {
    const maxVisible = 5
    const half = Math.floor(maxVisible / 2)
    let start = Math.max(1, pagerInfo.value.current - half)
    let end = Math.min(pagerInfo.value.pageTotal, start + maxVisible - 1)

    if (end - start + 1 < maxVisible) {
        start = Math.max(1, end - maxVisible + 1)
    }

    return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

// 上一页
const handlePrevPage = () => {
    if (pagerInfo.value.current > 1) {
        handlePageChange(pagerInfo.value.current - 1)
    }
}

// 下一页
const handleNextPage = () => {
    if (pagerInfo.value.current < pagerInfo.value.pageTotal) {
        handlePageChange(pagerInfo.value.current + 1)
    }
}

// 加载更多
const loadMore = () => {
    if (hasMore.value && !loadingMore.value && pagerInfo.value.current < pagerInfo.value.pageTotal) {
        loadingMore.value = true
        handlePageChange(pagerInfo.value.current + 1)
        setTimeout(() => {
            loadingMore.value = false
        }, 500)
    }
}

// 刷新
const onRefresh = () => {
    refreshing.value = true
    refreshAllActivities()
    setTimeout(() => {
        refreshing.value = false
        uni.stopPullDownRefresh()
    }, 1000)
}

// ==================== 可见活动计算 ====================
const visibleStaticActivities = computed(() => {
    return staticActivityConfigs.filter(config => {
        if (!config.showCondition) return true

        switch (config.showCondition) {
            case 'tableDataNewYear24Flag':
                return activityState.tableDataNewYear24Flag
            case "country === 'CN'":
                return country.value === 'CN'
            case 'choujiaClose':
                return activityState.choujiaClose
            case 'tableDataNoWorriesFlag':
                return activityState.tableDataNoWorriesFlag
            case 'standard':
                return activityState.standard
            case 'tableData2Flag':
                return activityState.tableData2Flag
            case 'tableDataCptFlag':
                return activityState.tableDataCptFlag
            case 'tableData3FlagJYB':
                return activityState.tableData3FlagJYB
            case '!isAfterSeptember30() && !isSupportedCountry':
                return !isAfterSeptember30() && !isSupportedCountry.value
            case '!isAfterSeptember30() && isSupportedCountry':
                return !isAfterSeptember30() && isSupportedCountry.value
            default:
                return true
        }
    })
})

// ==================== 创建动态活动配置 ====================
const createDynamicConfig = (item: any) => {
    return {
        id: item.id,
        title: item.title,
        description: item.subTitle,
        image: Host80 + item.coverImage,
        time: item.deliveryTime?.split(' ')[0],
        hot: item.hot,
        onClick: 'toSingle',
        onClickParams: [item.id],
        buttons: [
            {
                type: item.startTime && item.endTime && overdue(item.startTime, item.endTime) ? 'red' : 'gray',
                text: 'Custom.Activity.Apply',
                action: 'applications',
                params: [item]
            },
            {
                type: 'check',
                text: 'Custom.Activity.List',
                action: 'checkActivity',
                params: [item]
            },
            {
                type: 'check',
                text: 'Custom.Activity.Single',
                action: 'toSingle',
                params: [item.id]
            }
        ]
    }
}

const createGiveConfig = (item: any) => {
    return {
        id: item.id,
        title: item.title,
        description: item.subTitle,
        image: Host80 + item.coverUrl,
        time: item.revokeDate?.split(' ')[0],
        hot: item.hot,
        onClick: 'toSingle',
        onClickParams: ['newList', item.id],
        buttons: [
            {
                type: item.valid === 1 ? 'red' : 'gray',
                text: 'Custom.Activity.Apply',
                action: 'toActivity24nianzhong',
                condition: item.valid === 1
            },
            {
                type: 'check',
                text: 'Custom.Activity.Single',
                action: 'toSingle',
                params: ['newList', item.id]
            }
        ]
    }
}

// ==================== 弹窗状态聚合 ====================
const dialogState = {
    dialogChinaUnionPay,
    dialogChinaUnionPay1,
    dialogChinaUnionPayJX,
    dialogDealResult,
    dialogDealResultJx,
    dialogDealResultJxVip,
    dialogDealResultCpt,
    dialogDealResultJxJYB,
    dialogDealResultNoWorries,
    dialogNoWorries,
    dialogNoWorriesApply,
    dialogNewTask,
    dialogNewTaskDraw,
    dialogSurplusActivity,
    dialogSurplusActivity1,
    openCalculatorFlag
}

const formData = {
    dialogDealResult_form,
    dialogDealResultJx_form,
    dialogDealResultJx_formVip,
    dialogDealResultJx_formJYB,
    dialogDealResultCpt_form,
    dialogDeal_formNoWorries,
    selectedAccount,
    valueInfo,
    selectedSurplusActivity
}

const surplusOptions = {
    options: surplusActivityOptions,
    loading: surplusActivityLoading
}

// 更新弹窗可见性
const updateDialogVisible = (key: string, value: boolean) => {
    const dialogMap: Record<string, any> = {
        dialogChinaUnionPay,
        dialogChinaUnionPay1,
        dialogChinaUnionPayJX,
        dialogDealResult,
        dialogDealResultJx,
        dialogDealResultJxVip,
        dialogDealResultCpt,
        dialogDealResultJxJYB,
        dialogDealResultNoWorries,
        dialogNoWorries,
        dialogNoWorriesApply,
        dialogNewTask,
        dialogNewTaskDraw,
        dialogSurplusActivity,
        dialogSurplusActivity1,
        openCalculatorFlag
    }
    if (dialogMap[key]) {
        dialogMap[key].value = value
    }
}

// 处理弹窗操作
const handleDialogAction = (action: string, data?: any) => {
    switch (action) {
        case 'toApply23':
            toApply23()
            break
        case 'toApply23Cancel':
            toApply23Cancel()
            break
        case 'toTransformActive':
            toTransformActive()
            break
        // ... 其他操作
    }
}

// ==================== 活动操作处理 ====================
const handleActivityAction = ({ type, params }: { type: string; params?: any[] }) => {
    switch (type) {
        case 'toSingle':
            toSingle(...(params || []))
            break
        case 'openCalculator':
            openCalculatorFlag.value = true
            break
        case 'openPdf':
            openPdf(params?.[0] || type)
            break
        case 'openSurplusActivityDialog':
            dialogSurplusActivity.value = true
            break
        case 'openSurplusActivityDialog1':
            dialogSurplusActivity1.value = true
            break
        case 'goMonthlyTaskList':
            goMonthlyTaskList()
            break
        case 'goSurplusTaskList':
            goSurplusTaskList()
            break
        case 'toHistoryLuckyDraw':
            toHistoryLuckyDraw()
            break
        case 'toOpenTask':
            dialogNewTaskDraw.value = true
            break
        case 'toNewTask':
            dialogNewTask.value = true
            break
        case 'toTaskList':
            toTaskList()
            break
        case 'toApplyNoWorriesOpen':
            dialogDealResultNoWorries.value = true
            break
        case 'toRealizationNoWorries':
            dialogNoWorries.value = true
            break
        case 'toActivity24Trading':
            toActivity24Trading()
            break
        case 'toActivity24nianzhong':
            toActivity24nianzhong()
            break
        case 'toApply23Open':
            toApply23Open()
            break
        case 'toTransform':
            toTransform()
            break
        case 'toRealization':
            toRealization()
            break
        case 'toApplyCptOpen':
            dialogDealResultCpt.value = true
            break
        case 'toOpenSingle':
            // 处理打开外部链接
            break
        case 'toApply24JYBOpenVip':
            dialogDealResultJxJYB.value = true
            break
        case 'toRealization24JYBVip':
            // 处理变现
            break
        case 'applications':
            // 处理申请
            break
        case 'checkActivity':
            // 处理查看活动
            break
        case 'openDialog':
            if (params?.[0]) {
                updateDialogVisible(params[0], true)
            }
            break
        case 'cashBack':
            // 处理返现
            break
        case 'toApply23JxOpen':
            dialogDealResultJx.value = true
            break
        case 'toApply23JxOpenVip':
            dialogDealResultJxVip.value = true
            break
        case 'toApplyCptOpen':
            dialogDealResultCpt.value = true
            break
        case 'toApply24JYBOpenVip':
            dialogDealResultJxJYB.value = true
            break
        case 'toApplyNoWorriesOpen':
            dialogDealResultNoWorries.value = true
            break
        case 'toRealizationJx':
            toRealizationJx()
            break
        case 'toRealizationJxVip':
            toRealizationJxVip()
            break
        case 'toRealization24JYBVip':
            toRealization24JYBVip()
            break
        case 'toRealizationNoWorries':
            dialogNoWorries.value = true
            break
        case 'toOpenSingle':
            toOpenSingle(params?.[0])
            break
        case 'cashBack':
            cashBack()
            break
        default:
            console.warn('未知操作类型:', type)
    }
}

// ==================== 生命周期 ====================
onLoad(() => {
    refreshAllActivities()
})

onPullDownRefresh(() => {
    refreshAllActivities()
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
})

onReachBottom(() => {
    loadMore()
})
</script>

<style scoped lang="scss">
.custom_activities {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;

    .crm-title-box {
        padding: 20rpx 30rpx;
        background-color: #fff;
        border-bottom: 1rpx solid #e5e5e5;

        .tit {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
        }
    }

    .main-content {
        flex: 1;
        overflow: hidden;

        .tab {
            height: 100%;
            padding: 20rpx;
        }
    }

    .loading-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(255, 255, 255, 0.9);
        z-index: 100;

        .loading-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 30rpx;
            background-color: #fff;
            border-radius: 16rpx;
            box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

            .loading-text {
                margin-top: 20rpx;
                font-size: 28rpx;
                color: #666;
            }
        }
    }

    .loading-more,
    .no-more {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 30rpx;
        font-size: 28rpx;
        color: #999;
    }

    .spin {
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }

    .crm_pagination {
        padding: 20rpx;
        background-color: #fff;
        border-top: 1rpx solid #e5e5e5;

        .pagination {
            display: flex;
            align-items: center;
            justify-content: center;

            .page-item {
                display: flex;
                align-items: center;
                padding: 0 20rpx;
                height: 60rpx;
                background-color: #fff;
                border: 1rpx solid #dcdfe6;
                border-radius: 8rpx;
                font-size: 28rpx;
                color: #606266;
                cursor: pointer;
                margin: 0 10rpx;

                &.disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                    pointer-events: none;
                }
            }

            .page-numbers {
                display: flex;
                gap: 10rpx;

                .page-number {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-width: 60rpx;
                    height: 60rpx;
                    padding: 0 8rpx;
                    background-color: #fff;
                    border: 1rpx solid #dcdfe6;
                    border-radius: 8rpx;
                    font-size: 28rpx;
                    color: #606266;
                    cursor: pointer;

                    &.active {
                        background-color: #007aff;
                        border-color: #007aff;
                        color: #fff;
                    }
                }
            }
        }
    }
}
</style>