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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BusinessException;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.content.api.enums.activity.ContentActivityRewardEnum;
import com.gic.enterprise.api.enums.PlatformChannelEnum;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatActivityRewardDetailLog;
import com.gic.haoban.manage.service.pojo.bo.RewardReturnBO;
import com.gic.haoban.manage.service.util.ExecuteServiceUtil;
import com.gic.marketing.api.dto.CoupCardCode;
import com.gic.marketing.api.dto.CoupCardLogDTO;
import com.gic.marketing.api.enums.MarketingErrCode;
import com.gic.marketing.api.service.CoupCardDistributionService;
import com.gic.member.api.constant.integral.IntegralTypeEnum;
import com.gic.member.api.dto.integral.req.IntegralOperationFullReq;
import com.gic.member.api.dto.integral.resp.IntegralOperationResp;
import com.gic.member.api.service.integral.IntegralWriteApiService;
import com.gic.member.ext.api.dto.growth.constant.GrowthErrorCode;
import com.gic.member.ext.api.dto.growth.req.MemberGrowthChangeValueReq;
import com.gic.member.ext.api.dto.growth.resp.MemberGrowthOperateResp;
import com.gic.member.ext.api.enums.growth.GrowthRuleEnum;
import com.gic.member.ext.api.service.MemberGrowthWriteApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class RewardSender {

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

    private static final String BUSINESS_NAME = "社群邀请有礼";

    @Autowired
    private IntegralWriteApiService integralWriteApiService;
    @Autowired
    private CoupCardDistributionService coupCardDistributionService;
    @Autowired
    private MemberGrowthWriteApiService memberGrowthWriteApiService;

    public RewardReturnBO sendReward(TabGroupChatActivityRewardDetailLog rewardDetailLog, String activityName) throws BusinessException {
        String enterpriseId = rewardDetailLog.getEnterpriseId();
        String memberId = rewardDetailLog.getMemberId();
        Long chatActivityId = rewardDetailLog.getChatActivityId();
        String rewardDetailLogId = String.valueOf(rewardDetailLog.getChatActivityRewardDetailId());
        Integer rewardType = rewardDetailLog.getRewardType();
        String rewardValue = rewardDetailLog.getRewardValue();

        logger.info("处理奖励: enterpriseId={}, memberId={}, rewardType={}, rewardValue={}",
                enterpriseId, memberId, rewardType, rewardValue);

        switch (ContentActivityRewardEnum.getByValue(rewardType)) {
            case INTEGRAL:
                Integer integral = Integer.parseInt(rewardValue);
                return sendIntegral(enterpriseId, memberId, integral, BUSINESS_NAME + "-" + activityName, rewardDetailLogId, rewardDetailLogId);
            case GROWTH:
                Integer growthValue = Integer.parseInt(rewardValue);
                return sendGrowth(enterpriseId, memberId, growthValue, activityName, rewardDetailLogId, rewardDetailLogId);
            case COUPON:
                return sendCoupon(enterpriseId, memberId, rewardValue, String.valueOf(chatActivityId));
            default:
                throw new BusinessException("-1", "不支持的奖励类型");
        }
    }

    public RewardReturnBO sendIntegral(String enterpriseId, String memberId, Integer integral, String remark, String relationId, String oRelationId) throws BusinessException {
        Integer integralType = integral > 0 ? IntegralTypeEnum.TYPE_1122.getCode() : IntegralTypeEnum.TYPE_1242.getCode();
        IntegralOperationFullReq req = new IntegralOperationFullReq();
        req.setMemberId(memberId);
        req.setEnterpriseId(enterpriseId);
        req.setIntegralType(integralType);
        req.setIntegral(integral);
        req.setSourceChannel(PlatformChannelEnum.C_WECHAT_MINI.getChannelCode());
        req.setRemark(remark);
        req.setUniqueId(relationId);
        req.setRelationId(relationId);
        req.setoRelationId(oRelationId);

        logger.info("发送积分:{}", JSON.toJSONString(req));

        ServiceResponse<IntegralOperationResp> response = ExecuteServiceUtil.executeService(() ->
                integralWriteApiService.integralOperation(req), "积分处理异常");

        if (response.isSuccess() && response.getResult() != null) {
            Integer realOperationIntegral = response.getResult().getRealOperationIntegral();
            return new RewardReturnBO(response.getResult().getIntegralLogId(), realOperationIntegral != null ? realOperationIntegral : integral);
        }
        throw new BusinessException("-1", response.getMessage());
    }

    public RewardReturnBO sendGrowth(String enterpriseId, String memberId, Integer growthValue, String remark, String relationId, String oRelationId) throws BusinessException {
        String ruleCode = GrowthRuleEnum.INVITE_ACTIVITY.getRuleCode();
        MemberGrowthChangeValueReq req = new MemberGrowthChangeValueReq();
        req.setEnterpriseId(enterpriseId);
        req.setMemberId(memberId);
        req.setChannelCode(PlatformChannelEnum.C_WECHAT_MINI.getChannelCode());
        req.setRuleCode(ruleCode);
        req.setGrowthChangeValue(growthValue);
        req.desc(BUSINESS_NAME, remark);
        req.setOuterChangeId(relationId);
        req.setOriginChangeId(oRelationId);
        logger.info("发送成长值: {}", JSON.toJSONString(req));

        ServiceResponse<MemberGrowthOperateResp> response = ExecuteServiceUtil.executeService(() ->
                memberGrowthWriteApiService.updateMemberGrowthChangeValue(req), "成长值发放异常");

        if (response.isSuccess() && response.getResult() != null) {
            MemberGrowthOperateResp growthResp = response.getResult();
            return new RewardReturnBO(String.valueOf(growthResp.getChangeId()), growthResp.getActualChangeGrowth());
        }
        if (Objects.equals(response.getCode(), GrowthErrorCode.MEMBER_GROWTH_IS_ZERO.code())) {
            //当前会员没有成长值，无法进行扣除
            return new RewardReturnBO("", 0);
        }
        throw new BusinessException("-1", response.getMessage());
    }

    public RewardReturnBO sendCoupon(String enterpriseId, String memberId, String cardId, String relationId) throws BusinessException {
        logger.info("发送卡券: enterpriseId={}, memberId={}, cardId={}, relationId={}", enterpriseId, memberId, cardId, relationId);

        ServiceResponse<CoupCardLogDTO> response = ExecuteServiceUtil.executeService(() ->
                coupCardDistributionService.sendCard(enterpriseId, cardId, memberId, "",
                CoupCardCode.CARD_RECEIVE_CODE_GROUP_CHAT_ACTIVITY.getCode(),
                CoupCardCode.CARD_RECEIVE_CODE_GROUP_CHAT_ACTIVITY.getRelationType(), relationId, true), "卡券发放异常");
        if (response.isSuccess() && response.getResult() != null) {
            CoupCardLogDTO cardLogDTO = response.getResult();
            return new RewardReturnBO(cardLogDTO.getCardLogId(), null);
        }
        throw new BusinessException("-1", MarketingErrCode.convertCouponError(response.getMessage()));
    }

}
