package com.haha.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.entity.User;
import com.haha.mapper.UserMapper;
import com.haha.service.UserService;
import com.haha.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AccountService accountService;

    @Override
    public User getUserByOpenId(String openId) {
        return lambdaQuery().eq(User::getOpenid, openId).one();
    }

    @Override
    public User getUserByPhone(String phone) {
        return lambdaQuery().eq(User::getPhone, phone).one();
    }

    @Override
    public boolean updateCreditScore(Long userId, Integer score) {
        return lambdaUpdate().eq(User::getId, userId).set(User::getCreditScore, score).update();
    }

    @Override
    public boolean updateBalance(Long userId, BigDecimal amount) {
        return accountService.updateBalance(userId, amount);
    }

    @Override
    public IPage<User> getPage(int page, int pageSize, Map<String, Object> params) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        // 昵称或手机号搜索
        String keyword = (String) params.get("keyword");
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w
                .like(User::getNickname, keyword)
                .or()
                .like(User::getPhone, keyword)
            );
        }
        
        // 状态筛选
        Object statusObj = params.get("status");
        if (statusObj != null && !statusObj.toString().isEmpty()) {
            wrapper.eq(User::getStatus, Integer.valueOf(statusObj.toString()));
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc(User::getCreateTime);
        
        Page<User> pageResult = new Page<>(page, pageSize);
        return page(pageResult, wrapper);
    }

    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总客户数
        long total = count();
        stats.put("total", total);
        
        // 正常用户数
        long active = lambdaQuery().eq(User::getStatus, 1).count();
        stats.put("active", active);
        
        // 禁用用户数
        long disabled = lambdaQuery().eq(User::getStatus, 0).count();
        stats.put("disabled", disabled);
        
        // 新增用户数（今日）
        // TODO: 添加今日新增统计
        stats.put("todayNew", 0);
        
        return stats;
    }
}
