package com.gic.haoban.manage.web.controller.chat;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.constants.StatisticsApolloKeyConstant;
import com.gic.haoban.manage.api.dto.chat.GroupChatActivityInviteLogDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatActivityRewardDetailLogDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatActivityRewardLogDTO;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivityInviteLogQDTO;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivityRewardLogQDTO;
import com.gic.haoban.manage.api.service.chat.GroupChatActivityLogApiService;
import com.gic.haoban.manage.web.handle.GroupChatActivityInviterHandle;
import com.gic.haoban.manage.web.handle.GroupChatActivityJoinHandle;
import com.gic.haoban.manage.web.handle.GroupChatActivityRewardHandle;
import com.gic.haoban.manage.web.qo.chat.GroupChatActivityDataInviterDetailReq;
import com.gic.haoban.manage.web.qo.chat.GroupChatActivityDataOverviewReq;
import com.gic.haoban.manage.web.qo.chat.GroupChatActivityDataRewardLevelReq;
import com.gic.haoban.manage.web.qo.chat.GroupChatActivityJoinDataReq;
import com.gic.haoban.manage.web.vo.chat.*;
import com.gic.member.api.constant.RewardResultTypeEnum;
import com.gic.member.api.dto.MemberDTO;
import com.gic.member.api.dto.MemberDocDTO;
import com.gic.member.api.service.MemberService;
import com.gic.web.common.utils.DataApiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 社群邀请有礼数据
 *
 * @author shangfeng
 * @date 2024-10-10 15:56:56
 */
@RestController
@RequestMapping("/group-chat-activity-data")
public class GroupChatActivityDataController {

    @Resource
    private GroupChatActivityLogApiService groupChatActivityLogApiService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private MemberService memberService;

    @Resource
    private GroupChatActivityJoinHandle groupChatActivityJoinHandle;

    @Resource
    private GroupChatActivityInviterHandle groupChatActivityInviterHandle;

    @Resource
    private GroupChatActivityRewardHandle groupChatActivityRewardHandle;

    /**
     * 列表统计数据
     *
     * @param joinDataReq
     * @return
     */
    @RequestMapping("get-join-data-list")
    @ResponseBody
    public RestResponse<List<GroupChatActivityJoinDataVO>> getJoinDataList(@RequestBody GroupChatActivityJoinDataReq joinDataReq) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();

        GroupChatActivityDataOverviewReq overviewReq = new GroupChatActivityDataOverviewReq();
        overviewReq.setEnterpriseId(user.getEnterpriseId());
        overviewReq.setChatActivityId(StringUtils.join(joinDataReq.getChatActivityIdList(), ","));

        Map<String, Object> res = DataApiUtils.http(JSON.toJSONString(overviewReq), StatisticsApolloKeyConstant.data_mkt_group_chat_data_overview);
        Map<String, GroupChatDataOverviewVO> map = Maps.newHashMap();
        List<GroupChatDataOverviewVO> list = DataApiUtils.parsePageDataList(res, GroupChatDataOverviewVO.class);

        if (CollectionUtils.isNotEmpty(list)) {
            map = list.stream().collect(Collectors.toMap(GroupChatDataOverviewVO::getChatActivityId, groupChatDataOverviewVO -> groupChatDataOverviewVO));
        }
        Map<String, GroupChatDataOverviewVO> finalMap = map;
        List<GroupChatActivityJoinDataVO> joinDataVOList = joinDataReq.getChatActivityIdList().stream().map(chatActivityId -> {
            GroupChatActivityJoinDataVO groupChatActivityJoinDataVO = new GroupChatActivityJoinDataVO();
            groupChatActivityJoinDataVO.setChatActivityId(chatActivityId);
            GroupChatDataOverviewVO groupChatDataOverviewVO = finalMap.get(chatActivityId.toString());
            if(Objects.nonNull(groupChatDataOverviewVO)){
                if(StringUtils.isNotEmpty(groupChatDataOverviewVO.getInviterNum())){
                    groupChatActivityJoinDataVO.setInviterNum(Integer.parseInt(groupChatDataOverviewVO.getInviterNum()));
                }
                if(StringUtils.isNotEmpty(groupChatDataOverviewVO.getInviteeNum())){
                    groupChatActivityJoinDataVO.setInviteeNum(Integer.parseInt(groupChatDataOverviewVO.getInviteeNum()));
                }
                if(StringUtils.isNotEmpty(groupChatDataOverviewVO.getEffectiveInviteeNum())){
                    groupChatActivityJoinDataVO.setEffectiveInviteeNum(Integer.parseInt(groupChatDataOverviewVO.getEffectiveInviteeNum()));
                }
            }
            return groupChatActivityJoinDataVO;
        }).collect(Collectors.toList());

