package cn.novalon.gym.manage.app.config;


import cn.novalon.gym.manage.checkIn.handler.CheckInHandler;
import cn.novalon.gym.manage.datacount.handler.DataStatisticsHandler;
import cn.novalon.gym.manage.file.handler.SysFileHandler;
import cn.novalon.gym.manage.auth.handler.PhoneAuthHandler;
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseBookingHandler;
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseHandler;
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseRecommendHandler;
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseTypeHandler;
import cn.novalon.gym.manage.groupcourse.handler.CourseLabelHandler;
import cn.novalon.gym.manage.member.handler.MemberCardHandler;
import cn.novalon.gym.manage.member.handler.MemberCardRecordHandler;
import cn.novalon.gym.manage.member.handler.MemberCardTransactionHandler;
import cn.novalon.gym.manage.member.handler.MemberHandler;
import cn.novalon.gym.manage.member.handler.WechatAuthHandler;
import cn.novalon.gym.manage.notify.handler.SysNoticeHandler;
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
import cn.novalon.gym.manage.payment.handler.PaymentHandler;
import cn.novalon.gym.manage.sys.handler.auth.PasswordDiagnosticHandler;
import cn.novalon.gym.manage.sys.handler.auth.SysAuthHandler;
import cn.novalon.gym.manage.sys.handler.config.SysConfigHandler;
import cn.novalon.gym.manage.sys.handler.dict.SysDictHandler;
import cn.novalon.gym.manage.sys.handler.dictionary.DictionaryHandler;
import cn.novalon.gym.manage.sys.handler.log.OperationLogHandler;
import cn.novalon.gym.manage.sys.handler.log.SysLogHandler;
import cn.novalon.gym.manage.sys.handler.menu.MenuHandler;
import cn.novalon.gym.manage.sys.handler.permission.SysPermissionHandler;
import cn.novalon.gym.manage.sys.handler.role.SysRoleHandler;
import cn.novalon.gym.manage.sys.handler.stats.StatsHandler;
import cn.novalon.gym.manage.sys.handler.user.SysUserHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RouterFunctions.route;

/**
 * 系统路由配置类
 * 
 * 文件定义：配置WebFlux函数式路由，将HTTP请求映射到对应的Handler方法
 * 涉及业务：用户、角色、字典、菜单、公告、文件等所有RESTful API路由
 * 算法：使用RouterFunctions.route()构建函数式路由规则
 *
 * @author 张翔
 * @date 2026-03-13
 */
@Configuration
public class SystemRouter {

