package com.moka.gdtauto.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moka.gdtauto.annotation.AuthUser;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.controller.vo.AccountGroupAccountRequest;
import com.moka.gdtauto.controller.vo.CreateAccountGroupRequest;
import com.moka.gdtauto.controller.vo.UpdateAccountGroupRequest;
import com.moka.gdtauto.entity.AccountGroup;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.service.AccountGroupService;
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 java.util.List;

/**
 * 账号组管理控制器
 *
 * @author moka
 * @since 2026-02-24
 */
@Tag(name = "账号组管理", description = "账号组的创建、更新、删除及账号关联管理")
@Slf4j
@RestController
@RequestMapping("/api/account-group")
@RequiredArgsConstructor
public class AccountGroupController {

    private final AccountGroupService accountGroupService;

    /**
     * 创建账号组
     */
    @Operation(summary = "创建账号组", description = "为当前用户创建新的账号组，可同时选择账号")
    @PostMapping("/create")
    public Result<Long> createAccountGroup(
            @RequestBody CreateAccountGroupRequest request,
            @AuthUser SysUser sysUser) {
        try {
            Long groupId = accountGroupService.createAccountGroup(
                    sysUser.getId(),
                    request.getGroupName(),
                    request.getDeliveryMode(),
                    request.getRemark(),
                    request.getAccountIds()
            );
            return Result.success(groupId, "创建账号组成功");
        } catch (Exception e) {
            log.error("创建账号组失败", e);
            return Result.fail("创建账号组失败: " + e.getMessage());
        }
    }

    /**
     * 更新账号组
     */
    @Operation(summary = "更新账号组", description = "更新指定账号组的信息，可同时更新关联账号")
    @PostMapping("/update")
    public Result<Void> updateAccountGroup(
            @RequestBody UpdateAccountGroupRequest request,
            @AuthUser SysUser sysUser) {
        try {
            boolean success = accountGroupService.updateAccountGroup(
                    request.getGroupId(),
                    sysUser.getId(),
                    request.getGroupName(),
                    request.getDeliveryMode(),
                    request.getRemark(),
                    request.getAccountIds()
            );
            if (success) {
                return Result.success("更新账号组成功");
            } else {
                return Result.fail("账号组不存在或无权限");
            }
        } catch (Exception e) {
            log.error("更新账号组失败", e);
            return Result.fail("更新账号组失败: " + e.getMessage());
        }
    }

    /**
     * 删除账号组
     */
    @Operation(summary = "删除账号组", description = "删除指定的账号组")
    @DeleteMapping("/{groupId}")
    public Result<Void> deleteAccountGroup(
            @Parameter(description = "账号组ID", required = true)
            @PathVariable Long groupId,
            @AuthUser SysUser sysUser) {
        try {
            boolean success = accountGroupService.deleteAccountGroup(groupId, sysUser.getId());
            if (success) {
                return Result.success("删除账号组成功");
            } else {
                return Result.fail("账号组不存在或无权限");
            }
        } catch (Exception e) {
            log.error("删除账号组失败", e);
            return Result.fail("删除账号组失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的账号组列表（分页）
     */
    @Operation(summary = "获取账号组列表", description = "分页获取当前用户的所有账号组")
    @GetMapping("/list")
    public Result<Page<AccountGroup>> getAccountGroups(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer pageSize,
            @AuthUser SysUser sysUser) {
        try {
            Page<AccountGroup> page = accountGroupService.getUserAccountGroups(
                    sysUser.getId(), pageNum, pageSize);
            return Result.success(page, "查询成功");
        } catch (Exception e) {
            log.error("查询账号组列表失败", e);
            return Result.fail("查询账号组列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的账号组列表（不分页）
     */
    @GetMapping("/all")
    public Result<List<AccountGroup>> getAllAccountGroups(
            @AuthUser SysUser sysUser) {
        try {
            List<AccountGroup> accountGroups = accountGroupService.lambdaQuery()
                    .eq(AccountGroup::getUserId, sysUser.getId())
                    .orderByDesc(AccountGroup::getId)
                    .list();
            return Result.success(accountGroups, "查询成功");
        } catch (Exception e) {
            log.error("查询账号组列表失败", e);
            return Result.fail("查询账号组列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取账号组详情
     */
    @Operation(summary = "获取账号组详情", description = "根据ID获取账号组详细信息")
    @GetMapping("/{groupId}")
    public Result<AccountGroup> getAccountGroup(
            @Parameter(description = "账号组ID", required = true)
            @PathVariable Long groupId,
            @AuthUser SysUser sysUser) {
        try {
            AccountGroup accountGroup = accountGroupService.getAccountGroupById(groupId, sysUser.getId());
            if (accountGroup != null) {
                return Result.success(accountGroup, "查询成功");
            } else {
                return Result.fail("账号组不存在或无权限");
            }
        } catch (Exception e) {
            log.error("查询账号组详情失败", e);
            return Result.fail("查询账号组详情失败: " + e.getMessage());
        }
    }

    /**
     * 添加账号到账号组
     */
    @Operation(summary = "添加账号到账号组", description = "将一个或多个账号添加到指定账号组")
    @PostMapping("/add-accounts")
    public Result<Void> addAccountsToGroup(
            @RequestBody AccountGroupAccountRequest request,
            @AuthUser SysUser sysUser) {
        try {
            boolean success = accountGroupService.addAccountsToGroup(
                    request.getGroupId(),
                    request.getAccountIds(),
                    sysUser.getId()
            );
            if (success) {
                return Result.success("添加账号成功");
            } else {
                return Result.fail("账号组不存在或无权限");
            }
        } catch (Exception e) {
            log.error("添加账号到账号组失败", e);
            return Result.fail("添加账号失败: " + e.getMessage());
        }
    }

    /**
     * 从账号组移除账号
     */
    @Operation(summary = "从账号组移除账号", description = "从指定账号组移除一个或多个账号")
    @PostMapping("/remove-accounts")
    public Result<Void> removeAccountsFromGroup(
            @RequestBody AccountGroupAccountRequest request,
            @AuthUser SysUser sysUser) {
        try {
            boolean success = accountGroupService.removeAccountsFromGroup(
                    request.getGroupId(),
                    request.getAccountIds(),
                    sysUser.getId()
            );
            if (success) {
                return Result.success("移除账号成功");
            } else {
                return Result.fail("账号组不存在或无权限");
            }
        } catch (Exception e) {
            log.error("从账号组移除账号失败", e);
            return Result.fail("移除账号失败: " + e.getMessage());
        }
    }

    /**
     * 获取账号组下的所有账号ID
     */
    @Operation(summary = "获取账号组的账号列表", description = "获取指定账号组关联的所有账号ID")
    @GetMapping("/{groupId}/accounts")
    public Result<List<Long>> getAccountIdsByGroupId(
            @Parameter(description = "账号组ID", required = true)
            @PathVariable Long groupId,
            @AuthUser SysUser sysUser) {
        try {
            List<Long> accountIds = accountGroupService.getAccountIdsByGroupId(groupId, sysUser.getId());
            return Result.success(accountIds, "查询成功");
        } catch (Exception e) {
            log.error("查询账号组账号列表失败", e);
            return Result.fail("查询账号组账号列表失败: " + e.getMessage());
        }
    }
}
