package com.bonus.canteen.core.android.service.impl;

import com.bonus.canteen.core.android.dto.AppDTO;
import com.bonus.canteen.core.android.mapper.UserMapper;
import com.bonus.canteen.core.android.service.UserService;
import com.bonus.canteen.core.android.vo.UserInfoVo;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.utils.SM4EncryptUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 19814
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper mapper;

    private static final int PHONE_LENGTH = 11;

    @Override
    public AjaxResult getUserInfo(AppDTO dto) {
        List<UserInfoVo> list = mapper.getUserInfo(dto);
        if (list.isEmpty()) {
            return AjaxResult.success(new ArrayList<>());
        }
        List<UserInfoVo> moneyList = mapper.getMoneyList();
        // 构建 userId 到 moneyVo 的映射，提升查找效率
        Map<String, UserInfoVo> moneyMap = moneyList.stream().collect(Collectors.toMap(UserInfoVo::getUserId, vo -> vo, (a, b) -> a));
        list.forEach(userInfoVo -> {
            if (userInfoVo.getPhone().length() > PHONE_LENGTH) {
                userInfoVo.setPhone(SM4EncryptUtils.sm4Decrypt(userInfoVo.getPhone()));
            }
            UserInfoVo money = moneyMap.get(userInfoVo.getUserId());
            if (money != null) {
                userInfoVo.setPersonalWalletBalance(money.getPersonalWalletBalance());
                userInfoVo.setSubsidiesBalance(money.getSubsidiesBalance());
            }
        });
        return AjaxResult.success(list);
    }

}