    @Bean
    public RouterFunction<ServerResponse> systemRoutes(
            DictionaryHandler dictionaryHandler,
            SysUserHandler userHandler,
            MenuHandler menuHandler,
            SysRoleHandler roleHandler,
            SysConfigHandler configHandler,
            SysLogHandler logHandler,
            OperationLogHandler operationLogHandler,
            SysAuthHandler authHandler,
            StatsHandler statsHandler,
            SysDictHandler dictHandler,
            SysNoticeHandler noticeHandler,
            SysUserMessageHandler messageHandler,
            SysFileHandler fileHandler,
            SysPermissionHandler permissionHandler,
            MemberHandler memberHandler,
            WechatAuthHandler wechatAuthHandler,
            PasswordDiagnosticHandler passwordDiagnosticHandler,
            MemberCardHandler memberCardHandler,
            MemberCardRecordHandler memberCardRecordHandler,
            MemberCardTransactionHandler memberCardTransactionHandler,
            GroupCourseHandler groupCourseHandler,
            GroupCourseBookingHandler groupCourseBookingHandler,
            GroupCourseRecommendHandler groupCourseRecommendHandler,
            GroupCourseTypeHandler groupCourseTypeHandler,
            CourseLabelHandler courseLabelHandler,
            CheckInHandler checkInHandler,
            DataStatisticsHandler dataStatisticsHandler,
            PhoneAuthHandler phoneAuthHandler,
            PaymentHandler paymentHandler) {

        return route()
                // ========== 诊断路由 ==========
                .GET("/api/diagnostic/password", passwordDiagnosticHandler::diagnose)

                // ========== 字典路由 ==========
                .GET("/api/dictionaries", dictionaryHandler::getAllDictionaries)
                .GET("/api/dictionaries/{id}", dictionaryHandler::getDictionaryById)
                .GET("/api/dictionaries/type/{type}", dictionaryHandler::getDictionariesByType)
                .GET("/api/dictionaries/check/exists", dictionaryHandler::checkTypeAndCodeExists)
                .POST("/api/dictionaries", dictionaryHandler::createDictionary)
                .PUT("/api/dictionaries/{id}", dictionaryHandler::updateDictionary)
                .DELETE("/api/dictionaries/{id}", dictionaryHandler::deleteDictionary)

                // ========== 用户路由 ==========
                .GET("/api/users", userHandler::getAllUsers)
                .GET("/api/users/page", userHandler::getUsersByPage)
                .GET("/api/users/count", userHandler::getUserCount)
                .GET("/api/users/username/{username}", userHandler::getUserByUsername)
                .GET("/api/users/check/username", userHandler::checkUsernameExists)
                .GET("/api/users/check/email", userHandler::checkEmailExists)
                .POST("/api/users", userHandler::createUser)
                .GET("/api/users/{id}", userHandler::getUserById)
                .PUT("/api/users/{id}", userHandler::updateUser)
                .DELETE("/api/users/{id}", userHandler::deleteUser)
                .POST("/api/users/{id}/action/change-password", userHandler::changePassword)
                .POST("/api/users/{id}/action/logical-delete", userHandler::logicalDeleteUser)
                .POST("/api/users/logical-delete", userHandler::logicalDeleteUsers)
                .POST("/api/users/action/restore", userHandler::restoreUsers)
                .POST("/api/users/{id}/action/restore", userHandler::restoreUser)
                .GET("/api/users/{id}/roles", userHandler::getUserRoles)
                .POST("/api/users/{id}/roles", userHandler::assignRoles)

                // ========== 菜单路由 ==========
                .GET("/api/menus", menuHandler::getAllMenus)
                .GET("/api/menus/tree", menuHandler::getMenuTree)
                .GET("/api/menus/{id}", menuHandler::getMenuById)
                .POST("/api/menus", menuHandler::createMenu)
                .PUT("/api/menus/{id}", menuHandler::updateMenu)
                .DELETE("/api/menus/{id}", menuHandler::deleteMenu)

                // ========== 角色路由 ==========
                .GET("/api/roles", roleHandler::getAllRoles)
                .GET("/api/roles/page", roleHandler::getRolesByPage)
                .GET("/api/roles/count", roleHandler::getRoleCount)
                .GET("/api/roles/name/{roleName}", roleHandler::getRoleByName)
                .GET("/api/roles/check-name", roleHandler::checkNameExists)
                .GET("/api/roles/{id}", roleHandler::getRoleById)
                .POST("/api/roles", roleHandler::createRole)
                .PUT("/api/roles/{id}", roleHandler::updateRole)
                .DELETE("/api/roles/{id}", roleHandler::deleteRole)
                .POST("/api/roles/{id}/restore", roleHandler::restoreRole)
                .GET("/api/roles/{id}/permissions", permissionHandler::getPermissionsByRoleId)
                .POST("/api/roles/{id}/permissions", permissionHandler::assignPermissionsToRole)

                // ========== 配置路由 ==========
                .GET("/api/config", configHandler::getAllConfigs)
                .GET("/api/config/{id}", configHandler::getConfigById)
                .GET("/api/config/key/{configKey}", configHandler::getConfigByKey)
                .POST("/api/config", configHandler::createConfig)
                .PUT("/api/config/{id}", configHandler::updateConfig)
                .DELETE("/api/config/{id}", configHandler::deleteConfig)

                // ========== 日志路由 ==========
                .GET("/api/logs/login", logHandler::getAllLoginLogs)
                .GET("/api/logs/login/page", logHandler::getLoginLogsByPage)
                .GET("/api/logs/login/count", logHandler::getLoginLogCount)
                .GET("/api/logs/login/today/count", logHandler::getTodayLoginCount)
                .GET("/api/logs/login/recent", logHandler::getRecentLoginLogs)
                .GET("/api/logs/login/{id}", logHandler::getLoginLogById)
                .POST("/api/logs/login", logHandler::createLoginLog)
                .GET("/api/logs/exception", logHandler::getAllExceptionLogs)
                .GET("/api/logs/exception/page", logHandler::getExceptionLogsByPage)
                .GET("/api/logs/exception/count", logHandler::getExceptionLogCount)
                .GET("/api/logs/exception/{id}", logHandler::getExceptionLogById)
                .POST("/api/logs/exception", logHandler::createExceptionLog)
                .GET("/api/logs/operation", operationLogHandler::getAllOperationLogs)
                .GET("/api/logs/operation/export", operationLogHandler::exportOperationLogs)
                .GET("/api/logs/operation/page", operationLogHandler::getOperationLogsByPage)
                .GET("/api/logs/operation/count", operationLogHandler::getOperationLogCount)
                .GET("/api/logs/operation/{id}", operationLogHandler::getOperationLogById)
                .POST("/api/logs/operation", operationLogHandler::createOperationLog)

                // ========== 认证路由 ==========
                .POST("/api/auth/login", authHandler::login)
                .POST("/api/auth/register", authHandler::register)
                .POST("/api/auth/logout", authHandler::logout)

                // ========== 统计路由 ==========
                .GET("/api/stats/overview", statsHandler::getOverview)

                // ========== 数据字典路由 ==========
                .GET("/api/dict/types", dictHandler::getAllDictTypes)
                .GET("/api/dict/types/{id}", dictHandler::getDictTypeById)
                .GET("/api/dict/types/type/{dictType}", dictHandler::getDictTypeByType)
                .POST("/api/dict/types", dictHandler::createDictType)
                .PUT("/api/dict/types/{id}", dictHandler::updateDictType)
                .DELETE("/api/dict/types/{id}", dictHandler::deleteDictType)
                .GET("/api/dict/data", dictHandler::getAllDictData)
                .GET("/api/dict/data/type/{dictType}", dictHandler::getDictDataByType)
                .GET("/api/dict/data/{id}", dictHandler::getDictDataById)
                .POST("/api/dict/data", dictHandler::createDictData)
                .PUT("/api/dict/data/{id}", dictHandler::updateDictData)
                .DELETE("/api/dict/data/{id}", dictHandler::deleteDictData)

                // ========== 公告路由 ==========
                .GET("/api/notices", noticeHandler::getAllNotices)
                .GET("/api/notices/{id}", noticeHandler::getNoticeById)
                .GET("/api/notices/status/{status}", noticeHandler::getNoticesByStatus)
                .POST("/api/notices", noticeHandler::createNotice)
                .PUT("/api/notices/{id}", noticeHandler::updateNotice)
                .DELETE("/api/notices/{id}", noticeHandler::deleteNotice)

                // ========== 消息路由 ==========
                .GET("/api/messages/user/{userId}", messageHandler::getMessagesByUser)
                .GET("/api/messages/user/{userId}/page", messageHandler::getMessagesByUserPage)
                .GET("/api/messages/user/{userId}/unread", messageHandler::getUnreadCount)
                .GET("/api/messages/user/{userId}/unread/list", messageHandler::getUnreadList)
                .GET("/api/messages/user/{userId}/unread/page", messageHandler::getUnreadMessagesPage)
                .POST("/api/messages", messageHandler::createMessage)
                .PUT("/api/messages/{id}/read", messageHandler::markAsRead)
                .PUT("/api/messages/user/{userId}/read", messageHandler::markAllAsRead)
                .DELETE("/api/messages/{id}", messageHandler::deleteMessage)

                // ========== 文件路由 ==========
                .GET("/api/files", fileHandler::getAllFiles)
                .GET("/api/files/{id}", fileHandler::getFileById)
                .POST("/api/files/upload", fileHandler::uploadFile)
                .GET("/api/files/{id}/download", fileHandler::downloadFile)
                .GET("/api/files/download/{fileName}", fileHandler::downloadFileByName)
                .GET("/api/files/{id}/preview", fileHandler::previewFile)
                .GET("/api/files/preview/{fileName}", fileHandler::previewFileByName)
                .DELETE("/api/files/{id}", fileHandler::deleteFile)

                // ========== 权限路由 ==========
                .GET("/api/permissions", permissionHandler::getAllPermissions)
                .GET("/api/permissions/{id}", permissionHandler::getPermissionById)
                .GET("/api/permissions/code/{code}", permissionHandler::getPermissionByCode)
                .GET("/api/permissions/check-code", permissionHandler::checkCodeExists)
                .GET("/api/permissions/count", permissionHandler::getPermissionCount)
                .POST("/api/permissions", permissionHandler::createPermission)
                .PUT("/api/permissions/{id}", permissionHandler::updatePermission)
                .DELETE("/api/permissions/{id}", permissionHandler::deletePermission)

                // ========== 手机号认证路由 ==========
                .POST("/api/auth/phone/one-click-login", phoneAuthHandler::oneClickLogin)
                .POST("/api/auth/phone/send-code", phoneAuthHandler::sendSmsCode)
                .POST("/api/auth/phone/code-login", phoneAuthHandler::codeLogin)

                // ========== 会员模块路由 - 微信认证 ==========
                .POST("/api/member/auth/miniapp/login", wechatAuthHandler::miniappLogin)
                .GET("/api/member/auth/mp/callback", wechatAuthHandler::verifyMpSignature)
                .POST("/api/member/auth/mp/callback", wechatAuthHandler::mpCallback)
                
                // ========== 会员模块路由 - 会员信息 ==========
                .GET("/api/member/info", memberHandler::getMemberInfo)
                .PUT("/api/member/info", memberHandler::updateMemberInfo)
                .POST("/api/member/phone/bind", memberHandler::bindPhone)
                .GET("/api/member/subscribe/status", memberHandler::checkSubscribeStatus)
                
                // ========== 会员模块路由 - 管理端 ==========
                .POST("/api/admin/member/{id}/phone", memberHandler::adminUpdatePhone)
                .GET("/api/admin/member/{id}", memberHandler::adminGetMemberInfo)
                .PUT("/api/admin/member/{id}", memberHandler::adminUpdateMemberInfo)
                .GET("/api/admin/members", memberHandler::searchMembers)
                .GET("/api/admin/members/all", memberHandler::getAllMembers)


                // ========================================
                // ========== 会员卡管理路由 ==============
                // ========================================

                // ===== 会员卡类型管理 =====
                .GET("/api/member-cards/active", memberCardHandler::getActiveCards)
                .GET("/api/member-cards/{memberCardId}", memberCardHandler::getMemberCardById)
                .POST("/api/member-cards", memberCardHandler::createMemberCard)

                // ===== 会员卡记录管理（核心业务）=====
                .POST("/api/member-card-records/purchase", memberCardRecordHandler::purchaseCard)
                .POST("/api/member-card-records/{recordId}/renew", memberCardRecordHandler::renewCard)
                .POST("/api/member-card-records/{recordId}/use", memberCardRecordHandler::useCard)
                .POST("/api/member-card-records/{recordId}/refund", memberCardRecordHandler::refundCard)
                .GET("/api/member-card-records/my-cards/{memberId}", memberCardRecordHandler::getMyCards)
                .GET("/api/member-card-records/{recordId}", memberCardRecordHandler::getMemberCardRecordById)
                .POST("/api/member-card-records/process-expired", memberCardRecordHandler::processExpiredCards)

                // ===== 会员卡交易流水管理 =====
                .POST("/api/member-card-transactions", memberCardTransactionHandler::insertTransaction)
                .GET("/api/member-card-transactions", memberCardTransactionHandler::getTransactionsWithConditions)
                .GET("/api/member-card-transactions/member/{memberId}", memberCardTransactionHandler::getMemberTransactions)
                .GET("/api/member-card-transactions/card/{cardId}", memberCardTransactionHandler::getTransactionsByCardId)
                .GET("/api/member-card-transactions/statistics/deduct/{cardId}", memberCardTransactionHandler::getDeductCountByCardId)
                .GET("/api/member-card-transactions/statistics/renew", memberCardTransactionHandler::getRenewAmountByTimeRange)
                .GET("/api/member-card-transactions/statistics/purchase/{memberId}", memberCardTransactionHandler::getPurchaseAmountByMember)

                // ========================================
                // ========== 团课管理路由 =================
                // ========================================

                // ===== 团课课程管理 =====
                .GET("/api/groupCourse/list", groupCourseHandler::getAllGroupCourse)
                .POST("/api/groupCourse/page", groupCourseHandler::getGroupCoursesByPage)

                // ===== 团课类型管理 =====
                .GET("/api/groupCourse/types", groupCourseTypeHandler::getAllGroupCourseTypes)
                .GET("/api/groupCourse/types/search", groupCourseTypeHandler::searchGroupCourseTypes)
                .GET("/api/groupCourse/types/categories", groupCourseTypeHandler::getCategories)
                .GET("/api/groupCourse/types/category/{category}", groupCourseTypeHandler::getGroupCourseTypesByCategory)
                .GET("/api/groupCourse/types/{id}", groupCourseTypeHandler::getGroupCourseTypeById)
                .POST("/api/groupCourse/types", groupCourseTypeHandler::createGroupCourseType)
                .PUT("/api/groupCourse/types/{id}", groupCourseTypeHandler::updateGroupCourseType)
                .DELETE("/api/groupCourse/types/{id}", groupCourseTypeHandler::deleteGroupCourseType)

                // ===== 团课标签管理 =====
                .GET("/api/groupCourse/labels", courseLabelHandler::getAllLabels)
                .GET("/api/groupCourse/labels/search", courseLabelHandler::searchLabels)
                .GET("/api/groupCourse/labels/{id}", courseLabelHandler::getLabelById)
                .GET("/api/groupCourse/types/{typeId}/labels", courseLabelHandler::getLabelsByTypeId)
                .POST("/api/groupCourse/labels", courseLabelHandler::createLabel)
                .PUT("/api/groupCourse/labels/{id}", courseLabelHandler::updateLabel)
                .DELETE("/api/groupCourse/labels/{id}", courseLabelHandler::deleteLabel)
                .POST("/api/groupCourse/types/{typeId}/labels", courseLabelHandler::addLabelsToType)
                .DELETE("/api/groupCourse/types/{typeId}/labels/{labelId}", courseLabelHandler::removeLabelFromType)
                .DELETE("/api/groupCourse/types/{typeId}/labels", courseLabelHandler::clearLabelsFromType)

                // ===== 团课预约管理 =====
                .POST("/api/groupCourse/book", groupCourseBookingHandler::bookCourse)
                .POST("/api/groupCourse/booking/{bookingId}/cancel", groupCourseBookingHandler::cancelBooking)
                .GET("/api/groupCourse/bookings/member/{memberId}", groupCourseBookingHandler::getBookingsByMemberId)
                .GET("/api/groupCourse/bookings/course/{courseId}", groupCourseBookingHandler::getBookingsByCourseId)
                .GET("/api/groupCourse/bookings/{bookingId}", groupCourseBookingHandler::getBookingById)

                // ===== 团课推荐管理 =====
                .GET("/api/groupCourse/recommend/list", groupCourseRecommendHandler::getAllRecommendations)
                .GET("/api/groupCourse/recommend/active", groupCourseRecommendHandler::getAllActiveRecommendations)
                .GET("/api/groupCourse/recommend/{id}", groupCourseRecommendHandler::getRecommendationById)
                .GET("/api/groupCourse/recommend/course/{courseId}", groupCourseRecommendHandler::getRecommendationsByCourseId)
                .POST("/api/groupCourse/recommend", groupCourseRecommendHandler::createRecommendation)
                .PUT("/api/groupCourse/recommend/{id}", groupCourseRecommendHandler::updateRecommendation)
                .DELETE("/api/groupCourse/recommend/{id}", groupCourseRecommendHandler::deleteRecommendation)
                .POST("/api/groupCourse/recommend/{id}/enable", groupCourseRecommendHandler::enableRecommendation)
                .POST("/api/groupCourse/recommend/{id}/disable", groupCourseRecommendHandler::disableRecommendation)

                // ===== 团课课程管理（需要放在具体路由之后）=====
                .GET("/api/groupCourse/{id}", groupCourseHandler::getGroupCourseById)
                .GET("/api/groupCourse/{id}/detail", groupCourseHandler::getGroupCourseDetailById)
                .POST("/api/groupCourse", groupCourseHandler::createGroupCourse)
                .PUT("/api/groupCourse/{id}", groupCourseHandler::updateGroupCourse)
                .DELETE("/api/groupCourse/{id}", groupCourseHandler::deleteGroupCourse)
                .POST("/api/groupCourse/{id}/cancel", groupCourseHandler::cancelGroupCourse)
                .POST("/api/groupCourse/signin/{memberId}", groupCourseHandler::signIn)
                .POST("/api/groupCourse/search", groupCourseHandler::searchGroupCourses)
                
                // ========= 签到模块路由 ==========
                // ===== 签到核心功能 =====
                .POST("/api/checkIn", checkInHandler::checkIn)
                .GET("/api/checkIn/qrcode", checkInHandler::getQRCode)
                
                // ===== 签到记录管理 =====
                .GET("/api/checkIn/records", checkInHandler::getSignInRecords)
                .GET("/api/checkIn/records/{id}", checkInHandler::getSignInRecordById)
                
                // ===== 签到统计 =====
                .GET("/api/checkIn/statistics", checkInHandler::getSignInStatistics)
                .GET("/api/checkIn/daily-stats", checkInHandler::getDailySignInStats)
                
                // ===== 签到数据导出 =====
                .GET("/api/checkIn/records/export", checkInHandler::exportSignInRecords)

                // ========================================
                // ========== 数据统计模块路由 ============
                // ========================================

                // ===== 数据统计核心功能 =====
                .GET("/api/datacount/summary", dataStatisticsHandler::getStatisticsSummary)
                .GET("/api/datacount/member", dataStatisticsHandler::getMemberStatistics)
                .GET("/api/datacount/booking", dataStatisticsHandler::getBookingStatistics)
                .GET("/api/datacount/signin", dataStatisticsHandler::getSignInStatistics)
                .GET("/api/datacount/history", dataStatisticsHandler::queryHistoricalStatistics)
                .GET("/api/datacount/export", dataStatisticsHandler::exportStatistics)

                // ========================================
                // ========== 支付模块路由 =================
                // ========================================

                // ===== 支付宝App支付 =====
                .POST("/api/payment/create", paymentHandler::createPayment)
                .GET("/api/payment/{orderId}", paymentHandler::getPaymentStatus)
                .POST("/api/payment/{orderId}/refund", paymentHandler::refundPayment)
                .POST("/api/payment/notify", paymentHandler::alipayNotify)

                // ===== 支付宝扫码支付 =====
                .POST("/api/payment/qrcode/create", paymentHandler::createQrCodePayment)

                .build();
    }
}
