package com.bizzan.bitrade.controller.staking;

import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.dto.BatchAirdropDistributeRequest;
import com.bizzan.bitrade.dto.StakingOrderVO;
import com.bizzan.bitrade.entity.AirdropRecord;
import com.bizzan.bitrade.entity.StakingConfig;
import com.bizzan.bitrade.entity.StakingRecord;
import com.bizzan.bitrade.service.AirdropPoolService;
import com.bizzan.bitrade.service.StakingService;
import com.bizzan.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 管理员质押管理接口，支持配置管理和查看订单、流水
 *
 * @author auto
 * @date 2026-05-17
 */
@RestController
@RequestMapping("/staking")
@Slf4j
public class StakingAdminController extends BaseAdminController {

    @Autowired
    private StakingService stakingService;

    @Autowired
    private AirdropPoolService airdropPoolService;

    // ========================= 质押配置管理 =========================

    /**
     * 查询所有质押配置（含禁用）
     *
     * @return 配置列表
     */
    @RequiresPermissions("staking:config")
    @PostMapping("/config/list")
    public MessageResult listConfigs() {
        List<StakingConfig> configs = stakingService.getAllConfigs();
        return success(configs);
    }

    /**
     * 新增质押配置（指定可质押的自定义币种及规则）
     *
     * @param config 质押配置信息
     * @return 新增后的配置
     */
    @RequiresPermissions("staking:config")
    @PostMapping("/config/add")
    public MessageResult addConfig(@RequestBody StakingConfig config) {
        // 新增时清除ID，由数据库自增生成
        config.setId(null);
        try {
            StakingConfig saved = stakingService.saveConfig(config);
            return success(saved);
        } catch (IllegalArgumentException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改质押配置（可修改最小金额、锁定天数、释放规则、状态等）
     *
     * @param config 质押配置（需含ID）
     * @return 修改后的配置
     */
    @RequiresPermissions("staking:config")
    @PostMapping("/config/update")
    public MessageResult updateConfig(@RequestBody StakingConfig config) {
        if (config.getId() == null) {
            return error("配置ID不能为空");
        }
        try {
            StakingConfig saved = stakingService.saveConfig(config);
            return success(saved);
        } catch (IllegalArgumentException e) {
            return error(e.getMessage());
        }
    }

    // ========================= 质押订单查询 =========================

    /**
     * 分页查询所有用户的质押订单
     *
     * @param pageNo   页码（从1开始）
     * @param pageSize 每页条数
     * @return 订单分页数据
     */
    @RequiresPermissions("staking:order")
    @PostMapping("/orders")
    public MessageResult listOrders(@RequestParam(defaultValue = "1") int pageNo,
                                    @RequestParam(defaultValue = "20") int pageSize,
                                    @RequestParam(required = false) Integer status,
                                    @RequestParam(required = false) Long memberId,
                                    @RequestParam(required = false) String coinUnit,
                                    @RequestParam(required = false) Boolean pendingAirdropToday) {
        Page<StakingOrderVO> page = stakingService.getAllStakingOrders(
                pageNo, pageSize, status, memberId, coinUnit, pendingAirdropToday);
        return success(page);
    }

    /**
     * 对质押中的订单发放空投（同一订单每日限一次）
     */
    @RequiresPermissions("staking:order")
    @PostMapping("/orders/airdrop-distribute")
    public MessageResult distributeAirdrop(@RequestBody AirdropRecord record) {
        return airdropPoolService.distribute(record);
    }

    /**
     * 批量发放空投（统一金额，仅质押中且今日未发放的订单）
     */
    @RequiresPermissions("staking:order")
    @PostMapping("/orders/airdrop-distribute/batch")
    public MessageResult batchDistributeAirdrop(@RequestBody BatchAirdropDistributeRequest request) {
        return airdropPoolService.batchDistribute(request.getStakingOrderIds(), request.getAmount());
    }

    // ========================= 质押流水查询 =========================

    /**
     * 分页查询所有质押流水（质押和释放）
     *
     * @param pageNo   页码（从1开始）
     * @param pageSize 每页条数
     * @return 流水分页数据
     */
    @RequiresPermissions("staking:record")
    @PostMapping("/records")
    public MessageResult listRecords(@RequestParam(defaultValue = "1") int pageNo,
                                     @RequestParam(defaultValue = "20") int pageSize) {
        Page<StakingRecord> page = stakingService.getAllStakingRecords(pageNo, pageSize);
        return success(page);
    }
}
