package com.spot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spot.constant.SysConstant;
import com.spot.entity.AccountRecord;
import com.spot.enums.MessageCode;
import com.spot.mapper.AccountRecordMapper;
import com.spot.req.AccountRecordListReq;
import com.spot.resp.ApiResultVo;
import com.spot.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 资金流水查询控制器
 *
 * @author jean
 * @date 2026-05-06
 */
@Slf4j
@RestController
@RequestMapping("/v1")
public class AccountRecordController {

    @Autowired
    private AccountRecordMapper accountRecordMapper;

    /**
     * 分页查询资金流水（支持按 symbol/type/source/时间范围过滤）
     *
     * @param request HTTP请求
     * @param req     查询请求
     * @return 分页流水列表
     */
    @PostMapping("/account_records")
    @ResponseBody
    public ApiResultVo<Page<AccountRecord>> listAccountRecords(HttpServletRequest request,
                                                               @RequestBody AccountRecordListReq req) {
        String lang = RequestUtils.getLangFromHeader(request);
        try {
            Long uid = (Long) request.getAttribute(SysConstant.REQUEST_ATTR_MEMBER_ID);

            int page = req.getPage() != null ? req.getPage() : 1;
            int size = req.getSize() != null ? req.getSize() : 10;
            Page<AccountRecord> pg = new Page<>(page, size);

            // 1. 构建查询条件
            LambdaQueryWrapper<AccountRecord> qw = buildQuery(uid, req);

            // 2. 执行分页查询
            Page<AccountRecord> result = accountRecordMapper.selectPage(pg, qw);
            return ApiResultVo.success(lang, result);
        } catch (Exception e) {
            log.error("查询资金流水失败", e);
            return ApiResultVo.fail(lang, MessageCode.UNKNOWN_ERROR);
        }
    }

    /**
     * 构建流水查询条件
     */
    private LambdaQueryWrapper<AccountRecord> buildQuery(Long uid, AccountRecordListReq req) {
        LambdaQueryWrapper<AccountRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(AccountRecord::getUid, uid);

        if (req.getSymbol() != null && !req.getSymbol().isEmpty()) {
            qw.eq(AccountRecord::getSymbol, req.getSymbol());
        }
        if (req.getType() != null) {
            qw.eq(AccountRecord::getType, req.getType());
        }
        if (req.getSource() != null && !req.getSource().isEmpty()) {
            qw.eq(AccountRecord::getSource, req.getSource());
        }

        // 时间范围（秒级时间戳）
        if (req.getStartTime() != null) {
            LocalDateTime s = Instant.ofEpochMilli(req.getStartTime() * 1000L)
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();
            qw.ge(AccountRecord::getCtime, s);
        }
        if (req.getEndTime() != null) {
            LocalDateTime e = Instant.ofEpochMilli(req.getEndTime() * 1000L)
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();
            qw.le(AccountRecord::getCtime, e);
        }

        qw.orderByDesc(AccountRecord::getCtime).orderByDesc(AccountRecord::getId);
        return qw;
    }
}
