package com.gic.haoban.manage.service.service.chat.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BusinessException;
import com.gic.api.base.commons.Constant;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.chat.*;
import com.gic.haoban.manage.api.enums.chat.ChatActivityInviteRewardEnum;
import com.gic.haoban.manage.api.enums.chat.ChatActivityRewardInviteEnum;
import com.gic.haoban.manage.service.context.chat.RewardSender;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatActivityInviteLogMapper;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.PageHelperUtils;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivityRewardDetailLogQDTO;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivityRewardLogQDTO;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatActivityRewardDetailLogMapper;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatActivityRewardLogMapper;
import com.gic.haoban.manage.service.entity.chat.*;
import com.gic.haoban.manage.service.pojo.bo.RewardReturnBO;
import com.gic.haoban.manage.service.pojo.bo.chat.GroupChatActivityContext;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatActivityInviteLog;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatActivityRewardLog;
import com.gic.haoban.manage.service.service.chat.GroupChatActivityRewardDetailLogService;
import com.gic.haoban.manage.service.service.chat.GroupChatActivityRewardLogService;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 内容活动完成奖励表(TabHaobanGroupChatActivityRewardLog)表服务实现类
 *
 * @author makejava
 * @since 2024-09-27 16:09:57
 */
@Service("groupChatActivityRewardLogService")
public class GroupChatActivityRewardLogServiceImpl implements GroupChatActivityRewardLogService {

    private static final Logger logger = LoggerFactory.getLogger(GroupChatActivityRewardLogService.class);

    @Autowired
    private GroupChatActivityRewardLogMapper groupChatActivityRewardLogMapper;
    @Autowired
    private GroupChatActivityInviteLogMapper groupChatActivityInviteLogMapper;
    @Autowired
    private GroupChatActivityRewardDetailLogMapper groupChatActivityRewardDetailLogMapper;
    @Autowired
    private GroupChatActivityRewardDetailLogService groupChatActivityRewardDetailLogService;
    @Autowired
    private RewardSender rewardSender;

    private GroupChatActivityRewardLogDTO convertToDTO(TabGroupChatActivityRewardLog tabGroupChatActivityRewardLog) {
        GroupChatActivityRewardLogDTO groupChatActivityRewardLogDTO = new GroupChatActivityRewardLogDTO();
        BeanUtils.copyProperties(tabGroupChatActivityRewardLog, groupChatActivityRewardLogDTO);
        return groupChatActivityRewardLogDTO;
    }

    @Override
    public Page<GroupChatActivityRewardLogDTO> queryRewardLogDetails(GroupChatActivityRewardLogQDTO rewardLogQDTO) {
        PageHelper.startPage(rewardLogQDTO);
        List<TabGroupChatActivityRewardLog> rewardLogList = groupChatActivityRewardLogMapper.queryList(rewardLogQDTO);
        if (CollectionUtils.isEmpty(rewardLogList)) {
            return PageHelperUtils.changePageHelperToCurrentPage(rewardLogList, GroupChatActivityRewardLogDTO.class);
        }
        Page<GroupChatActivityRewardLogDTO> page = PageHelperUtils.changePageHelperToCurrentPage(rewardLogList, GroupChatActivityRewardLogDTO.class);

        List<Long> rewardLogIdList = rewardLogList.stream()
                .map(TabGroupChatActivityRewardLog::getChatActivityRewardLogId).collect(Collectors.toList());
        GroupChatActivityRewardDetailLogQDTO rewardDetailLogQDTO = new GroupChatActivityRewardDetailLogQDTO();
        rewardDetailLogQDTO.setRewardLogIdList(rewardLogIdList);
        List<GroupChatActivityRewardDetailLogDTO> rewardDetailLogDTOList = groupChatActivityRewardDetailLogService.queryList(rewardDetailLogQDTO);
        Map<Long, List<GroupChatActivityRewardDetailLogDTO>> rewardDetailLogDTOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(rewardDetailLogDTOList)) {
            rewardDetailLogDTOMap = rewardDetailLogDTOList.stream()
                    .collect(Collectors.groupingBy(GroupChatActivityRewardDetailLogDTO::getChatActivityRewardId));
        }
        Map<Long, List<GroupChatActivityRewardDetailLogDTO>> finalRewardDetailLogDTOMap = rewardDetailLogDTOMap;

