package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.WechatManagementDto;
import com.dora.entity.WechatMenu;
import com.dora.entity.WechatMessageTemplate;
import com.dora.entity.WechatKeywordReply;
import com.dora.service.WechatManagementService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 微信公众号管理控制器 - 管理端
 * 
 * @author dora
 * @date 2024/12/01
 */
@Slf4j
@RestController
@RequestMapping("/admin/wechat")
@Tag(name = "微信公众号管理", description = "微信公众号菜单和消息模板管理接口")
@RequiredArgsConstructor
public class AdminWechatManagementController {

    private final WechatManagementService wechatManagementService;

    // ==================== 菜单管理接口 ====================

    /**
     * 获取菜单树结构
     */
    @GetMapping("/menu/tree")
    @Operation(summary = "获取菜单树", description = "获取微信公众号菜单树结构")
    public Result<List<WechatMenu>> getMenuTree() {
        try {
            List<WechatMenu> menuTree = wechatManagementService.getMenuTree();
            return Result.success(menuTree);
        } catch (Exception e) {
            log.error("获取菜单树失败", e);
            return Result.error("获取菜单树失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取菜单详情
     */
    @GetMapping("/menu/{id}")
    @Operation(summary = "获取菜单详情", description = "根据ID获取菜单详细信息")
    public Result<WechatMenu> getMenuById(@PathVariable Long id) {
        try {
            WechatMenu menu = wechatManagementService.getMenuById(id);
            if (menu == null) {
                return Result.error("菜单不存在");
            }
            return Result.success(menu);
        } catch (Exception e) {
            log.error("获取菜单详情失败 - ID: {}", id, e);
            return Result.error("获取菜单详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建菜单
     */
    @PostMapping("/menu")
    @Operation(summary = "创建菜单", description = "创建新的微信公众号菜单")
    public Result<WechatMenu> createMenu(@Valid @RequestBody WechatManagementDto.MenuCreateRequest request) {
        try {
            WechatMenu menu = wechatManagementService.createMenu(request);
            return Result.success(menu);
        } catch (Exception e) {
            log.error("创建菜单失败", e);
            return Result.error("创建菜单失败：" + e.getMessage());
        }
    }

    /**
     * 更新菜单
     */
    @PutMapping("/menu/{id}")
    @Operation(summary = "更新菜单", description = "更新指定ID的菜单信息")
    public Result<WechatMenu> updateMenu(@PathVariable Long id, 
                                        @Valid @RequestBody WechatManagementDto.MenuUpdateRequest request) {
        try {
            WechatMenu menu = wechatManagementService.updateMenu(id, request);
            return Result.success(menu);
        } catch (Exception e) {
            log.error("更新菜单失败 - ID: {}", id, e);
            return Result.error("更新菜单失败：" + e.getMessage());
        }
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/menu/{id}")
    @Operation(summary = "删除菜单", description = "删除指定ID的菜单（级联删除子菜单）")
    public Result<Boolean> deleteMenu(@PathVariable Long id) {
        try {
            boolean success = wechatManagementService.deleteMenu(id);
            return success ? Result.success(true) : Result.error("删除菜单失败");
        } catch (Exception e) {
            log.error("删除菜单失败 - ID: {}", id, e);
            return Result.error("删除菜单失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新菜单状态
     */
    @PutMapping("/menu/status")
    @Operation(summary = "批量更新菜单状态", description = "批量启用或禁用菜单")
    public Result<Boolean> updateMenuStatus(@RequestParam List<Long> ids, 
                                           @RequestParam boolean enabled) {
        try {
            boolean success = wechatManagementService.updateMenuStatus(ids, enabled);
            return success ? Result.success(true) : Result.error("更新菜单状态失败");
        } catch (Exception e) {
            log.error("批量更新菜单状态失败", e);
            return Result.error("更新菜单状态失败：" + e.getMessage());
        }
    }

    /**
     * 发布菜单到微信服务器
     */
    @PostMapping("/menu/publish")
    @Operation(summary = "发布菜单", description = "将配置的菜单发布到微信公众号")
    public Result<Boolean> publishMenu() {
        try {
            boolean success = wechatManagementService.publishMenu();
            return success ? Result.success(true, "菜单发布成功") : Result.error("菜单发布失败");
        } catch (Exception e) {
            log.error("发布菜单失败", e);
            return Result.error("发布菜单失败：" + e.getMessage());
        }
    }

    /**
     * 删除微信服务器上的菜单
     */
    @DeleteMapping("/menu/wechat")
    @Operation(summary = "删除微信菜单", description = "删除微信公众号服务器上的菜单")
    public Result<Boolean> deleteWechatMenu() {
        try {
            boolean success = wechatManagementService.deleteWechatMenu();
            return success ? Result.success(true) : Result.error("删除微信菜单失败");
        } catch (Exception e) {
            log.error("删除微信菜单失败", e);
            return Result.error("删除微信菜单失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前微信服务器上的菜单
     */
    @GetMapping("/menu/current")
    @Operation(summary = "获取当前微信菜单", description = "获取微信公众号服务器上当前的菜单配置")
    public Result<WechatManagementDto.WechatMenuResponse> getCurrentWechatMenu() {
        try {
            WechatManagementDto.WechatMenuResponse response = wechatManagementService.getCurrentWechatMenu();
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取当前微信菜单失败", e);
            return Result.error("获取当前微信菜单失败：" + e.getMessage());
        }
    }

    // ==================== 消息模板管理接口 ====================

    /**
     * 分页获取消息模板列表
     */
    @GetMapping("/template")
    @Operation(summary = "获取消息模板列表", description = "分页获取消息模板列表")
    public Result<WechatManagementDto.TemplatePageResponse> getTemplateList(
            @Parameter(description = "模板名称") @RequestParam(required = false) String templateName,
            @Parameter(description = "模板类型") @RequestParam(required = false) String templateType,
            @Parameter(description = "触发类型") @RequestParam(required = false) String triggerType,
            @Parameter(description = "是否启用") @RequestParam(required = false) Integer isEnabled,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        
        try {
            WechatManagementDto.TemplateQueryRequest request = new WechatManagementDto.TemplateQueryRequest();
            request.setTemplateName(templateName);
            request.setTemplateType(templateType);
            request.setTriggerType(triggerType);
            request.setIsEnabled(isEnabled);
            request.setPage(page);
            request.setSize(size);

            WechatManagementDto.TemplatePageResponse response = wechatManagementService.getTemplateList(request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取消息模板列表失败", e);
            return Result.error("获取消息模板列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取消息模板详情
     */
    @GetMapping("/template/{id}")
    @Operation(summary = "获取消息模板详情", description = "根据ID获取消息模板详细信息")
    public Result<WechatMessageTemplate> getTemplateById(@PathVariable Long id) {
        try {
            WechatMessageTemplate template = wechatManagementService.getTemplateById(id);
            if (template == null) {
                return Result.error("消息模板不存在");
            }
            return Result.success(template);
        } catch (Exception e) {
            log.error("获取消息模板详情失败 - ID: {}", id, e);
            return Result.error("获取消息模板详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建消息模板
     */
    @PostMapping("/template")
    @Operation(summary = "创建消息模板", description = "创建新的消息模板")
    public Result<WechatMessageTemplate> createTemplate(@Valid @RequestBody WechatManagementDto.TemplateCreateRequest request) {
        try {
            WechatMessageTemplate template = wechatManagementService.createTemplate(request);
            return Result.success(template);
        } catch (Exception e) {
            log.error("创建消息模板失败", e);
            return Result.error("创建消息模板失败：" + e.getMessage());
        }
    }

    /**
     * 更新消息模板
     */
    @PutMapping("/template/{id}")
    @Operation(summary = "更新消息模板", description = "更新指定ID的消息模板")
    public Result<WechatMessageTemplate> updateTemplate(@PathVariable Long id, 
                                                        @Valid @RequestBody WechatManagementDto.TemplateUpdateRequest request) {
        try {
            WechatMessageTemplate template = wechatManagementService.updateTemplate(id, request);
            return Result.success(template);
        } catch (Exception e) {
            log.error("更新消息模板失败 - ID: {}", id, e);
            return Result.error("更新消息模板失败：" + e.getMessage());
        }
    }

    /**
     * 删除消息模板
     */
    @DeleteMapping("/template/{id}")
    @Operation(summary = "删除消息模板", description = "删除指定ID的消息模板")
    public Result<Boolean> deleteTemplate(@PathVariable Long id) {
        try {
            boolean success = wechatManagementService.deleteTemplate(id);
            return success ? Result.success(true) : Result.error("删除消息模板失败");
        } catch (Exception e) {
            log.error("删除消息模板失败 - ID: {}", id, e);
            return Result.error("删除消息模板失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新模板状态
     */
    @PutMapping("/template/status")
    @Operation(summary = "批量更新模板状态", description = "批量启用或禁用消息模板")
    public Result<Boolean> updateTemplateStatus(@RequestParam List<Long> ids, 
                                               @RequestParam boolean enabled) {
        try {
            boolean success = wechatManagementService.updateTemplateStatus(ids, enabled);
            return success ? Result.success(true) : Result.error("更新模板状态失败");
        } catch (Exception e) {
            log.error("批量更新模板状态失败", e);
            return Result.error("更新模板状态失败：" + e.getMessage());
        }
    }

    // ==================== 关键词回复管理接口 ====================

    /**
     * 分页获取关键词回复列表
     */
    @GetMapping("/keyword")
    @Operation(summary = "获取关键词回复列表", description = "分页获取关键词回复配置列表")
    public Result<WechatManagementDto.KeywordReplyPageResponse> getKeywordReplyList(
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "匹配类型") @RequestParam(required = false) String matchType,
            @Parameter(description = "是否启用") @RequestParam(required = false) Integer isEnabled,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        
        try {
            WechatManagementDto.KeywordReplyQueryRequest request = new WechatManagementDto.KeywordReplyQueryRequest();
            request.setKeyword(keyword);
            request.setMatchType(matchType);
            request.setIsEnabled(isEnabled);
            request.setPage(page);
            request.setSize(size);

            WechatManagementDto.KeywordReplyPageResponse response = wechatManagementService.getKeywordReplyList(request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取关键词回复列表失败", e);
            return Result.error("获取关键词回复列表失败：" + e.getMessage());
        }
    }

    /**
     * 创建关键词回复
     */
    @PostMapping("/keyword")
    @Operation(summary = "创建关键词回复", description = "创建新的关键词回复配置")
    public Result<WechatKeywordReply> createKeywordReply(@Valid @RequestBody WechatManagementDto.KeywordReplyCreateRequest request) {
        try {
            WechatKeywordReply keywordReply = wechatManagementService.createKeywordReply(request);
            return Result.success(keywordReply);
        } catch (Exception e) {
            log.error("创建关键词回复失败", e);
            return Result.error("创建关键词回复失败：" + e.getMessage());
        }
    }

    /**
     * 更新关键词回复
     */
    @PutMapping("/keyword/{id}")
    @Operation(summary = "更新关键词回复", description = "更新指定ID的关键词回复配置")
    public Result<WechatKeywordReply> updateKeywordReply(@PathVariable Long id, 
                                                        @Valid @RequestBody WechatManagementDto.KeywordReplyUpdateRequest request) {
        try {
            WechatKeywordReply keywordReply = wechatManagementService.updateKeywordReply(id, request);
            return Result.success(keywordReply);
        } catch (Exception e) {
            log.error("更新关键词回复失败 - ID: {}", id, e);
            return Result.error("更新关键词回复失败：" + e.getMessage());
        }
    }

    /**
     * 删除关键词回复
     */
    @DeleteMapping("/keyword/{id}")
    @Operation(summary = "删除关键词回复", description = "删除指定ID的关键词回复配置")
    public Result<Boolean> deleteKeywordReply(@PathVariable Long id) {
        try {
            boolean success = wechatManagementService.deleteKeywordReply(id);
            return success ? Result.success(true) : Result.error("删除关键词回复失败");
        } catch (Exception e) {
            log.error("删除关键词回复失败 - ID: {}", id, e);
            return Result.error("删除关键词回复失败：" + e.getMessage());
        }
    }

    // ==================== 素材管理接口 ====================

    @PostMapping("/media/upload")
    @Operation(summary = "上传永久素材", description = "上传图片、语音、视频等永久素材到微信服务器")
    public Result<WechatManagementDto.MediaUploadResult> uploadPermanentMedia(
            @Parameter(description = "要上传的文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "素材类型 (image, voice, video, thumb)") @RequestParam("type") String mediaType,
            @Parameter(description = "视频标题 (视频类型必须)") @RequestParam(required = false) String title,
            @Parameter(description = "视频描述 (视频类型必须)") @RequestParam(required = false) String introduction) {
        try {
            WechatManagementDto.MediaUploadResult result = wechatManagementService.uploadPermanentMedia(file, mediaType, title, introduction);
            return Result.success(result);
        } catch (IOException e) {
            log.error("上传素材文件处理失败", e);
            return Result.error("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("上传永久素材失败", e);
            return Result.error("上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/media/list")
    @Operation(summary = "获取永久素材列表", description = "分页获取微信服务器上的永久素材列表")
    public Result<WechatManagementDto.MediaFilePageResponse> listPermanentMedia(
            @Parameter(description = "素材类型 (image, voice, video, news)") @RequestParam String type,
            @Parameter(description = "页码 (从1开始)") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量 (1-20)") @RequestParam(defaultValue = "10") int size) {
        try {
            WechatManagementDto.MediaFilePageResponse result = wechatManagementService.listPermanentMedia(type, page, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取永久素材列表失败", e);
            return Result.error("获取列表失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/media")
    @Operation(summary = "删除永久素材", description = "根据media_id删除微信服务器上的永久素材")
    public Result<Boolean> deletePermanentMedia(
            @Parameter(description = "素材的media_id") @RequestParam String mediaId) {
        try {
            boolean success = wechatManagementService.deletePermanentMedia(mediaId);
            return success ? Result.success(true) : Result.error("删除素材失败");
        } catch (Exception e) {
            log.error("删除永久素材失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    // ==================== 统计分析接口 ====================

    /**
     * 获取管理概览统计
     */
    @GetMapping("/overview")
    @Operation(summary = "获取管理概览", description = "获取微信公众号管理的统计概览信息")
    public Result<WechatManagementDto.ManagementOverview> getManagementOverview() {
        try {
            WechatManagementDto.ManagementOverview overview = wechatManagementService.getManagementOverview();
            return Result.success(overview);
        } catch (Exception e) {
            log.error("获取管理概览失败", e);
            return Result.error("获取管理概览失败：" + e.getMessage());
        }
    }
}
