package com.it.rattan.monisuo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.rattan.monisuo.common.Result;
import com.it.rattan.monisuo.entity.*;
import com.it.rattan.monisuo.mapper.AccountFundMapper;
import com.it.rattan.monisuo.mapper.OrderFundMapper;
import com.it.rattan.monisuo.service.*;
import com.it.rattan.monisuo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理后台接口
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private FundService fundService;

    @Autowired
    private AssetService assetService;

    @Autowired
    private AccountFundMapper accountFundMapper;

    @Autowired
    private OrderFundMapper orderFundMapper;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");

        if (username == null || password == null) {
            return Result.fail("用户名和密码不能为空");
        }

        // 简单验证，实际应从数据库查询
        // 这里预置账号: admin/admin123, superadmin/admin123
        String validPassword = "$2a$12$VSVV5o6OXguuFh4f7JvQielF22zxvsvjITkOr/K8D5TnZZcVtQ0B2"; // admin123
        org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder encoder =
                new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();

        // 临时处理：预置账号
        if (("admin".equals(username) || "superadmin".equals(username)) &&
                encoder.matches(password, validPassword)) {
            String token = JwtUtil.createToken(1L, username, "admin");

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            Map<String, Object> adminInfo = new HashMap<>();
            adminInfo.put("id", 1L);
            adminInfo.put("username", username);
            adminInfo.put("nickname", "超级管理员");
            adminInfo.put("role", 1);
            adminInfo.put("avatar", "/avatars/admin.jpg");
            result.put("adminInfo", adminInfo);
            return Result.success("登录成功", result);
        }

        return Result.fail("用户名或密码错误");
    }

    /**
     * 用户列表
     */
    @GetMapping("/user/list")
    public Result<Map<String, Object>> getUserList(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            wrapper.like(User::getUsername, username);
        }
        if (status != null) {
            wrapper.eq(User::getStatus, status);
        }
        wrapper.orderByDesc(User::getCreateTime);

        Page<User> page = new Page<>(pageNum, pageSize);
        IPage<User> result = userService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.getRecords());
        data.put("total", result.getTotal());
        data.put("pageNum", result.getCurrent());
        data.put("pageSize", result.getSize());
        return Result.success(data);
    }

    /**
     * 用户详情
     */
    @GetMapping("/user/detail")
    public Result<Map<String, Object>> getUserDetail(@RequestParam Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("user", user);

        // 资产信息
        AccountFund fund = assetService.getOrCreateFundAccount(userId);
        data.put("fund", fund);

        // 交易账户
        List<Map<String, Object>> trade = assetService.getTradeAccount(userId);
        data.put("trade", trade);

        return Result.success(data);
    }

    /**
     * 禁用/启用用户
     */
    @PostMapping("/user/status")
    public Result<Void> updateUserStatus(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        Integer status = (Integer) params.get("status");

        User user = userService.getById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);

        return Result.success(status == 1 ? "已启用" : "已禁用", null);
    }

    /**
     * 币种列表
     */
    @GetMapping("/coin/list")
    public Result<Map<String, Object>> getCoinList() {
        List<Coin> coins = coinService.list();
        Map<String, Object> data = new HashMap<>();
        data.put("list", coins);
        return Result.success(data);
    }

    /**
     * 新增/编辑币种
     */
    @PostMapping("/coin/save")
    public Result<Void> saveCoin(@RequestBody Coin coin) {
        if (coin.getCode() == null || coin.getCode().isEmpty()) {
            return Result.fail("币种代码不能为空");
        }
        if (coin.getName() == null || coin.getName().isEmpty()) {
            return Result.fail("币种名称不能为空");
        }

        coin.setCode(coin.getCode().toUpperCase());

        if (coin.getId() == null) {
            // 新增
            coin.setCreateTime(LocalDateTime.now());
            coinService.save(coin);
        } else {
            // 编辑
            coin.setUpdateTime(LocalDateTime.now());
            coinService.updateById(coin);
        }

        return Result.success("保存成功", null);
    }

    /**
     * 调整币种价格
     */
    @PostMapping("/coin/price")
    public Result<Void> updateCoinPrice(@RequestBody Map<String, Object> params) {
        String code = (String) params.get("code");
        BigDecimal price = new BigDecimal(params.get("price").toString());

        Coin coin = coinService.getCoinByCode(code);
        if (coin == null) {
            return Result.fail("币种不存在");
        }

        if (coin.getPriceType() == 1) {
            return Result.fail("实时币种价格不可手动修改");
        }

        coin.setPrice(price);
        coin.setUpdateTime(LocalDateTime.now());
        coinService.updateById(coin);

        return Result.success("价格已更新", null);
    }

    /**
     * 币种上架/下架
     */
    @PostMapping("/coin/status")
    public Result<Void> updateCoinStatus(@RequestBody Map<String, Object> params) {
        Long coinId = Long.valueOf(params.get("coinId").toString());
        Integer status = (Integer) params.get("status");

        Coin coin = coinService.getById(coinId);
        if (coin == null) {
            return Result.fail("币种不存在");
        }

        coin.setStatus(status);
        coin.setUpdateTime(LocalDateTime.now());
        coinService.updateById(coin);

        return Result.success(status == 1 ? "已上架" : "已下架", null);
    }

    /**
     * 价格计算器
     */
    @PostMapping("/coin/calculator")
    public Result<Map<String, Object>> calculatePrice(@RequestBody Map<String, Object> params) {
        BigDecimal currentPrice = new BigDecimal(params.get("currentPrice").toString());
        BigDecimal holdingAmount = new BigDecimal(params.getOrDefault("holdingAmount", "1000").toString());
        BigDecimal targetProfit = new BigDecimal(params.get("targetProfit").toString());

        // 计算目标价格
        // 持仓数量 = 持仓金额 / 当前价格
        BigDecimal quantity = holdingAmount.divide(currentPrice, 8, BigDecimal.ROUND_DOWN);
        // 单币盈亏 = 目标盈亏 / 持仓数量
        BigDecimal profitPerCoin = targetProfit.divide(quantity, 8, BigDecimal.ROUND_DOWN);
        // 目标价格 = 当前价格 + 单币盈亏
        BigDecimal targetPrice = currentPrice.add(profitPerCoin);

        Map<String, Object> result = new HashMap<>();
        result.put("targetPrice", targetPrice);
        result.put("quantity", quantity);
        result.put("profitPerCoin", profitPerCoin);

        return Result.success(result);
    }

    /**
     * 待审批订单
     */
    @GetMapping("/order/pending")
    public Result<Map<String, Object>> getPendingOrders(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {

        IPage<OrderFund> page = fundService.getPendingOrders(pageNum, pageSize);

        Map<String, Object> data = new HashMap<>();
        data.put("list", page.getRecords());
        data.put("total", page.getTotal());
        return Result.success(data);
    }

    /**
     * 所有充提订单
     */
    @GetMapping("/order/list")
    public Result<Map<String, Object>> getAllOrders(
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {

        IPage<OrderFund> page = fundService.getAllOrders(type, status, pageNum, pageSize);

        Map<String, Object> data = new HashMap<>();
        data.put("list", page.getRecords());
        data.put("total", page.getTotal());
        data.put("pageNum", page.getCurrent());
        data.put("pageSize", page.getSize());
        return Result.success(data);
    }

    /**
     * 审批订单
     */
    @PostMapping("/order/approve")
    public Result<Void> approveOrder(@RequestBody Map<String, Object> params) {
        String orderNo = (String) params.get("orderNo");
        Integer status = (Integer) params.get("status");
        String rejectReason = (String) params.get("rejectReason");
        String adminRemark = (String) params.get("adminRemark");

        if (orderNo == null || status == null) {
            return Result.fail("参数错误");
        }

        if (status != 2 && status != 3) {
            return Result.fail("状态参数错误");
        }

        try {
            fundService.approve(1L, "管理员", orderNo, status, rejectReason, adminRemark);
            return Result.success(status == 2 ? "审批通过" : "已驳回", null);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 资金总览
     */
    @GetMapping("/finance/overview")
    public Result<Map<String, Object>> getFinanceOverview() {
        Map<String, Object> data = new HashMap<>();

        // 累计充值
        BigDecimal totalDeposit = orderFundMapper.sumCompletedDeposit();
        data.put("totalDeposit", totalDeposit);

        // 累计提现
        BigDecimal totalWithdraw = orderFundMapper.sumCompletedWithdraw();
        data.put("totalWithdraw", totalWithdraw);

        // 在管资金
        BigDecimal fundBalance = accountFundMapper.sumAllBalance();
        data.put("fundBalance", fundBalance);

        // 交易账户总值
        BigDecimal tradeValue = accountFundMapper.sumAllTradeValue();
        data.put("tradeValue", tradeValue != null ? tradeValue : BigDecimal.ZERO);

        // 待审批数量
        int pendingCount = orderFundMapper.countPending();
        data.put("pendingCount", pendingCount);

        // 用户总数
        long userCount = userService.count();
        data.put("userCount", userCount);

        return Result.success(data);
    }
}
