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.UserSubscription;
import com.yingpai.miniapp.domain.bo.UserSubscriptionBo;
import com.yingpai.miniapp.domain.vo.UserSubscriptionVo;
import com.yingpai.miniapp.mapper.MiniappUserMapper;
import com.yingpai.miniapp.mapper.UserSubscriptionMapper;
import com.yingpai.miniapp.service.IUserSubscriptionService;
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 UserSubscriptionServiceImpl implements IUserSubscriptionService {
    
    private final UserSubscriptionMapper subscriptionMapper;
    private final MiniappUserMapper userMapper;
    
    @Override
    public TableDataInfo<UserSubscriptionVo> queryPageList(UserSubscriptionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserSubscription> wrapper = buildQueryWrapper(bo);
        Page<UserSubscription> page = subscriptionMapper.selectPage(pageQuery.build(), wrapper);
        
        List<UserSubscriptionVo> voList = page.getRecords().stream()
                .map(this::toVo)
                .collect(Collectors.toList());
        
        Page<UserSubscriptionVo> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(voList);
        return TableDataInfo.build(voPage);
    }
    
    @Override
    public List<UserSubscriptionVo> queryList(UserSubscriptionBo bo) {
        LambdaQueryWrapper<UserSubscription> wrapper = buildQueryWrapper(bo);
        return subscriptionMapper.selectList(wrapper).stream()
                .map(this::toVo)
                .collect(Collectors.toList());
    }
    
    @Override
    public UserSubscriptionVo queryById(Long id) {
        UserSubscription subscription = subscriptionMapper.selectById(id);
        return subscription != null ? toVo(subscription) : null;
    }
    
    @Override
    public Boolean deleteById(Long id) {
        return subscriptionMapper.deleteById(id) > 0;
    }
    
    @Override
    public Boolean updateStatus(Long id, Integer status) {
        UserSubscription subscription = new UserSubscription();
        subscription.setId(id);
        subscription.setStatus(status);
        return subscriptionMapper.updateById(subscription) > 0;
    }
    
    private LambdaQueryWrapper<UserSubscription> buildQueryWrapper(UserSubscriptionBo bo) {
        LambdaQueryWrapper<UserSubscription> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(bo.getUserId() != null, UserSubscription::getUserId, bo.getUserId());
        wrapper.eq(bo.getPoolType() != null, UserSubscription::getPoolType, bo.getPoolType());
        wrapper.eq(bo.getStatus() != null, UserSubscription::getStatus, bo.getStatus());
        wrapper.orderByDesc(UserSubscription::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(UserSubscription::getUserId, -1L); // 无匹配用户
            } else {
                wrapper.in(UserSubscription::getUserId, userIds);
            }
        }
        
        return wrapper;
    }
    
    private UserSubscriptionVo toVo(UserSubscription subscription) {
        UserSubscriptionVo vo = new UserSubscriptionVo();
        vo.setId(subscription.getId());
        vo.setUserId(subscription.getUserId());
        vo.setPoolType(subscription.getPoolType());
        vo.setPoolTypeName(subscription.getPoolType() == 1 ? "超短池" : "强势池");
        vo.setOrderNo(subscription.getOrderNo());
        vo.setAmount(subscription.getAmount());
        vo.setStartTime(subscription.getStartTime());
        vo.setExpireTime(subscription.getExpireTime());
        vo.setStatus(subscription.getStatus());
        vo.setStatusName(subscription.getStatus() == 1 ? "生效中" : "已过期");
        vo.setCreateTime(subscription.getCreateTime());
        
        // 查询用户信息
        var user = userMapper.selectById(subscription.getUserId());
        if (user != null) {
            vo.setNickname(user.getNickname());
            vo.setPhone(user.getPhone());
        }
        
        return vo;
    }
}