        List<GroupChatActivityRewardLogDTO> rewardLogDTOList = rewardLogList.stream().map(tabGroupChatActivityRewardLog -> {
            GroupChatActivityRewardLogDTO rewardLogDTO = convertToDTO(tabGroupChatActivityRewardLog);
            rewardLogDTO.setRewardDetailLogDTOList(finalRewardDetailLogDTOMap.get(rewardLogDTO.getChatActivityRewardLogId()));
            return rewardLogDTO;

        }).collect(Collectors.toList());
        page.setResult(rewardLogDTOList);
        return page;
    }
    @Override
    public void dealRewardAndSaveLog(GroupChatActivityContext context) {
        Long chatActivityId = context.getChatActivityId();
        String inviterMemberId = context.getInviterMemberId();
        String enterpriseId = context.getEnterpriseId();
        GroupChatActivityDTO chatActivityDTO = context.getChatActivityDTO();
        Integer inviteRewardType = chatActivityDTO.getInviteRewardType();
        Map<Integer, List<GroupChatActivityRewardDTO>> rewardMap = chatActivityDTO.getRewardMap();
        TabGroupChatActivityInviteLog inviteLog = new TabGroupChatActivityInviteLog();
        inviteLog.setChatActivityId(chatActivityId);
        inviteLog.setInviterMemberId(inviterMemberId);
        inviteLog.setEnterpriseId(enterpriseId);
        inviteLog.setInviteType(Constant.FLAG_TRUE);
        Long count = groupChatActivityInviteLogMapper.count(inviteLog);
        if (count <= 0) {
            return;
        }
        //发送邀请人奖励
        List<GroupChatActivityRewardDTO> inviterRewardDTOList = rewardMap.get(ChatActivityRewardInviteEnum.INVITER.value);
        if (CollectionUtils.isNotEmpty(inviterRewardDTOList)) {
            List<GroupChatActivityRewardDTO> sendReward = new ArrayList<>();
            Integer inviteLevel = 1;
            for (GroupChatActivityRewardDTO rewardDTO : inviterRewardDTOList) {
                Integer inviteNumber = rewardDTO.getInviteNumber();
                Integer limitReward = rewardDTO.getLimitReward();
                if (Objects.equals(ChatActivityInviteRewardEnum.FIXED_REWARD.value, inviteRewardType)) {
                    //固定奖励 有效邀请为整数倍 且 完成奖励次数小于等于奖励上限
                    if (count.intValue() % inviteNumber == 0 && count.intValue() / inviteNumber <= limitReward) {
                        sendReward.add(rewardDTO);
                    }
                } else if (Objects.equals(ChatActivityInviteRewardEnum.LADDER_REWARD.value, inviteRewardType)) {
                    // 阶梯奖励 有效邀请次数相等
                    if (count.intValue() == inviteNumber) {
                        sendReward.add(rewardDTO);
                        inviteLevel = rewardDTO.getInviteLevel();
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(sendReward)) {
                dealInviteReward(chatActivityId, inviterMemberId, inviteLevel, ChatActivityRewardInviteEnum.INVITER.value, sendReward, chatActivityDTO);
            }
        }
        List<GroupChatActivityRewardDTO> inviteeRewardDTOList = rewardMap.get(ChatActivityRewardInviteEnum.INVITEE.value);
        //发送受邀人奖励
        if (CollectionUtils.isNotEmpty(inviteeRewardDTOList)) {
            String memberId = context.getChatUser().getMemberId();
            if (StringUtils.isBlank(memberId)) {
                logger.info("受邀人memberId为空");
                return;
            }
            dealInviteReward(chatActivityId, memberId, 1, ChatActivityRewardInviteEnum.INVITEE.value, inviteeRewardDTOList, chatActivityDTO);
        }
    }

    /**
     * 发送奖励并保存日志
     * @param chatActivityId    活动id
     * @param memberId  会员id
     * @param inviteLevel   完成的层级
     * @param rewardInvite  奖励人类型
     * @param sendReward    发送的奖励明细
     * @param activityDTO   活动DTO
     */
    private void dealInviteReward(Long chatActivityId, String memberId, Integer inviteLevel,Integer rewardInvite, List<GroupChatActivityRewardDTO> sendReward, GroupChatActivityDTO activityDTO) {
        String enterpriseId = activityDTO.getEnterpriseId();
        String wxEnterpriseId = activityDTO.getWxEnterpriseId();
        String activityName = activityDTO.getActivityName();
        //保存奖励记录
        Long rewardLogId = UniqueIdUtils.uniqueLong();
        TabGroupChatActivityRewardLog rewardLog = new TabGroupChatActivityRewardLog();
        rewardLog.setChatActivityRewardLogId(rewardLogId);
        rewardLog.setChatActivityId(chatActivityId);
        rewardLog.setMemberId(memberId);
        rewardLog.setRewardInvite(rewardInvite);
        rewardLog.setInviteLevel(inviteLevel);
        rewardLog.setEnterpriseId(enterpriseId);
        rewardLog.setWxEnterpriseId(wxEnterpriseId);
        groupChatActivityRewardLogMapper.insert(rewardLog);
        for (GroupChatActivityRewardDTO rewardDTO : sendReward) {
            List<GroupChatActivityRewardDetailDTO> detailList = rewardDTO.getDetailList();
            for (GroupChatActivityRewardDetailDTO rewardDetailDTO : detailList) {
                String rewardValue = rewardDetailDTO.getRewardValue();
                List<JSONObject> list = JSONArray.parseArray(rewardDetailDTO.getRewardName(), JSONObject.class);
                String[] rewardList = rewardValue.split(",");
                for (int i = 0; i < rewardList.length; i++) {
                    String rewardV = rewardList[i];
                    String rewardName = list.get(i).getString("name");
                    TabGroupChatActivityRewardDetailLog rewardDetailLog = new TabGroupChatActivityRewardDetailLog();
                    Long rewardDetailId = UniqueIdUtils.uniqueLong();
                    rewardDetailLog.setChatActivityRewardDetailId(rewardDetailId);
                    rewardDetailLog.setChatActivityRewardId(rewardLogId);
                    rewardDetailLog.setChatActivityId(rewardDTO.getChatActivityId());
                    rewardDetailLog.setActivityRewardId(rewardDetailDTO.getChatActivityRewardId());
                    rewardDetailLog.setMemberId(memberId);
                    rewardDetailLog.setRewardType(rewardDetailDTO.getRewardType());
                    rewardDetailLog.setRewardValue(rewardV);
                    rewardDetailLog.setRewardName(rewardName);
                    rewardDetailLog.setSuccessFlag(Constant.FLAG_FALSE);
                    rewardDetailLog.setEnterpriseId(enterpriseId);
                    rewardDetailLog.setWxEnterpriseId(wxEnterpriseId);
                    groupChatActivityRewardDetailLogMapper.insert(rewardDetailLog);
                    RewardReturnBO rewardReturnBO = null;
                    String rewardRemark = null;
                    try {
                        rewardReturnBO = rewardSender.sendReward(rewardDetailLog, activityName);
                    } catch (BusinessException e) {
                        logger.info("发放奖励失败 rewardDetailLogId:{}", rewardDetailId, e);
                        rewardRemark = e.getMessage();
                    }
                    rewardDetailLog.setRewardRemark(rewardRemark);
                    if (rewardReturnBO != null) {
                        rewardDetailLog.setRewardBusinessId(rewardReturnBO.getRewardBusinessId());
                        rewardDetailLog.setSuccessFlag(Constant.FLAG_TRUE);
                    }
                    groupChatActivityRewardDetailLogMapper.update(rewardDetailLog);
                }
            }
        }
    }
}
