
package com.tmerclub.cloud.user.feign;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.api.user.bo.UidAndUserIdBO;
import com.tmerclub.cloud.api.user.dto.CustomerReqDTO;
import com.tmerclub.cloud.api.user.dto.MemberReqDTO;
import com.tmerclub.cloud.api.user.dto.UserRegisterDTO;
import com.tmerclub.cloud.api.user.feign.UserFeignClient;
import com.tmerclub.cloud.api.user.vo.*;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.user.dto.UserManagerDTO;
import com.tmerclub.cloud.user.mapper.UserExtensionMapper;
import com.tmerclub.cloud.user.mapper.UserMapper;
import com.tmerclub.cloud.user.model.User;
import com.tmerclub.cloud.user.service.UserBalanceLogService;
import com.tmerclub.cloud.user.service.UserRechargeCouponService;
import com.tmerclub.cloud.user.service.UserRightsService;
import com.tmerclub.cloud.user.service.UserService;
import com.tmerclub.cloud.user.vo.UserExtensionVO;
import com.tmerclub.cloud.user.vo.UserVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

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

/**
 * 用户地址feign连接
 *
 * @author tmerclub
 * @date 2020/12/07
 */
@DubboService
public class UserFeignController implements UserFeignClient {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserExtensionMapper userExtensionMapper;
    @Autowired
    private UserBalanceLogService userBalanceLogService;
    @Autowired
    private UserRightsService userRightsService;
    @Autowired
    private UserRechargeCouponService userRechargeCouponService;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;

    @Override
    public ServerResponseEntity<List<UserApiVO>> getUserByUserIds(List<Long> userIds) {
        List<UserApiVO> userList = userService.getUserByUserIds(userIds);
        return ServerResponseEntity.success(userList);
    }

    @Override
    public ServerResponseEntity<List<UserApiVO>> getUserByParam(UserApiVO userApiVO) {
        return ServerResponseEntity.success(userService.getUserByParam(userApiVO));
    }

    @Override
    public ServerResponseEntity<UserApiVO> getUserData(Long userId) {
        UserApiVO user = userService.getByUserId(userId);
        return ServerResponseEntity.success(user);
    }

    @Override
    public ServerResponseEntity<UserApiVO> getInsiderUserData(Long userId) {
        UserApiVO user = userService.getByUserId(userId);
        return ServerResponseEntity.success(user);
    }

    @Override
    public ServerResponseEntity<List<Long>> getMeetConditionsUserIds(MemberReqDTO param) {
        if (CollectionUtil.isEmpty(param.getUserIds())) {
            return ServerResponseEntity.success(null);
        }
        // 根据用户id，获取用户的信息
        List<Long> userIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<UserExtensionVO> userExtensionList = userExtensionMapper.countByMemberTypeConditions(param);
        // 根据用户等级进行分类
        Map<Integer, List<UserExtensionVO>> userInfoMap = userExtensionList.stream().collect(Collectors.groupingBy(UserExtensionVO::getLevelType));
        // 查找指定等级的用户时，过滤多余的数据
        if (!Objects.equals(param.getMemberType(), 0) && userInfoMap.containsKey(param.getMemberType() - 1)) {
            userExtensionList = userInfoMap.get(param.getMemberType() - 1);
        } else if (param.getMemberType() != 0) {
            //查询类型不为全部全员,上面过滤不执行则清空全部
            userExtensionList = null;
        }

        if (Objects.nonNull(userExtensionList) && CollUtil.isNotEmpty(userExtensionList)) {
            userExtensionList.forEach(userExtensionVO -> userIds.add(userExtensionVO.getUserId()));
        }
        return ServerResponseEntity.success(userIds);
    }

