package com.yingpai.miniapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yingpai.miniapp.domain.PaymentOrder;
import com.yingpai.miniapp.domain.bo.PaymentOrderBo;
import com.yingpai.miniapp.domain.vo.PaymentOrderVo;
import com.yingpai.miniapp.mapper.MiniappUserMapper;
import com.yingpai.miniapp.mapper.PaymentOrderMapper;
import com.yingpai.miniapp.service.IPaymentOrderService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 支付订单Service实现
 */
@Service
@RequiredArgsConstructor
public class PaymentOrderServiceImpl implements IPaymentOrderService {
    
    private final PaymentOrderMapper orderMapper;
    private final MiniappUserMapper userMapper;
    
    @Override
    public TableDataInfo<PaymentOrderVo> queryPageList(PaymentOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PaymentOrder> wrapper = buildQueryWrapper(bo);
        Page<PaymentOrder> page = orderMapper.selectPage(pageQuery.build(), wrapper);
        
        List<PaymentOrderVo> voList = page.getRecords().stream()
                .map(this::toVo)
                .collect(Collectors.toList());
        
        Page<PaymentOrderVo> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(voList);
        return TableDataInfo.build(voPage);
    }
    
    @Override
    public List<PaymentOrderVo> queryList(PaymentOrderBo bo) {
        LambdaQueryWrapper<PaymentOrder> wrapper = buildQueryWrapper(bo);
        return orderMapper.selectList(wrapper).stream()
                .map(this::toVo)
                .collect(Collectors.toList());
    }
    
    @Override
    public PaymentOrderVo queryById(Long id) {
        PaymentOrder order = orderMapper.selectById(id);
        return order != null ? toVo(order) : null;
    }
    
    @Override
    public Boolean deleteById(Long id) {
        return orderMapper.deleteById(id) > 0;
    }
    
    private LambdaQueryWrapper<PaymentOrder> buildQueryWrapper(PaymentOrderBo bo) {
        LambdaQueryWrapper<PaymentOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(bo.getOrderNo()), PaymentOrder::getOrderNo, bo.getOrderNo());
        wrapper.eq(bo.getUserId() != null, PaymentOrder::getUserId, bo.getUserId());
        wrapper.eq(bo.getPoolType() != null, PaymentOrder::getPoolType, bo.getPoolType());
        wrapper.eq(bo.getOrderStatus() != null, PaymentOrder::getOrderStatus, bo.getOrderStatus());
        wrapper.orderByDesc(PaymentOrder::getCreateTime);
        
        // 如果有昵称或手机号查询，需要先查用户ID
        if (StringUtils.isNotBlank(bo.getNickname()) || StringUtils.isNotBlank(bo.getPhone())) {
            List<Long> userIds = userMapper.selectList(new LambdaQueryWrapper<com.yingpai.miniapp.domain.MiniappUser>()
                    .like(StringUtils.isNotBlank(bo.getNickname()), com.yingpai.miniapp.domain.MiniappUser::getNickname, bo.getNickname())
                    .like(StringUtils.isNotBlank(bo.getPhone()), com.yingpai.miniapp.domain.MiniappUser::getPhone, bo.getPhone()))
                    .stream()
                    .map(com.yingpai.miniapp.domain.MiniappUser::getId)
                    .collect(Collectors.toList());
            if (userIds.isEmpty()) {
                wrapper.eq(PaymentOrder::getUserId, -1L); // 无匹配用户
            } else {
                wrapper.in(PaymentOrder::getUserId, userIds);
            }
        }
        
        return wrapper;
    }
    
    private PaymentOrderVo toVo(PaymentOrder order) {
        PaymentOrderVo vo = new PaymentOrderVo();
        vo.setId(order.getId());
        vo.setOrderNo(order.getOrderNo());
        vo.setUserId(order.getUserId());
        vo.setPoolType(order.getPoolType());
        vo.setPoolTypeName(order.getPoolType() == 1 ? "超短池" : "强势池");
        vo.setAmount(order.getAmount());
        vo.setOrderStatus(order.getOrderStatus());
        vo.setOrderStatusName(getStatusName(order.getOrderStatus()));
        vo.setTransactionId(order.getTransactionId());
        vo.setPayTime(order.getPayTime());
        vo.setCreateTime(order.getCreateTime());
        
        // 查询用户信息
        var user = userMapper.selectById(order.getUserId());
        if (user != null) {
            vo.setNickname(user.getNickname());
            vo.setPhone(user.getPhone());
        }
        
        return vo;
    }
    
    private String getStatusName(Integer status) {
        return switch (status) {
            case 0 -> "待支付";
            case 1 -> "已支付";
            case 2 -> "已取消";
            default -> "已关闭";
        };
    }
}
