package com.spot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spot.entity.ExTrade;
import com.spot.mapper.ExTradeMapper;
import com.spot.req.AdminTradeQueryReq;
import com.spot.service.ExTradeService;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class ExTradeServiceImpl extends ServiceImpl<ExTradeMapper, ExTrade> implements ExTradeService {

    @Override
    public Page<ExTrade> adminPageQuery(AdminTradeQueryReq req) {
        Page<ExTrade> pg = new Page<>(req.getPage() != null ? req.getPage() : 1,
                req.getSize() != null ? req.getSize() : 15);
        LambdaQueryWrapper<ExTrade> qw = new LambdaQueryWrapper<>();
        if (req.getId() != null) {
            qw.eq(ExTrade::getId, req.getId());
        }
        if (req.getOrderId() != null) {
            qw.and(w -> w.eq(ExTrade::getBidId, req.getOrderId())
                    .or().eq(ExTrade::getAskId, req.getOrderId()));
        }
        if (req.getSymbol() != null && !req.getSymbol().isEmpty()) {
            qw.eq(ExTrade::getSymbol, req.getSymbol());
        }
        if (req.getSide() != null && !req.getSide().isEmpty()) {
            qw.eq(ExTrade::getTrendSide, req.getSide());
        }
        if (req.getUserId() != null && req.getRole() != null && !req.getRole().isEmpty()) {
            if ("TAKER".equalsIgnoreCase(req.getRole())) {
                qw.and(w -> w.eq(ExTrade::getTrendSide, "BUY")
                        .eq(ExTrade::getBidUserId, req.getUserId())
                        .or()
                        .eq(ExTrade::getTrendSide, "SELL")
                        .eq(ExTrade::getAskUserId, req.getUserId()));
            } else if ("MAKER".equalsIgnoreCase(req.getRole())) {
                qw.and(w -> w.eq(ExTrade::getTrendSide, "BUY")
                        .eq(ExTrade::getAskUserId, req.getUserId())
                        .or()
                        .eq(ExTrade::getTrendSide, "SELL")
                        .eq(ExTrade::getBidUserId, req.getUserId()));
            }
        } else if (req.getUserId() != null) {
            qw.and(w -> w.eq(ExTrade::getBidUserId, req.getUserId())
                    .or().eq(ExTrade::getAskUserId, req.getUserId()));
        }
        if (req.getCtimeBegin() != null) {
            qw.ge(ExTrade::getCtime, LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(req.getCtimeBegin()), ZoneId.systemDefault()));
        }
        if (req.getCtimeEnd() != null) {
            qw.le(ExTrade::getCtime, LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(req.getCtimeEnd()), ZoneId.systemDefault()));
        }
        qw.orderByDesc(ExTrade::getCtime);
        return this.page(pg, qw);
    }
}
