package com.sqx.modules.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.PageUtils;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserInfo;
import com.sqx.modules.app.mapper.UserInfoMapper;
import com.sqx.modules.app.service.UserInfoService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【user_info】的数据库操作Service实现
 * @createDate 2025-01-02 14:15:08
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    private final UserDao userDao;

    public UserInfoServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }


    @Override
    public UserInfo getByUserIdOrSave(long userId) {
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId));
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(userId);
            save(userInfo);
        }
        return userInfo;
    }

    @Override
    public UserInfo getByUserId(long userId) {
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId));
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(userId);
        }
        return userInfo;
    }

    @Override
    public boolean isAuth(long userId) {
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId)
                .isNotNull(UserInfo::getCertName)
                .isNotNull(UserInfo::getCertNo)
        );
        if (userInfo != null) {
            return true;
        }
        return false;
    }

    @Override
    public List<UserInfo> getUsersByNameAndCertNo(String certName, String certNo) {
        List<UserInfo> userIds = baseMapper.selectList(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getCertName, certName)
                .eq(UserInfo::getCertNo, certNo)
                .select(UserInfo::getUserId)
        );
        return userIds;
    }

    @Override
    public Integer countCertCount(String name, String idNum) {
        return count(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getCertName, name)
                .eq(UserInfo::getCertNo, idNum)
                .isNotNull(UserInfo::getAccountNo)
                .isNotNull(UserInfo::getMobile)
        );
    }

    @Override
    public Integer countCertCount(String name, String idNum, String accountNo, String mobile) {
        return count(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getCertName, name)
                .eq(UserInfo::getCertNo, idNum)
                .eq(UserInfo::getAccountNo, accountNo)
                .eq(UserInfo::getMobile, mobile)
        );
    }

    /**
     * 获取用户认证标签
     * @param userId 用户id
     * @return 0-未认证，1-新用户，2-老用户
     */
    @Override
    public int getAuthUserTag(long userId) {
        UserInfo userInfo = getByUserId(userId);
        if (userInfo == null) {
            // 未认证
            return 0;
        }
        if(StrUtil.isEmpty(userInfo.getCertNo())){
            // 未认证
            return 0;
        }
        String certNo = userInfo.getCertNo();
        List<UserInfo> authUserlist = baseMapper.selectList(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getCertNo, certNo));
        // 同身份证号第一个认证用户
        UserInfo firstAuth = authUserlist.stream().sorted(Comparator.comparingLong(UserInfo::getId)).findFirst().get();
        if (firstAuth.getUserId() == userId) {
            // 新用户
            return 1;
        }
        // 老用户
        return 2;
    }

    @Override
    public Object getList(Integer page, Integer size, String phone, String name) {
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(phone)) {
            UserEntity userEntity = userDao.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhone, phone));
            lambdaQueryWrapper.eq(UserInfo::getUserId, userEntity == null ? -99999 : userEntity.getUserId());
        }

        if (StrUtil.isNotBlank(name)) {
            lambdaQueryWrapper.like(UserInfo::getCertName, name);
        }
        PageHelper.startPage(page, size);
        List<UserInfo> userInfoList = list(lambdaQueryWrapper);
        PageInfo<UserInfo> userInfoPageInfo = new PageInfo<>(userInfoList);

        Set<Long> userIdList = userInfoList.stream().map(UserInfo::getUserId).collect(Collectors.toSet());
        Map<Long, UserEntity> userMap = userIdList.isEmpty() ? new HashMap<>() : userDao.selectList(new LambdaQueryWrapper<UserEntity>().in(UserEntity::getUserId, userIdList))
                .stream().collect(Collectors.toMap(UserEntity::getUserId, item -> item));

        userInfoList.forEach(item -> {
            UserEntity userEntity = userMap.get(item.getUserId());
            if (userEntity == null) return;
            item.setName(userEntity.getUserName());
            item.setPhone(userEntity.getPhone());
        });
        return PageUtils.page(userInfoPageInfo);
    }
}




