using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Dto.Pet;
using QYZH.InteractiveMagazine.Models.Enum;

namespace QYZH.InteractiveMagazine.WebApi.Controllers;

/// <summary>
/// 宠物管理控制器（后台）
/// </summary>
[Route("api/[controller]")]
[ApiController]
[ApiExplorerSettings(GroupName = nameof(ApiVersionEnum.Platform))]
public class PetManageController : BaseController
{
    private readonly IPetService _petService;
    private readonly ILogger<PetManageController> _logger;

    public PetManageController(IPetService petService, ILogger<PetManageController> logger)
    {
        _petService = petService;
        _logger = logger;
    }

    // ==================== 宠物模板管理 ====================

    /// <summary>
    /// 创建宠物模板
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse<PetTemplateOutput>> CreateTemplateAsync([FromBody] PetTemplateInput input)
    {
        try
        {
            var result = await _petService.CreateTemplateAsync(input);
            return Success(result, "创建宠物模板成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "创建宠物模板业务异常: {Message}", ex.Message);
            return BaseResponse<PetTemplateOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建宠物模板系统异常");
            return BaseResponse<PetTemplateOutput>.Fail("创建宠物模板失败，请稍后重试");
        }
    }

    /// <summary>
    /// 更新宠物模板
    /// </summary>
    [HttpPut("{id}")]
    public async Task<BaseResponse<PetTemplateOutput>> UpdateTemplateAsync(long id, [FromBody] PetTemplateInput input)
    {
        try
        {
            var result = await _petService.UpdateTemplateAsync(id, input);
            return Success(result, "更新宠物模板成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "更新宠物模板业务异常: {Message}", ex.Message);
            return BaseResponse<PetTemplateOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新宠物模板系统异常，ID：{Id}", id);
            return BaseResponse<PetTemplateOutput>.Fail("更新宠物模板失败，请稍后重试");
        }
    }

    /// <summary>
    /// 删除宠物模板
    /// </summary>
    [HttpDelete("{id}")]
    public async Task<BaseResponse<object>> DeleteTemplateAsync(long id)
    {
        try
        {
            await _petService.DeleteTemplateAsync(id);
            return Success(new object(), "删除宠物模板成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "删除宠物模板业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除宠物模板系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("删除宠物模板失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取单个宠物模板
    /// </summary>
    [HttpGet("{id}")]
    public async Task<BaseResponse<PetTemplateOutput>> GetTemplateByIdAsync(long id)
    {
        try
        {
            var result = await _petService.GetTemplateByIdAsync(id);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取宠物模板业务异常: {Message}", ex.Message);
            return BaseResponse<PetTemplateOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取宠物模板系统异常，ID：{Id}", id);
            return BaseResponse<PetTemplateOutput>.Fail("获取宠物模板失败，请稍后重试");
        }
    }

    /// <summary>
    /// 分页查询宠物模板列表
    /// </summary>
    [HttpPost("list")]
    public async Task<BaseResponse<PageListModel<PetTemplateOutput>>> GetTemplatesAsync([FromBody] PetTemplateQueryInput input)
    {
        try
        {
            var result = await _petService.GetTemplatesAsync(input);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "查询宠物模板列表业务异常: {Message}", ex.Message);
            return BaseResponse<PageListModel<PetTemplateOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询宠物模板列表系统异常");
            return BaseResponse<PageListModel<PetTemplateOutput>>.Fail("查询宠物模板列表失败，请稍后重试");
        }
    }

    /// <summary>
    /// 更新宠物模板状态（启用/禁用）
    /// </summary>
    [HttpPut("{id}/status")]
    public async Task<BaseResponse<object>> UpdateTemplateStatusAsync(long id)
    {
        try
        {
            await _petService.UpdateTemplateStatusAsync(id);
            return Success(new object(), "更新状态成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "更新模板状态业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新模板状态系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("更新模板状态失败，请稍后重试");
        }
    }

    // ==================== 进化链管理 ====================

    /// <summary>
    /// 创建进化阶段
    /// </summary>
    [HttpPost("evolution")]
    public async Task<BaseResponse<PetEvolutionOutput>> CreateEvolutionAsync([FromBody] PetEvolutionInput input)
    {
        try
        {
            var result = await _petService.CreateEvolutionAsync(input);
            return Success(result, "创建进化阶段成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "创建进化阶段业务异常: {Message}", ex.Message);
            return BaseResponse<PetEvolutionOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建进化阶段系统异常");
            return BaseResponse<PetEvolutionOutput>.Fail("创建进化阶段失败，请稍后重试");
        }
    }

    /// <summary>
    /// 更新进化阶段
    /// </summary>
    [HttpPut("evolution/{id}")]
    public async Task<BaseResponse<PetEvolutionOutput>> UpdateEvolutionAsync(long id, [FromBody] PetEvolutionInput input)
    {
        try
        {
            var result = await _petService.UpdateEvolutionAsync(id, input);
            return Success(result, "更新进化阶段成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "更新进化阶段业务异常: {Message}", ex.Message);
            return BaseResponse<PetEvolutionOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新进化阶段系统异常，ID：{Id}", id);
            return BaseResponse<PetEvolutionOutput>.Fail("更新进化阶段失败，请稍后重试");
        }
    }

    /// <summary>
    /// 删除进化阶段
    /// </summary>
    [HttpDelete("evolution/{id}")]
    public async Task<BaseResponse<object>> DeleteEvolutionAsync(long id)
    {
        try
        {
            await _petService.DeleteEvolutionAsync(id);
            return Success(new object(), "删除进化阶段成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "删除进化阶段业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除进化阶段系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("删除进化阶段失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取单个进化阶段
    /// </summary>
    [HttpGet("evolution/{id}")]
    public async Task<BaseResponse<PetEvolutionOutput>> GetEvolutionByIdAsync(long id)
    {
        try
        {
            var result = await _petService.GetEvolutionByIdAsync(id);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取进化阶段业务异常: {Message}", ex.Message);
            return BaseResponse<PetEvolutionOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取进化阶段系统异常，ID：{Id}", id);
            return BaseResponse<PetEvolutionOutput>.Fail("获取进化阶段失败，请稍后重试");
        }
    }

    /// <summary>
    /// 分页查询进化阶段列表
    /// </summary>
    [HttpPost("evolution/list")]
    public async Task<BaseResponse<PageListModel<PetEvolutionOutput>>> GetEvolutionsAsync([FromBody] PetEvolutionQueryInput input)
    {
        try
        {
            var result = await _petService.GetEvolutionsAsync(input);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "查询进化阶段列表业务异常: {Message}", ex.Message);
            return BaseResponse<PageListModel<PetEvolutionOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询进化阶段列表系统异常");
            return BaseResponse<PageListModel<PetEvolutionOutput>>.Fail("查询进化阶段列表失败，请稍后重试");
        }
    }

    // ==================== 皮肤管理 ====================

    /// <summary>
    /// 创建皮肤
    /// </summary>
    [HttpPost("skin")]
    public async Task<BaseResponse<PetSkinOutput>> CreateSkinAsync([FromBody] PetSkinInput input)
    {
        try
        {
            var result = await _petService.CreateSkinAsync(input);
            return Success(result, "创建皮肤成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "创建皮肤业务异常: {Message}", ex.Message);
            return BaseResponse<PetSkinOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建皮肤系统异常");
            return BaseResponse<PetSkinOutput>.Fail("创建皮肤失败，请稍后重试");
        }
    }

    /// <summary>
    /// 更新皮肤
    /// </summary>
    [HttpPut("skin/{id}")]
    public async Task<BaseResponse<PetSkinOutput>> UpdateSkinAsync(long id, [FromBody] PetSkinInput input)
    {
        try
        {
            var result = await _petService.UpdateSkinAsync(id, input);
            return Success(result, "更新皮肤成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "更新皮肤业务异常: {Message}", ex.Message);
            return BaseResponse<PetSkinOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新皮肤系统异常，ID：{Id}", id);
            return BaseResponse<PetSkinOutput>.Fail("更新皮肤失败，请稍后重试");
        }
    }

    /// <summary>
    /// 删除皮肤
    /// </summary>
    [HttpDelete("skin/{id}")]
    public async Task<BaseResponse<object>> DeleteSkinAsync(long id)
    {
        try
        {
            await _petService.DeleteSkinAsync(id);
            return Success(new object(), "删除皮肤成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "删除皮肤业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除皮肤系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("删除皮肤失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取单个皮肤（含图片列表）
    /// </summary>
    [HttpGet("skin/{id}")]
    public async Task<BaseResponse<PetSkinOutput>> GetSkinByIdAsync(long id)
    {
        try
        {
            var result = await _petService.GetSkinByIdAsync(id);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取皮肤业务异常: {Message}", ex.Message);
            return BaseResponse<PetSkinOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取皮肤系统异常，ID：{Id}", id);
            return BaseResponse<PetSkinOutput>.Fail("获取皮肤失败，请稍后重试");
        }
    }

    /// <summary>
    /// 分页查询皮肤列表
    /// </summary>
    [HttpPost("skin/list")]
    public async Task<BaseResponse<PageListModel<PetSkinOutput>>> GetSkinsAsync([FromBody] PetSkinQueryInput input)
    {
        try
        {
            var result = await _petService.GetSkinsAsync(input);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "查询皮肤列表业务异常: {Message}", ex.Message);
            return BaseResponse<PageListModel<PetSkinOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询皮肤列表系统异常");
            return BaseResponse<PageListModel<PetSkinOutput>>.Fail("查询皮肤列表失败，请稍后重试");
        }
    }

    // ==================== 皮肤图片管理 ====================

    /// <summary>
    /// 创建皮肤图片
    /// </summary>
    [HttpPost("skin-image")]
    public async Task<BaseResponse<PetSkinImageOutput>> CreateSkinImageAsync([FromBody] PetSkinImageInput input)
    {
        try
        {
            var result = await _petService.CreateSkinImageAsync(input);
            return Success(result, "创建皮肤图片成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "创建皮肤图片业务异常: {Message}", ex.Message);
            return BaseResponse<PetSkinImageOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建皮肤图片系统异常");
            return BaseResponse<PetSkinImageOutput>.Fail("创建皮肤图片失败，请稍后重试");
        }
    }

    /// <summary>
    /// 更新皮肤图片
    /// </summary>
    [HttpPut("skin-image/{id}")]
    public async Task<BaseResponse<PetSkinImageOutput>> UpdateSkinImageAsync(long id, [FromBody] PetSkinImageInput input)
    {
        try
        {
            var result = await _petService.UpdateSkinImageAsync(id, input);
            return Success(result, "更新皮肤图片成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "更新皮肤图片业务异常: {Message}", ex.Message);
            return BaseResponse<PetSkinImageOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新皮肤图片系统异常，ID：{Id}", id);
            return BaseResponse<PetSkinImageOutput>.Fail("更新皮肤图片失败，请稍后重试");
        }
    }

    /// <summary>
    /// 删除皮肤图片
    /// </summary>
    [HttpDelete("skin-image/{id}")]
    public async Task<BaseResponse<object>> DeleteSkinImageAsync(long id)
    {
        try
        {
            await _petService.DeleteSkinImageAsync(id);
            return Success(new object(), "删除皮肤图片成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "删除皮肤图片业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除皮肤图片系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("删除皮肤图片失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取指定皮肤的所有图片
    /// </summary>
    [HttpGet("skin-images/{skinId}")]
    public async Task<BaseResponse<List<PetSkinImageOutput>>> GetSkinImagesAsync(long skinId)
    {
        try
        {
            var result = await _petService.GetSkinImagesBySkinIdAsync(skinId);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取皮肤图片列表业务异常: {Message}", ex.Message);
            return BaseResponse<List<PetSkinImageOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取皮肤图片列表系统异常，SkinId：{SkinId}", skinId);
            return BaseResponse<List<PetSkinImageOutput>>.Fail("获取皮肤图片列表失败，请稍后重试");
        }
    }

    // ==================== 便捷查询接口 ====================

    /// <summary>
    /// 根据模板Id获取进化链列表（非分页）
    /// </summary>
    [HttpGet("evolutions/{templateId}")]
    public async Task<BaseResponse<List<PetEvolutionOutput>>> GetEvolutionsByTemplateIdAsync(long templateId)
    {
        try
        {
            var result = await _petService.GetEvolutionsByTemplateIdAsync(templateId);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取进化链列表业务异常: {Message}", ex.Message);
            return BaseResponse<List<PetEvolutionOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取进化链列表系统异常，TemplateId：{TemplateId}", templateId);
            return BaseResponse<List<PetEvolutionOutput>>.Fail("获取进化链列表失败，请稍后重试");
        }
    }

    /// <summary>
    /// 根据模板Id获取皮肤列表（非分页）
    /// </summary>
    [HttpGet("skins/{templateId}")]
    public async Task<BaseResponse<List<PetSkinOutput>>> GetSkinsByTemplateIdAsync(long templateId)
    {
        try
        {
            var result = await _petService.GetSkinsByTemplateIdAsync(templateId);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取皮肤列表业务异常: {Message}", ex.Message);
            return BaseResponse<List<PetSkinOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取皮肤列表系统异常，TemplateId：{TemplateId}", templateId);
            return BaseResponse<List<PetSkinOutput>>.Fail("获取皮肤列表失败，请稍后重试");
        }
    }

    /// <summary>
    /// 根据皮肤Id获取各阶段图片列表（按进化阶段分组，含阶段基本信息）
    /// </summary>
    [HttpGet("skin-images-grouped/{skinId}")]
    public async Task<BaseResponse<List<SkinEvolutionStageOutput>>> GetSkinImagesGroupedBySkinIdAsync(long skinId)
    {
        try
        {
            var result = await _petService.GetSkinImagesGroupedBySkinIdAsync(skinId);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取分组皮肤图片业务异常: {Message}", ex.Message);
            return BaseResponse<List<SkinEvolutionStageOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取分组皮肤图片系统异常，SkinId：{SkinId}", skinId);
            return BaseResponse<List<SkinEvolutionStageOutput>>.Fail("获取分组皮肤图片失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取所有皮肤下拉列表
    /// </summary>
    /// <param name="types">皮肤类型列表（可选）</param>
    [HttpGet("skins/select")]
    public async Task<BaseResponse<List<SelectOptionDto>>> GetAllSkinsForSelectAsync([FromQuery] List<string>? types = null)
    {
        try
        {
            var result = await _petService.GetAllSkinsForSelectAsync(types);
            return Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取皮肤下拉列表系统异常");
            return BaseResponse<List<SelectOptionDto>>.Fail("获取皮肤下拉列表失败，请稍后重试");
        }
    }
}
