package com.ruoyi.fadapp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fadapp.domain.vo.FadAppUserVo;
import com.ruoyi.fadapp.service.IFadAppUserService;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * FAD APP用户管理Service业务层处理
 *
 * @author ruoyi
 */
@RequiredArgsConstructor
@Service
public class FadAppUserServiceImpl implements IFadAppUserService {

    private final SysUserMapper userMapper;

    /**
     * 查询用户列表
     */
    @Override
    public TableDataInfo<FadAppUserVo> queryUserList(FadAppUserVo bo, PageQuery pageQuery) {
        QueryWrapper<SysUser> lqw = buildQueryWrapper(bo);
        Page<SysUser> result = userMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(BeanUtil.copyToList(result.getRecords(), FadAppUserVo.class));
    }

    /**
     * 获取用户详细信息
     */
    @Override
    public FadAppUserVo getUserInfo(Long userId) {
        SysUser user = userMapper.selectById(userId);
        return BeanUtil.toBean(user, FadAppUserVo.class);
    }

    /**
     * 根据手机号获取用户信息
     */
    @Override
    public SysUser getUserByPhone(String phone) {
        return userMapper.selectUserByPhonenumber(phone);
    }

    /**
     * 获取用户统计信息
     */
    @Override
    public Object getUserStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalUsers", userMapper.selectCount(null));
        stats.put("activeUsers", userMapper.selectCount(
            Wrappers.<SysUser>lambdaQuery().eq(SysUser::getStatus, "0")
        ));
        return stats;
    }

    private QueryWrapper<SysUser> buildQueryWrapper(FadAppUserVo bo) {
        QueryWrapper<SysUser> lqw = Wrappers.query();
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), "user_name", bo.getUserName());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), "nick_name", bo.getNickName());
        lqw.like(StringUtils.isNotBlank(bo.getPhonenumber()), "phonenumber", bo.getPhonenumber());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), "status", bo.getStatus());
        lqw.eq(bo.getDeptId() != null, "dept_id", bo.getDeptId());
        return lqw;
    }
} 