package com.ruoyi.system.user.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.dashboard.constants.StatKeys;
import com.ruoyi.system.user.domain.UserQuery;
import com.ruoyi.system.user.domain.vo.UserAgentStatVO;
import com.ruoyi.system.user.domain.vo.UserStatVO;
import com.ruoyi.system.user.mapper.UserMapper;
import com.ruoyi.system.user.service.UserDashboard;

@Service
public class UserDashboardImpl implements UserDashboard {

    @Autowired
    private UserMapper userMapper;

    @Override
    public BigDecimal selectMaxOfPoint(UserQuery query) {
        return userMapper.selectMaxOfPoint(query);
    }

    @Override
    public UserStatVO selectStat(UserQuery query, List<String> keys) {
        UserStatVO vo = new UserStatVO();
        if (keys.contains(StatKeys.USER_BALANCE)) {
            vo.setBalance(userMapper.selectSumOfBalance(query));
        }
        return vo;
    }

    @Override
    public UserAgentStatVO selectAgentStat(UserQuery query, List<String> keys) {
        UserAgentStatVO vo = new UserAgentStatVO();
        if (keys.contains(StatKeys.USER_COUNT)) {
            vo.setCount(this.selectNormalCount(query));
        }
        if (keys.contains(StatKeys.USER_MCH_COUNT)) {
            vo.setMchCount(this.selectMchCount(query));
        }
        if (keys.contains(StatKeys.USER_AGENT_COUNT)) {
            vo.setAgentCount(this.selectAgentCount(query));
        }
        return vo;
    }

    @Override
    public Integer selectMchCount(UserQuery query) {
        UserQuery mchQuery = new UserQuery();
        BeanUtils.copyProperties(query, mchQuery);
        mchQuery.setRoleKey(RoleConstants.MCH);
        return this.selectCount(mchQuery);
    }

    private Integer selectAgentCount(UserQuery query) {
        UserQuery agentQuery = new UserQuery();
        BeanUtils.copyProperties(query, agentQuery);
        agentQuery.setRoleKey(RoleConstants.AGENT);
        return this.selectCount(agentQuery);
    }

    // 获取普通用户的数量
    private Integer selectNormalCount(UserQuery query) {
        UserQuery normalQuery = new UserQuery();
        BeanUtils.copyProperties(query, normalQuery);
        normalQuery.setUserType(UserType.USER.getCode());
        return this.selectCount(normalQuery);
    }

    @Override
    public BigDecimal selectSumOfBalance(UserQuery query) {
        return MathUtils.dv(userMapper.selectSumOfBalance(query));
    }

    @Override
    public Integer selectCount(UserQuery query) {
        return MathUtils.dv(userMapper.selectCount(query));
    }
}