package cn.freemud.service.impl;

import cn.freemud.adapter.CouponAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.vo.ActivityClassifyCouponBean;
import cn.freemud.entities.vo.ActivityCouponBean;
import cn.freemud.enums.*;
import cn.freemud.service.CouponActivityService;
import cn.freemud.service.thirdparty.CouponClient;
import cn.freemud.service.thirdparty.CouponOfflineClient;
import cn.freemud.utils.LogUtil;
import cn.freemud.utils.ResponseUtil;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 券服务
 */
@Service
public class CouponActivityServiceImpl implements CouponActivityService {

    @Autowired
    private CouponAdapter couponAdapter;
    @Autowired
    private CouponOfflineClient couponOfflineClient;
    private static Gson gson = new Gson();
    @Override
    public BaseResponse verificationCoupon(ActivityChannelEnum activityChannelEnum, String couponCode, String oid, String partnerId,
                                           String storeId, String userId, List<CouponCodeVerificationProductDto> products,Integer discountPrice) {
        if (StringUtils.isNotBlank(couponCode)) {
            CouponCodeVerificationDto couponCodeVerificationDto = couponAdapter.convert2CouponCodeVerificationDto(activityChannelEnum, couponCode, oid, partnerId, storeId, userId, products,discountPrice);
            try {
                //3.券核销
                CouponCodeResponseDto couponCodeResponseDto = couponOfflineClient.verification(couponCodeVerificationDto);
                LogUtil.info("coupond_verification_info", gson.toJson(couponCodeVerificationDto), gson.toJson(couponCodeResponseDto));
                if (!Objects.equals(couponCodeResponseDto.getStatusCode(), ResponseResult.SUCCESS.getCode())) {
                    LogUtil.info("coupond_verification_error", gson.toJson(couponCodeVerificationDto), gson.toJson(couponCodeResponseDto));
                    return ResponseUtil.error(ResponseResult.COUPON_VERIFICATION_FAIL);
                }
            } catch (Exception e) {
                LogUtil.error("verification_error", gson.toJson(couponCodeVerificationDto), "", e);
                return ResponseUtil.error(ResponseResult.COUPON_VERIFICATION_FAIL);
            }
        }
        return ResponseUtil.success();
    }
}