        return RestResponse.successResult(joinDataVOList);
    }


    /**
     * 数据概览
     *
     * @param overviewReq
     * @return
     */
    @RequestMapping("overview")
    @ResponseBody
    public RestResponse<GroupChatDataOverviewVO> overview(@RequestBody GroupChatActivityDataOverviewReq overviewReq) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        overviewReq.setEnterpriseId(user.getEnterpriseId());
        Map<String, Object> res = DataApiUtils.http(JSON.toJSONString(overviewReq), StatisticsApolloKeyConstant.data_mkt_group_chat_data_overview);
        Page page = DataApiUtils.getPageData(res);
        List<JSONObject> result = page.getResult();
        if (CollectionUtils.isEmpty(result)) {
            return RestResponse.successResult(null);
        }
        GroupChatDataOverviewVO groupChatDataOverviewVO = JSON.parseObject(JSON.toJSONString(result.get(0)), GroupChatDataOverviewVO.class);
        return RestResponse.successResult(groupChatDataOverviewVO);
    }

    /**
     * 阶梯奖励数据
     *
     * @param rewardLevelReq
     * @return
     */
    @RequestMapping("reward_level")
    @ResponseBody
    public RestResponse<Page<GroupChatDataRewardLevelVO>> rewardLevel(@RequestBody GroupChatActivityDataRewardLevelReq rewardLevelReq) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        rewardLevelReq.setEnterpriseId(user.getEnterpriseId());
        Map<String, Object> res = DataApiUtils.http(JSON.toJSONString(rewardLevelReq), StatisticsApolloKeyConstant.data_mkt_group_chat_data_reward_level);
        Page page = DataApiUtils.getPageData(res);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            List<GroupChatDataRewardLevelVO> groupChatDataOverviewVOList = JSON.parseArray(JSON.toJSONString(page.getResult()), GroupChatDataRewardLevelVO.class);
            page.setResult(groupChatDataOverviewVOList);
        }
        return RestResponse.successResult(page);
    }

    /**
     * 参与客户明细
     *
     * @param inviterDetailReq
     * @return
     */
    @RequestMapping("join_detail")
    @ResponseBody
    public RestResponse<Page<GroupChatDataJoinDetailVO>> joinDetail(@RequestBody GroupChatActivityDataInviterDetailReq inviterDetailReq) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        inviterDetailReq.setEnterpriseId(user.getEnterpriseId());
        Map<String, Object> res = DataApiUtils.http(JSON.toJSONString(inviterDetailReq), StatisticsApolloKeyConstant.data_mkt_group_chat_data_inviter_detail);
        Page page = DataApiUtils.getPageData(res);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            List<GroupChatDataJoinDetailVO> groupChatDataJoinDetailVOS = JSON.parseArray(JSON.toJSONString(page.getResult()), GroupChatDataJoinDetailVO.class);
            page.setResult(groupChatDataJoinDetailVOS);
        }
        return RestResponse.successResult(page);
    }


    /**
     * 邀请明细
     *
     * @param inviteLogQDTO
     * @return
     */
    @RequestMapping("inviter_detail")
    @ResponseBody
    public RestResponse<Page<GroupChatActivityInviteVO>> inviterDetail(@RequestBody GroupChatActivityInviteLogQDTO inviteLogQDTO) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        inviteLogQDTO.setEnterpriseId(user.getEnterpriseId());
        inviteLogQDTO.setSortFiled("create_time");
        inviteLogQDTO.setSortType("desc");
        ServiceResponse<Page<GroupChatActivityInviteLogDTO>> listServiceResponse = groupChatActivityLogApiService.queryInviteLogDetails(inviteLogQDTO);
        if (!listServiceResponse.isSuccess()) {
            return RestResponse.failure(listServiceResponse.getCode(), listServiceResponse.getMessage());
        }
        Page<GroupChatActivityInviteVO> page = new Page<>(inviteLogQDTO.getPageNum(), inviteLogQDTO.getPageSize(), 0, 0);
        Page<GroupChatActivityInviteLogDTO> groupChatActivityInviteLogPage = listServiceResponse.getResult();

        if (CollectionUtils.isEmpty(groupChatActivityInviteLogPage.getResult())) {
            return RestResponse.successResult(page);
        }
        Map<String, MemberDocDTO> memberDocDTOMap = Maps.newHashMap();
        List<String> inviteeMemberIdList = groupChatActivityInviteLogPage.getResult().stream()
                .map(GroupChatActivityInviteLogDTO::getInviteeMemberId).filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(inviteeMemberIdList)) {
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(inviteLogQDTO.getEnterpriseId());
            List<MemberDocDTO> memberDocDTOList = memberService.getMembersFromSearchIndex(enterpriseDTO.getEnterpriseMicroSignal(), inviteeMemberIdList);
            memberDocDTOMap = memberDocDTOList.stream().collect(Collectors.toMap(MemberDocDTO::getMemberId, memberDocDTO -> memberDocDTO));
        }

        Map<String, MemberDocDTO> finalMemberDocDTOMap = memberDocDTOMap;
        List<GroupChatActivityInviteVO> groupChatActivityInviteVOList = groupChatActivityInviteLogPage.getResult().stream().map(groupChatActivityInviteLogDTO -> {
            GroupChatActivityInviteVO groupChatActivityInviteVO = new GroupChatActivityInviteVO();
            groupChatActivityInviteVO.setNickName(groupChatActivityInviteLogDTO.getNickName());
            MemberDocDTO memberDocDTO = finalMemberDocDTOMap.get(groupChatActivityInviteLogDTO.getInviteeMemberId());
            if (Objects.nonNull(memberDocDTO)) {
                groupChatActivityInviteVO.setPhotoUrl(memberDocDTO.getPhotoUrl());
            }
            return groupChatActivityInviteVO;
        }).collect(Collectors.toList());
        page.setResult(groupChatActivityInviteVOList);
        page.setResult(groupChatActivityInviteVOList);
        page.setTotalCount(groupChatActivityInviteLogPage.getTotalCount());
        page.setTotalPage(groupChatActivityInviteLogPage.getTotalPage());
        return RestResponse.successResult(page);
    }

    /**
     * 奖励明细
     *
     * @param rewardLogQDTO
     * @return
     */
    @RequestMapping("reward_detail")
    @ResponseBody
    public RestResponse<Page<GroupChatActivityRewardVO>> rewardDetail(@RequestBody GroupChatActivityRewardLogQDTO rewardLogQDTO) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        rewardLogQDTO.setEnterpriseId(user.getEnterpriseId());

        ServiceResponse<Page<GroupChatActivityRewardLogDTO>> listServiceResponse = groupChatActivityLogApiService.queryRewardLogDetails(rewardLogQDTO);
        if (!listServiceResponse.isSuccess()) {
            return RestResponse.failure(listServiceResponse.getCode(), listServiceResponse.getMessage());
        }
        Page<GroupChatActivityRewardVO> page = new Page<>(rewardLogQDTO.getPageNum(), rewardLogQDTO.getPageSize(), 0, 0);
        Page<GroupChatActivityRewardLogDTO> groupChatActivityInviteLogPage = listServiceResponse.getResult();

        if (CollectionUtils.isEmpty(groupChatActivityInviteLogPage.getResult())) {
            return RestResponse.successResult(page);
        }

        List<GroupChatActivityRewardVO> groupChatActivityInviteVOList = convertToInteractionDetailVO(groupChatActivityInviteLogPage.getResult());
        page.setResult(groupChatActivityInviteVOList);
        page.setResult(groupChatActivityInviteVOList);
        page.setTotalCount(groupChatActivityInviteLogPage.getTotalCount());
        page.setTotalPage(groupChatActivityInviteLogPage.getTotalPage());
        return RestResponse.successResult(page);

    }


    /**
     * 奖励明细数据转换
     *
     * @param groupChatActivityRewardLogDTOS
     * @return
     */
    private List<GroupChatActivityRewardVO> convertToInteractionDetailVO(List<GroupChatActivityRewardLogDTO> groupChatActivityRewardLogDTOS) {
        List<String> memberIds = groupChatActivityRewardLogDTOS.stream().map(GroupChatActivityRewardLogDTO::getMemberId).collect(Collectors.toList());
        //会员信息
        List<MemberDTO> memberDtoList = memberService.getMemberDtoList(memberIds);
        //会员map
        Map<String, MemberDTO> memberDTOMap = memberDtoList.stream().collect(Collectors.toMap(MemberDTO::getMemberId, m -> m, (m1, m2) -> m2));

        return groupChatActivityRewardLogDTOS.stream().map(groupChatActivityRewardLogDTO -> {
            GroupChatActivityRewardVO groupChatActivityRewardVO = new GroupChatActivityRewardVO();
            BeanUtils.copyProperties(groupChatActivityRewardLogDTO, groupChatActivityRewardVO);
            MemberDTO memberDTO = memberDTOMap.get(groupChatActivityRewardLogDTO.getMemberId());
            if (Objects.nonNull(memberDTO)) {
                groupChatActivityRewardVO.setName(memberDTO.getMemberName());
                groupChatActivityRewardVO.setNickName(memberDTO.getThirdNickname());
                groupChatActivityRewardVO.setPhoneNumber(memberDTO.getPhoneNumber());
                groupChatActivityRewardVO.setMemberDeleteFlag(0);
            } else {
                groupChatActivityRewardVO.setMemberDeleteFlag(1);
            }
            if (CollectionUtils.isNotEmpty(groupChatActivityRewardLogDTO.getRewardDetailLogDTOList())) {
                int integral = 0;
                int growth = 0;
                List<String> cardList = Lists.newArrayList();
                for (GroupChatActivityRewardDetailLogDTO groupChatActivityRewardDetailLogDTO : groupChatActivityRewardLogDTO.getRewardDetailLogDTOList()) {
                    if (groupChatActivityRewardDetailLogDTO.getRewardType().equals(RewardResultTypeEnum.integral.getType())) {
                        integral += Integer.parseInt(groupChatActivityRewardDetailLogDTO.getRewardValue());
                    }
                    if (groupChatActivityRewardDetailLogDTO.getRewardType().equals(RewardResultTypeEnum.growth.getType())) {
                        growth += Integer.parseInt(groupChatActivityRewardDetailLogDTO.getRewardValue());
                    }
                    if (groupChatActivityRewardDetailLogDTO.getRewardType().equals(RewardResultTypeEnum.coupon.getType())) {
                        String card = groupChatActivityRewardDetailLogDTO.getRewardName() + "(";
                        if (groupChatActivityRewardDetailLogDTO.getSuccessFlag() == 1) {
                            card += groupChatActivityRewardDetailLogDTO.getRewardValue() + ")";
                        } else {
                            card += groupChatActivityRewardDetailLogDTO.getRewardRemark() + ")";
                        }
                        cardList.add(card);
                    }
                }
                groupChatActivityRewardVO.setIntegral(integral);
                groupChatActivityRewardVO.setGrowth(growth);
                groupChatActivityRewardVO.setCardInfo(StringUtils.join(cardList, "、"));
            }
            return groupChatActivityRewardVO;
        }).collect(Collectors.toList());


    }
}