    @Override
    public ServerResponseEntity<MemberContributeRespVO> getMemberContributeByParam(MemberReqDTO param) {
        Date endTime = param.getEndTime();
        param.setDateTime(endTime);
        // 先获取当前符合条件的所有会员数(只是查询一天的应该数据量不会很大？)
        List<UserExtensionVO> userExtensionList = userExtensionMapper.countByMemberTypeConditions(param);
        List<Long> userIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        Map<Integer, List<UserExtensionVO>> userInfoMap = userExtensionList.stream().collect(Collectors.groupingBy(UserExtensionVO::getLevelType));

        MemberContributeRespVO respParam = new MemberContributeRespVO();
        // 普通会员
        MemberContributeValueVO publicMember = new MemberContributeValueVO();
        // 付费会员
        MemberContributeValueVO paidMember = new MemberContributeValueVO();

        // 普通会员
        param.setMemberType(1);
        publicMember.setTotalMember(userExtensionMapper.countMemberByParam(param));
        // 普通会员ids
        List<UserExtensionVO> memberList = userInfoMap.get(0);
        for (UserExtensionVO extensionVO : memberList) {
            userIds.add(extensionVO.getUserId());
        }
        respParam.setUserIds(userIds);
        // 付费会员
        param.setMemberType(2);
        param.setDateTime(endTime);
        paidMember.setTotalMember(userExtensionMapper.countMemberByParam(param));
        respParam.setPublicMember(publicMember);
        respParam.setPaidMember(paidMember);
        // 付费会员ids
        userIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        memberList = userInfoMap.get(1);
        if (Objects.nonNull(memberList) && memberList.size() > 0) {
            for (UserExtensionVO userExtensionVO : memberList) {
                userIds.add(userExtensionVO.getUserId());
            }
        }
        respParam.setPaidUserIds(userIds);
        return ServerResponseEntity.success(respParam);
    }

    @Override
    public ServerResponseEntity<Integer> getMemberTrend(MemberReqDTO param) {
        return ServerResponseEntity.success(userExtensionMapper.countMemberByParam(param));
    }

    @Override
    public ServerResponseEntity<List<UserApiVO>> countUserByMobile(String mobile) {
        return ServerResponseEntity.success(userService.listUserByMobile(mobile));
    }

    @Override
    public ServerResponseEntity<Void> cancelBindingCoupons(List<Long> couponIds) {
        if (CollUtil.isNotEmpty(couponIds)) {
            userRechargeCouponService.cancelBindingCoupons(couponIds);
            userRightsService.cancelBindingCoupons(couponIds);
        }
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<UserApiVO> getUserAndOpenIdsByUserId(Long userId) {
        return ServerResponseEntity.success(userService.getUserAndOpenIdsByUserId(userId));
    }

    @Override
    public ServerResponseEntity<UidAndUserIdBO> save(UserRegisterDTO userRegisterDTO) {
        return ServerResponseEntity.success(userService.save(userRegisterDTO.getMobile(), null, userRegisterDTO.getTempUid()));
    }

    @Override
    public ServerResponseEntity<Integer> countNewUserByTime(CustomerReqDTO customerReqDTO) {
        return ServerResponseEntity.success(userService.countNewUserByTime(customerReqDTO.getStartTime(), customerReqDTO.getEndTime()));
    }


    @Override
    public List<Long> listNewUserIdByTime(CustomerReqDTO customerReqDTO) {
        return userService.listNewUserIdByTime(customerReqDTO.getStartTime(), customerReqDTO.getEndTime());
    }

    @Override
    public List<UserApiVO> listUserByUserIds(List<Long> userIds) {
        List<UserVO> userList = userService.listUserByUserIds(userIds);
        return BeanUtil.mapAsList(userList, UserApiVO.class);
    }
    @Override
    public ServerResponseEntity<Void> createAllinpayMember() {
        // 查询未注销的所有会员信息
        UserManagerDTO userManagerDTO = new UserManagerDTO();
        List<User> users = userService.listUser(userManagerDTO);
        if (CollectionUtils.isEmpty(users)) {
            return ServerResponseEntity.success();
        }
        // userId转成bizUserId，并调用通联接口创建会员
        List<String> bizUserIds = new ArrayList<>(users.size());
        for (User user : users) {
            bizUserIds.add(user.getUserId().toString());
        }
        allinpayFeignClient.batchCreatePersonalMember(bizUserIds);
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<MemberTrendRespVO> countUserNumByType(CustomerReqDTO customerReqDTO) {
        MemberTrendRespVO memberTrendRespVO = userMapper.countUserNumByType(customerReqDTO.getStartTime());
        return ServerResponseEntity.success(memberTrendRespVO);
    }

    @Override
    public MemberCountVO statisticsUserNum(MemberReqDTO memberReqDTO) {
        return userMapper.statisticsUserNum(memberReqDTO.getStartTime(), memberReqDTO.getEndTime());
    }

    @Override
    public ServerResponseEntity<Date> getInitialRegistrationTime() {
        Date beginTime = userMapper.getInitialRegistrationTime();
        return ServerResponseEntity.success(beginTime);
    }
}
