package com.greenorange.promotion.controller.userInfo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.greenorange.promotion.annotation.RequiresPermission;
import com.greenorange.promotion.annotation.SysLog;
import com.greenorange.promotion.common.BaseResponse;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.common.ResultUtils;
import com.greenorange.promotion.constant.UserConstant;
import com.greenorange.promotion.exception.ThrowUtils;
import com.greenorange.promotion.model.dto.CommonBatchRequest;
import com.greenorange.promotion.model.dto.userMainInfo.UserMainInfoAddRequest;
import com.greenorange.promotion.model.dto.userMainInfo.UserMainInfoUpdateRequest;
import com.greenorange.promotion.model.entity.UserInfo;
import com.greenorange.promotion.model.entity.UserMainInfo;
import com.greenorange.promotion.model.vo.userMainInfo.UserMainInfoVO;
import com.greenorange.promotion.model.vo.userMainInfo.UserMemberInfoVO;
import com.greenorange.promotion.model.vo.userMainInfo.UserTeamInfoVO;
import com.greenorange.promotion.service.common.CommonService;
import com.greenorange.promotion.service.userInfo.UserInfoService;
import com.greenorange.promotion.service.userInfo.UserMainInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.greenorange.promotion.model.dto.CommonRequest;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户主要信息 控制器
 */
@RestController
@RequestMapping("userMainInfo")
@Slf4j
@Tag(name = "用户主要信息管理")
@Transactional
public class UserMainInfoController {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserMainInfoService userMainInfoService;

    @Resource
    private CommonService commonService;


    /**
     * 小程序用户查询团队信息
     * @return 团队信息
     */
    @PostMapping("query/team")
    @Operation(summary = "小程序用户查询团队信息", description = "参数：用户主要信息添加请求体，权限：管理员，方法名：queryUserTeamInfo")
    @RequiresPermission(mustRole = UserConstant.DEFAULT_ROLE)
//    @SysLog(title = "用户主要信息管理", content = "小程序用户查询团队信息")
    public BaseResponse<UserTeamInfoVO> queryUserTeamInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getParentUserId, userId);
        List<UserInfo> userInfoList = userInfoService.list(userInfoLambdaQueryWrapper);
        List<UserMainInfo> userMainInfoList = commonService.findByFieldInTargetField(userInfoList, userMainInfoService, UserInfo::getId, UserMainInfo::getUserId);
        // 封装Map集合（键：用户id，值：用户信息）
        Map<Long, UserInfo> userInfoMap = new HashMap<>();
        for (UserInfo userInfo : userInfoList) {
            userInfoMap.put(userInfo.getId(), userInfo);
        }
        // 封装Map集合（键：用户id，值：用户主要信息）
        Map<Long, UserMainInfo> userMainInfoMap = new HashMap<>();
        for (UserMainInfo userMainInfo : userMainInfoList) {
            userMainInfoMap.put(userMainInfo.getUserId(), userMainInfo);
        }
        List<UserMemberInfoVO> userMemberInfoVOList = new ArrayList<>();
        BigDecimal totalEarnings = BigDecimal.ZERO;
        for (UserInfo userInfo : userInfoList) {
            Long id = userInfo.getId();
            UserInfo userInformation = userInfoMap.get(id);
            UserMainInfo userMainInfo = userMainInfoMap.get(id);
            UserMemberInfoVO userMemberInfoVO = UserMemberInfoVO.builder()
                    .subUserId(id)
                    .nickName(userInformation.getNickName())
                    .phoneNumber(userInformation.getPhoneNumber())
                    .teamSize(userMainInfo.getTeamSize())
                    .parentEarnings(userMainInfo.getParentEarnings())
                    .registerTime(userInformation.getCreateTime())
                    .build();
            userMemberInfoVOList.add(userMemberInfoVO);
            totalEarnings = totalEarnings.add(userMainInfo.getParentEarnings());
        }
        UserInfo userInfo = userInfoService.getById(userId);
        UserTeamInfoVO userTeamInfoVO = commonService.copyProperties(userInfo, UserTeamInfoVO.class);
        userTeamInfoVO.setDirectAgentSize(userInfoList.size());
        userTeamInfoVO.setTeamEarnings(totalEarnings);

        LambdaQueryWrapper<UserMainInfo> userMainInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userMainInfoLambdaQueryWrapper.eq(UserMainInfo::getUserId, userId);
        UserMainInfo userMainInfo = userMainInfoService.getOne(userMainInfoLambdaQueryWrapper);
        userTeamInfoVO.setTeamSize(userMainInfo.getTeamSize());
        userTeamInfoVO.setInviteQrCode(userMainInfo.getInviteQrCode());
        userTeamInfoVO.setUserMemberInfoVOList(userMemberInfoVOList);

        return ResultUtils.success(userTeamInfoVO);
    }

}