package cn.freemud.handle;

import cn.freemud.entities.dto.BindingCouponTypeDto;
import cn.freemud.entities.vo.CouponMsg;
import cn.freemud.enums.ResponseResult;
import cn.freemud.redis.RedisCache;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.couponcenter.online.domain.ActiveDetailVO;
import com.freemud.application.sdk.api.couponcenter.online.domain.AppKeyVO;
import com.freemud.application.sdk.api.couponcenter.online.request.ActiveBatchQueryRequest;
import com.freemud.application.sdk.api.couponcenter.online.request.PartnerRequest;
import com.freemud.application.sdk.api.couponcenter.online.service.FMActiveSdkService;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.sdk.api.assortment.shoppingcart.util.ShoppingSdkLogUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : xh.Z
 * @email : fisherman0510@163.com
 * @Date : 2021/10/22 下午7:54
 * @description :
 */
@Component
public class GetActivityMsgHandle {

    @Value("${coupon.app.id}")
    private String appId;

    /**
     * fisherman 获取 虚拟商品 券数据
     *
     * @param productBindingCoupons
     * @param partnerId
     * @return
     */
    public List<CouponMsg> getCouponData(List<BindingCouponTypeDto> productBindingCoupons, String partnerId) {
        List<CouponMsg> retList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(productBindingCoupons)) {
            // 处理 券数据  这里链路有问题  效率有点低, 后续需要优化
            List<String> activityCodes = productBindingCoupons.stream()
                    .map(BindingCouponTypeDto::getActivityCode)
                    .collect(Collectors.toList());
            List<ActiveDetailVO> activeDetailVOS = this.batchQueryActivityInfo(activityCodes, partnerId);
            if (CollectionUtils.isNotEmpty(activeDetailVOS)) {
                // 设置 券名称 数量
                Map<String, ActiveDetailVO> collect = activeDetailVOS.stream().collect(Collectors.toMap(ActiveDetailVO::getActiveCode, a -> a, (k1, k2) -> k1));
                productBindingCoupons.forEach(coupon -> {
                    CouponMsg msg = new CouponMsg();
                    ActiveDetailVO activeDetailVO = collect.get(coupon.getActivityCode());
                    msg.setActivityCode(coupon.getActivityCode());
                    msg.setNum(coupon.getNum());
                    msg.setActivityName(activeDetailVO.getActiveName());
                    retList.add(msg);
                });
            }
        }
        return retList;
    }

    private List<ActiveDetailVO> batchQueryActivityInfo(List<String> activityCodes, String partnerId) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        String appKey = this.getAppKey(partnerId, trackingNo);
        if (StringUtils.isEmpty(appKey)) {
            return null;
        }
        ActiveBatchQueryRequest activeBatchQueryRequest = new ActiveBatchQueryRequest();
        //去重
        List<String> activeCodes = new ArrayList<>(new HashSet(activityCodes));
        activeBatchQueryRequest.setActiveCode(activeCodes);
        activeBatchQueryRequest.setAppSecret(appKey);
        activeBatchQueryRequest.setPartnerId(Integer.parseInt(partnerId));
        FMActiveSdkService fmActiveSdkService = SDKCommonBaseContextWare.getBean(FMActiveSdkService.class);
        BaseResponse<List<ActiveDetailVO>> batchQueryResponse = fmActiveSdkService.batchQueryActivityInfo(activeBatchQueryRequest, trackingNo);
        if (batchQueryResponse == null
                || !ResponseResult.SUCCESS.getCode().equals(batchQueryResponse.getCode())
                || CollectionUtils.isEmpty(batchQueryResponse.getData())) {
            return null;
        }
        return batchQueryResponse.getData();
    }

    private String getAppKey(String partnerId, String trackingNo) {
        RedisCache redisCache = SDKCommonBaseContextWare.getBean(RedisCache.class);
        String key = "kgd:coupon:appKey:partner:";
        String appKey = redisCache.getValue(key + partnerId);
        if (StringUtils.isEmpty(appKey)) {
            PartnerRequest partnerRequest = new PartnerRequest();
            partnerRequest.setPartnerId(Integer.parseInt(partnerId));
            partnerRequest.setAppId(appId);
            FMActiveSdkService fmActiveSdkService = SDKCommonBaseContextWare.getBean(FMActiveSdkService.class);
            com.freemud.application.sdk.api.base.BaseResponse<AppKeyVO> appKeyVOBaseResponse = fmActiveSdkService.getAppKey(partnerRequest, trackingNo);
            if (appKeyVOBaseResponse == null || !"100".equals(appKeyVOBaseResponse.getCode())
                    || appKeyVOBaseResponse.getData() == null || StringUtils.isEmpty(appKeyVOBaseResponse.getData().getAppKey())) {
                return null;
            }
            appKey = appKeyVOBaseResponse.getData().getAppKey();
            redisCache.save(key + partnerId, appKey);
        }
        return appKey;
    }
}
