/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: CouponServiceImpl
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: song.cai
 * @date: 2018/12/24 18:40
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

package cn.freemud.service.impl;

import cn.freemud.adapter.CouponAdapter;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.demo.manager.coupon.Finals;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.coupon.Active;
import cn.freemud.entities.dto.coupon.CouponAvailableRespDto;
import cn.freemud.entities.dto.product.*;
import cn.freemud.entities.vo.*;
import cn.freemud.entities.vo.coupon.CouponAvailableReqVo;
import cn.freemud.entities.vo.coupon.CouponStateVo;
import cn.freemud.entities.vo.coupon.Product;
import cn.freemud.enums.*;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.CommonService;
import cn.freemud.service.CouponService;
import cn.freemud.service.ItemService;
import cn.freemud.service.thirdparty.*;
import cn.freemud.utils.BarcodeUtil;
import cn.freemud.utils.PropertyConvertUtil;
import cn.freemud.utils.RedisUtil;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.productcenter.constant.ResponseConstant;
import com.freemud.application.sdk.api.util.SignUtil;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;


@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CustomerExtendClient customerExtendClient;
    @Autowired
    private CouponAdapter couponAdapter;
    @Autowired
    private CouponOnlineClient couponOnlineClient;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ProductClient storeItemClient;
    @Autowired
    private ItemService itemService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private CouponAdapterClient couponAdaptClient;
    @Autowired
    private AssortmentSdkService assortmentSdkService;
    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;



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



    /**
     * 获取会员服务的优惠券列表
     *
     * @param getMemberCouponListRequestDto
     * @return
     */
    public GetMemberCouponListResponseDto.Result getMemberCouponList(GetMemberCouponListRequestDto getMemberCouponListRequestDto) {
        GetMemberCouponListResponseDto getMemberCouponListResponseDto = null;
        try {
            getMemberCouponListResponseDto = customerExtendClient.getMemberCouponListRequestDto(getMemberCouponListRequestDto);
        } catch (Exception ex) {
            ErrorLog.errorConvertJson(this.getClass(),"会员服务优惠券接口调用失败",ex);
        }
        if (getMemberCouponListResponseDto != null && Objects.equals(getMemberCouponListResponseDto.getCode(), ResponseResult.SUCCESS.getCode())) {
            return getMemberCouponListResponseDto.getData();
        }
        return null;
    }

    /**
     * 获取会员服务的优惠券列表
     *
     * @param getMemberCouponListRequestDto
     * @return
     */
    public List<GetMemberCouponListResponseDto.Result.MemberCoupon> getValidMemberCouponList(GetMemberCouponListRequestDto getMemberCouponListRequestDto, Integer orderType) {
        List<GetMemberCouponListResponseDto.Result.MemberCoupon> memberCoupons = Lists.newArrayList();
        GetMemberCouponListResponseDto.Result result = getMemberCouponList(getMemberCouponListRequestDto);
        // 过滤优惠券得点餐方式
        if (!Objects.isNull(result) && CollectionUtils.isNotEmpty(result.getMemberCoupons())) {
            List<String> activityCodes = result.getMemberCoupons().stream().map(GetMemberCouponListResponseDto.Result.MemberCoupon::getActivityCode).collect(Collectors.toList());
            Map<String, Boolean> activityCodesMap = couponOrderWay(getMemberCouponListRequestDto.getPartnerId(), activityCodes, orderType);
            result.getMemberCoupons().forEach(memberCoupon -> {
                if (activityCodesMap.get(memberCoupon.getActivityCode()) != null && activityCodesMap.get(memberCoupon.getActivityCode())) {
                    memberCoupons.add(memberCoupon);
                }
            });
        }
        return memberCoupons;
    }



    @Override
    public GetCouponDetailResponseDto getMemberCoupon(GetMemberCouponRequestVo requestVo) {
        //券详情查券服务
        Map<String, Object> map = new TreeMap<>();
        if (StringUtils.isBlank(requestVo.getPartnerId()) || StringUtils.isBlank(requestVo.getCouponCode())) {
            return null;
        }
        map.put(Finals.CODES, requestVo.getCouponCode());
        map.put(Finals.PARTNER_ID, requestVo.getPartnerId());
        map.put(Finals.MERCHANT_ID, requestVo.getPartnerId());
        map.put(Finals.ACTION, "code.allDetails");
        // 券码接口新增参数：组织机构（多个用英文逗号分离）
        String channelIds = commonService.getOrgIdsAsString(requestVo.getPartnerId(), requestVo.getStoreId());
        map.put(Finals.CHANNEL_ID_LIST, channelIds);
        if(requestVo.getCheckStoreId()){
            map.put(Finals.STOREID, requestVo.getStoreId());
            map.put(Finals.STORECHECK, "0");
        }
        // 由于门店服务老是慢，这个参数可以控制不查门店服务， 返回的数据也不需要门店数据
        map.put(Finals.IS_QUERY_STORE, false);
        map.put(Finals.SIGN, "adapterV4Skip" + requestVo.getPartnerId());
        GetCouponDetailResponseDto responseDto = couponOnlineClient.getCouponDetails(map);
        if (ResponseCodeConstant.RESPONSE_SUCCESS_1.equals(responseDto.getResult())) {
            return responseDto;
        }
        return null;
    }


    @Override
    public String getAppSecret(String partnerId) {
        // 获取券服务的密钥
        String couponAppSecret = RedisUtil.getCouponAppSecret(partnerId);
        String appSecret = redisCache.getValue(couponAppSecret);
        if (StringUtils.isBlank(appSecret)) {
            GetAppKeyResponseDto getAppKeyResponseDto = couponOnlineClient.getAppKey(GetAppKeyRequestDto.builder().partnerId(partnerId).appId(appid).build());
            if (Objects.equals(String.valueOf(getAppKeyResponseDto.getStatusCode()), ResponseResult.SUCCESS.getCode())
                    && getAppKeyResponseDto.getData() != null) {
                redisCache.save(couponAppSecret, getAppKeyResponseDto.getData().getAppKey());
                appSecret = getAppKeyResponseDto.getData().getAppKey();
            }
        }
        return appSecret;
    }


    /**
     * key = 活动code , value = 返回是否匹配点餐方式
     */
    @Override
    public Map<String, Boolean> couponOrderWay(String partnerId, List<String> activityCodes, Integer orderTye) {
        // 去重
        List<String> activeCodes = new ArrayList<>(new HashSet(activityCodes));
        String appSecret = this.getAppSecret(partnerId);
        // 最大15一提交
        int maxNum = 15;
        int count = activeCodes.size() / maxNum;
        ActivityChannelEnum activityChannelEnum = PropertyConvertUtil.orderTypeConvert2ActivityChannel(orderTye);
        if (activityChannelEnum == null) {
            activityChannelEnum = ActivityChannelEnum.pickup;
        }
        Map<String, Boolean> result = new HashMap<>();
        for (int j = 0; j <= count; j++) {
            List calActiveCodes = null;
            if (j == count) {
                calActiveCodes = activeCodes.subList(maxNum * j, activeCodes.size());
            } else {
                calActiveCodes = activeCodes.subList(maxNum * j, maxNum * j + maxNum);
            }
            BatchQueryActivityInfoRequestDto requestDto = new BatchQueryActivityInfoRequestDto();
            requestDto.setActiveCode(calActiveCodes);
            // 书写逻辑
            requestDto.setPartnerId(Integer.valueOf(partnerId));
            String sign = SignUtil.createMD5Sign(requestDto, appSecret);
            requestDto.setSign(sign);
            BatchQueryActivityInfoResponseDto batchQueryActivityInfoResponseDto = couponOnlineClient.batchQueryActivityInfo(requestDto);
            if (Objects.equals(batchQueryActivityInfoResponseDto.getStatusCode(), ResponseCodeConstant.RESPONSE_SUCCESS_0_STR)
                    && CollectionUtils.isNotEmpty(batchQueryActivityInfoResponseDto.getActivities())) {
                ActivityChannelEnum finalActivityChannelEnum = activityChannelEnum;
                batchQueryActivityInfoResponseDto.getActivities().forEach(active -> {
                    // 兼容历史数据
                    if (Objects.isNull(active.getRedeemChannel())) {
                        result.put(active.getActiveCode(), true);
                    } else {
                        result.put(active.getActiveCode(), Arrays.stream(active.getRedeemChannel().split(",")).anyMatch(Predicate.isEqual(finalActivityChannelEnum.getCode())));
                    }
                });
            }
        }
        return result;
    }


    @Override
    public ActivityClassifyCouponBean availableCoupon(List<CartGoods> cartGoods
                                                      , String partnerId
                                                      , String userId
                                                      , String storeId
                                                      , CouponPromotionVO couponPromotionVO
                                                      , boolean hasGoodsCoupon
                                                      , Integer orderType
                                                      , int isNew
                                                      , String appId,
                                                      String menuType,
                                                      String chooseCouponCode) {
        GetMemberCouponListRequestDto getMemberCouponListRequestDto = new GetMemberCouponListRequestDto(partnerId, userId);
        getMemberCouponListRequestDto.setStatusFlags(Arrays.asList(CouponStatus.STATUS_0.getCode(), CouponStatus.STATUS_2.getCode()));
        getMemberCouponListRequestDto.setPageNum(1);
        getMemberCouponListRequestDto.setPageSize(Integer.MAX_VALUE);
        //获取会员服务的优惠券列表
        GetMemberCouponListResponseDto.Result result = getMemberCouponList(getMemberCouponListRequestDto);
        List<GetMemberCouponListResponseDto.Result.MemberCoupon> memberCoupons = Lists.newArrayList();
        // 过滤优惠券得点餐方式
        if (!Objects.isNull(result) && CollectionUtils.isNotEmpty(result.getMemberCoupons())) {
            List<String> activityCodes = result.getMemberCoupons().stream().map(GetMemberCouponListResponseDto.Result.MemberCoupon::getActivityCode).collect(Collectors.toList());
            Map<String, Boolean> activityCodesMap = couponOrderWay(partnerId, activityCodes, orderType);
            result.getMemberCoupons().forEach(memberCoupon -> {
                if (activityCodesMap.get(memberCoupon.getActivityCode()) != null && activityCodesMap.get(memberCoupon.getActivityCode())) {
                    memberCoupons.add(memberCoupon);
                }
            });
        }
        ActivityClassifyCouponBean availableCouponResponseVo = new ActivityClassifyCouponBean();
        // 可用优惠券信息
        List<ActivityCouponBean> usableCoupons = Lists.newArrayList();
        // 不可用优惠券信息
        List<ActivityCouponBean> disableCoupons = Lists.newArrayList();
        if (result == null || CollectionUtils.isEmpty(memberCoupons)) {
            return returnEmptyAvailableCoupon(availableCouponResponseVo, usableCoupons, disableCoupons);
        }
        // 对象转map
        Map<String, GetMemberCouponListResponseDto.Result.MemberCoupon> memberCouponMap = memberCoupons.stream().collect(
                Collectors.toMap(GetMemberCouponListResponseDto.Result.MemberCoupon::getCouponCode, a -> a, (k1, k2) -> k1));
        List<String> couponCodes = Lists.newArrayList();
        memberCoupons.forEach(memberCoupon -> {
            // 只筛选券结束时间大于当前时间的券
            if (System.currentTimeMillis() < DateUtil.convert2Date(memberCoupon.getEndTime(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS).getTime()) {
                couponCodes.add(memberCoupon.getCouponCode());
            }
        });
        // fisherman 构建可选优惠券
        Integer freightAmount = null;
        if (couponPromotionVO !=null) {
            Long deliveryAmount = couponPromotionVO.getDeliveryAmount();
            freightAmount = deliveryAmount ==null?null: deliveryAmount.intValue();
        }
        List<CouponStateVo> couponStateList = buildAvailiableCoupons(cartGoods, partnerId, storeId, couponCodes, isNew,appId,menuType,freightAmount);
        if (CollectionUtils.isNotEmpty(couponStateList)) {
            return returnSuccessAvailiableCoupons(couponPromotionVO == null ? new HashSet<>() : couponPromotionVO.getCouponCodes(), hasGoodsCoupon, availableCouponResponseVo, usableCoupons, disableCoupons, memberCouponMap, couponStateList, chooseCouponCode);
        }
        return null;
    }

    private List<CouponStateVo> buildAvailiableCoupons(List<CartGoods> cartGoods, String partnerId, String storeId, List<String> couponCodes, int isNew,String appId,String menuType,Integer freightAmount) {
//        String appSecret = getAppSecret(partnerId);
        // 最大15一提交
        int maxNum = 15;
        int count = couponCodes.size() / maxNum;
        // 计算可用不可用券
        CouponAvailableReqVo couponAvailableReqVo = new CouponAvailableReqVo();
        couponAvailableReqVo.setProviderId(partnerId);
        couponAvailableReqVo.setMerchantId(partnerId);
        couponAvailableReqVo.setStoreId(storeId);
        couponAvailableReqVo.setAppId(appId);
        couponAvailableReqVo.setFreightAmount(freightAmount);
        List<Product> productList = Lists.newArrayList();
        // 优惠券优先级最高，根据商品原价做计算
        // 订单金额
        Long totalAmount = createProductRequest(cartGoods, productList, isNew);
        couponAvailableReqVo.setTotalAmount(Integer.valueOf(totalAmount + ""));
        couponAvailableReqVo.setProductList(productList);
//        couponAvailableReqVo.setChannelCodeList(commonService.getOrgCodes(partnerId, storeId));
        couponAvailableReqVo.setChannelIdList(commonService.getOrgIdsForCoupon(partnerId, storeId));
        if (StringUtils.isNotBlank(menuType)) {
            String code = BusinessTypeEnum.getByType(menuType).getCode();
            String channel = CouponRedeemChannel.getChannelByType(code);
            if (StringUtils.isNotBlank(channel)) {
                couponAvailableReqVo.setRedeemChannel(channel);
            }
        }

        List<CouponStateVo> couponStateList = Lists.newArrayList();
        for (int j = 0; j <= count; j++) {
            List calCouponCodes = null;
            if (j == count) {
                calCouponCodes = couponCodes.subList(maxNum * j, couponCodes.size());
            } else {
                calCouponCodes = couponCodes.subList(maxNum * j, maxNum * j + maxNum);
            }
            couponAvailableReqVo.setCouponCodes(calCouponCodes);
            CouponAvailableRespDto couponsAvailable = couponAdaptClient.getCouponsAvailable(couponAvailableReqVo);
            if (Objects.equals(String.valueOf(couponsAvailable.getResult()), ResponseResult.SUCCESS.getCode())
                    && CollectionUtils.isNotEmpty(couponsAvailable.getCouponStateList())) {
                couponStateList.addAll(couponsAvailable.getCouponStateList());
            }
        }
        return couponStateList;
    }

    private ActivityClassifyCouponBean returnSuccessAvailiableCoupons(Set<String> couponCodes, boolean hasGoodsCoupon, ActivityClassifyCouponBean availableCouponResponseVo, List<ActivityCouponBean> usableCoupons,
                                                                      List<ActivityCouponBean> disableCoupons, Map<String, GetMemberCouponListResponseDto.Result.MemberCoupon> memberCouponMap,
                                                                      List<CouponStateVo> couponStateList, String chooseCouponCode) {
        int disableCouponNum = 0;
        int usableCouponNum = 0;
        for (CouponStateVo couponStateVo : couponStateList) {
            // 过滤0得代金券
            if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_1.getCode())
                    && (couponStateVo.getOriginalPrice() == null
                    || couponStateVo.getOriginalPrice() == 0)) {
                continue;
            }

            // 过滤折扣券为0折得
            if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_3.getCode())
                    && (couponStateVo.getDiscount() == null
                    || couponStateVo.getDiscount() == 0)) {
                continue;
            }
            ActivityCouponBean activityCouponBean = new ActivityCouponBean();
            activityCouponBean.setCouponCode(couponStateVo.getCouponCode());
            GetMemberCouponListResponseDto.Result.MemberCoupon memberCoupon = memberCouponMap.get(couponStateVo.getCouponCode());
            if (memberCoupon != null) {
                activityCouponBean.setCouponName(memberCoupon.getCouponName());
                activityCouponBean.setEndTime(memberCoupon.getEndTime());
                if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_1.getCode())) {
                    activityCouponBean.setDiscountAmount(couponStateVo.getOriginalPrice() + "");
                } else if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_3.getCode())) {
                    // TODO 折扣券 百分值10 乘以10   前端统一除以100作为操作依据
                    activityCouponBean.setDiscountAmount(couponStateVo.getDiscount() != null ? couponStateVo.getDiscount() * 10 + "" : "0");
                }else if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_5.getCode())) {
                    // 这里需要加入 配送券逻辑  如果为null 表示 配送券金额 全免, 否则就是部分减免
                    activityCouponBean.setDiscountAmount(couponStateVo.getOriginalPrice()==null ? null : couponStateVo.getOriginalPrice()+"");
                }


                activityCouponBean.setThresholdDesc("满" + formatAmount((couponStateVo.getMinAmount() == null ? 0 : couponStateVo.getMinAmount()) * 1.00 / 100) + "元可用");
                activityCouponBean.setActivityDesc("不与其他活动优惠同时享受。");
                if (StringUtils.isNotBlank(couponStateVo.getMessage())){
                    String[] split = couponStateVo.getMessage().split(",");
                    if(split != null && split.length > 0){
                        activityCouponBean.setUnusedReason(split[0]);
                    } else {
                        activityCouponBean.setUnusedReason(couponStateVo.getMessage());
                    }
                } else {
                    activityCouponBean.setUnusedReason(couponStateVo.getMessage());
                }
                // 详情
                GetMemberCouponListResponseVo.MemberCouponDetail detail = new GetMemberCouponListResponseVo.MemberCouponDetail();
                detail.setActivityName(memberCoupon.getCouponName());
                String startDate = DateUtil.convert2String(DateUtil.convert2Date(memberCoupon.getStartTime(), DateUtil.FORMAT_yyyyMMdd_date), DateUtil.FORMAT_yyyyMMdd_date).replace("-", ".");
                String endDate = DateUtil.convert2String(DateUtil.convert2Date(memberCoupon.getEndTime(), DateUtil.FORMAT_yyyyMMdd_date), DateUtil.FORMAT_yyyyMMdd_date).replace("-", ".");
                detail.setEndTime(endDate);
                detail.setStartTime(startDate);
                String remark = memberCoupon.getActiveDesc();
                detail.setRemark(couponAdapter.getDescribeText(remark));
                if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_1.getCode())) {
                    detail.setAmountDesc("满" + formatAmount((couponStateVo.getMinAmount() == null ? 0 : couponStateVo.getMinAmount()) * 1.00 / 100) + "元减" + formatAmount((couponStateVo.getOriginalPrice() == null ? 0 : couponStateVo.getOriginalPrice()) * 1.00 / 100) + "元");
                } else if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_3.getCode())) {
                    detail.setAmountDesc("满" + formatAmount((couponStateVo.getMinAmount() == null ? 0 : couponStateVo.getMinAmount()) * 1.00 / 100) + "元" + formatAmount((couponStateVo.getDiscount() == null ? 0 : couponStateVo.getDiscount()) * 1.00 / 10) + "折");
                }
                // 设置条形码
                GetCouponBarCodeResponseVo responseVo = this.getCouponBarCode(couponStateVo.getCouponCode());
                detail.setCouponBarCode(responseVo.getBase64Image());

                activityCouponBean.setDetail(detail);
                activityCouponBean.setActivityCode(memberCoupon.getActivityCode());
                activityCouponBean.setCouponType(couponStateVo.getType());
                activityCouponBean.setDateDescribe(couponAdapter.getDateDescribe(memberCoupon.getStatus(), memberCoupon.getStartTime(), memberCoupon.getEndTime()));
                activityCouponBean.setCouponPic(memberCoupon.getLogo());
                if (couponStateVo.getDailyAvailableTimes() == null && couponStateVo.getAvailableTimes() != null){
                    activityCouponBean.setDailyAvailableTimes(couponStateVo.getAvailableTimes());
                } else {
                    activityCouponBean.setDailyAvailableTimes(couponStateVo.getDailyAvailableTimes());
                }
                // 券状态 0 可用 1 不可用 2 限制可用
                if (couponCodes.contains(activityCouponBean.getCouponCode())) {
                    activityCouponBean.setSelected(YesOrNoEnum.YES.getCode());
                } else {
                    activityCouponBean.setSelected(YesOrNoEnum.NO.getCode());
                }
                if (hasGoodsCoupon) {
                    if (StringUtils.isNotBlank(chooseCouponCode) && chooseCouponCode.equals(activityCouponBean.getCouponCode())){
                        activityCouponBean.setSelected(YesOrNoEnum.YES.getCode());
                        usableCoupons.add(activityCouponBean);
                        usableCouponNum = usableCouponNum + 1;
                    } else {
                        if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_0.getCode()) || Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_4.getCode())){
                            activityCouponBean.setUnusedReason("商品券只能在点餐页");
                        }
                        disableCoupons.add(activityCouponBean);
                        disableCouponNum = disableCouponNum + 1;
                    }
                } else {
                    if (Objects.equals(couponStateVo.getState(), CouponStateEnum.STATE_1.getCode()) || (activityCouponBean.getDailyAvailableTimes() != null && activityCouponBean.getDailyAvailableTimes() == 0)) {
                        if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_0.getCode()) || Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_4.getCode())){
                            activityCouponBean.setUnusedReason("商品券只能在点餐页");
                        }
                        disableCoupons.add(activityCouponBean);
                        disableCouponNum = disableCouponNum + 1;
                    } else if (Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_0.getCode()) || Objects.equals(couponStateVo.getType(), CouponTypeEnum.TYPE_4.getCode())) {
                        activityCouponBean.setUnusedReason("商品券只能在点餐页");
                        disableCoupons.add(activityCouponBean);
                        disableCouponNum = disableCouponNum + 1;
                    } else {
                        usableCoupons.add(activityCouponBean);
                        usableCouponNum = usableCouponNum + 1;
                    }
                }
            }

        }
        availableCouponResponseVo.setCouponNum(disableCouponNum + usableCouponNum);
        availableCouponResponseVo.setDisableCouponNum(disableCouponNum);
        availableCouponResponseVo.setUsableCouponNum(usableCouponNum);
        availableCouponResponseVo.setDisableCoupons(disableCoupons);
        availableCouponResponseVo.setUsableCoupons(usableCoupons);
        return availableCouponResponseVo;
    }

    private Long createProductRequest(List<CartGoods> cartGoods, List<Product> productList, int isNew) {
        Long totalAmount = 0L;

        if (isNew == 1) {
            for (CartGoods cartGood : cartGoods) {
                // 剔除商品券得商品
                if (StringUtils.isEmpty(cartGood.getSkuId()) && StringUtils.isEmpty(cartGood.getSpuId())) {
                    continue;
                }
                Product product = new Product();
                product.setProductId(StringUtils.isEmpty(cartGood.getSkuId()) ? cartGood.getSpuId() : cartGood.getSkuId());
                // 普通商品价格
                Integer currentCouponDiscount = cartGood.getCurrentCouponDiscount() != null ? cartGood.getCurrentCouponDiscount() : 0;
                product.setAmount(cartGood.getAmount().intValue() + currentCouponDiscount);
                totalAmount = totalAmount + product.getAmount();
                // todo ：小料价格累加到主商品上
                if (CollectionUtils.isNotEmpty(cartGood.getProductMaterialList())) {
                    for (CartGoods.MaterialGoods materialGoods : cartGood.getProductMaterialList()) {
                        Integer materialCurrentCouponDiscount = materialGoods.getCurrentCouponDiscount() != null ? materialGoods.getCurrentCouponDiscount() : 0;
                        product.setAmount(product.getAmount() + materialGoods.getAmount().intValue() + materialCurrentCouponDiscount);
                        totalAmount = totalAmount + materialGoods.getAmount() + materialCurrentCouponDiscount;
                    }
                }
                // 可选搭配优惠累加到主商品上
                if (CollectionUtils.isNotEmpty(cartGood.getProductGroupList())) {
                    for (CartGoods.ComboxGoods comboxGoods : cartGood.getProductGroupList()) {
                        Integer comboxCurrentCouponDiscount = comboxGoods.getCurrentCouponDiscount() != null ? comboxGoods.getCurrentCouponDiscount() : 0;
                        totalAmount = totalAmount + comboxCurrentCouponDiscount;
                    }
                }
                // 数量
                product.setQuantity(1);
                productList.add(product);
            }
        } else {
            for (CartGoods cartGood : cartGoods) {
                // 剔除商品券得商品
                if (StringUtils.isEmpty(cartGood.getSkuId()) && StringUtils.isEmpty(cartGood.getSpuId())) {
                    continue;
                }
                Product product = new Product();
                product.setProductId(StringUtils.isEmpty(cartGood.getSkuId()) ? cartGood.getSpuId() : cartGood.getSkuId());
                // 普通商品价格
                product.setAmount(Integer.valueOf(cartGood.getOriginalPrice() + ""));
                // 套餐价格为： 套餐价+可选商品总价格
                if (ObjectUtils.equals(GoodsTypeEnum.SET_MEAL_GOODS.getGoodsType(), cartGood.getGoodsType())) {
                    //购物车行单价
                    Long finalPrice = cartGood.getFinalPrice();
                    //表示套餐商品选择了可选他陪商品
                    //2.0.31迭代 【C端服务端】老算价-套餐可选搭配商品不计入优惠券金额门槛 wanghanghang 20210520
                    //计算优惠券门槛金额，老算价使用套餐固定搭配实付金额进行校验
//                    if (CollectionUtils.isNotEmpty(cartGood.getProductGroupList())) {
//                        finalPrice += cartGood.getProductGroupList().stream().mapToLong(group -> group.getFinalPrice() * group.getQty()).sum();
//                    }
                    product.setAmount(finalPrice.intValue());
                }

                totalAmount = totalAmount + product.getAmount() * cartGood.getQty();
                // todo ：小料价格累加到主商品上
                if (CollectionUtils.isNotEmpty(cartGood.getProductMaterialList())) {
                    for (CartGoods.MaterialGoods materialGoods : cartGood.getProductMaterialList()) {
                        product.setAmount(product.getAmount() + Integer.valueOf(materialGoods.getOriginalPrice() * materialGoods.getQty() * cartGood.getQty() + ""));
                        totalAmount = totalAmount + materialGoods.getOriginalPrice() * materialGoods.getQty() * cartGood.getQty();
                    }
                }
                // 数量
                product.setQuantity(cartGood.getQty());
                productList.add(product);
            }
        }
        return totalAmount;
    }

    private ActivityClassifyCouponBean returnEmptyAvailableCoupon(ActivityClassifyCouponBean availableCouponResponseVo, List<ActivityCouponBean> usableCoupons, List<ActivityCouponBean> disableCoupons) {
        availableCouponResponseVo.setCouponNum(0);
        availableCouponResponseVo.setDisableCouponNum(0);
        availableCouponResponseVo.setUsableCouponNum(0);
        availableCouponResponseVo.setDisableCoupons(disableCoupons);
        availableCouponResponseVo.setUsableCoupons(usableCoupons);
        return availableCouponResponseVo;
    }

    private static Object formatAmount(Double amount) {
        if (amount % (amount.intValue()) == 0.0) {
            return amount.intValue();
        } else {
            return amount;
        }
    }

    /**
     * 老版本券校验
     */
    public CheckSpqInfoResponseDto checkSpqInfo(CheckSpqInfoRequestDto requestDto) {
        String partnerId = requestDto.getPartnerId();
        String couponCode = requestDto.getCouponCode();
        String storeId = requestDto.getStoreId();
        //TODO 查询券详情券是否存在
        GetMemberCouponRequestVo requestVo = new GetMemberCouponRequestVo();
        requestVo.setPartnerId(partnerId);
        requestVo.setCouponCode(couponCode);
        requestVo.setStoreId(requestDto.getStoreId());
        requestVo.setCheckStoreId(true);
        GetCouponDetailResponseDto couponDetailResponseDto = this.getMemberCoupon(requestVo);
        if (couponDetailResponseDto == null || !couponDetailResponseDto.getResult().equals(ResponseCodeConstant.RESPONSE_SUCCESS_1) || CollectionUtils.isEmpty(couponDetailResponseDto.getDetails())) {
            return null;
        }
        //校验商品券是否可用
        if (!Objects.equals(couponDetailResponseDto.getDetails().get(0).getStatus(), CouponStatus.STATUS_0.getCode())
                && !Objects.equals(couponDetailResponseDto.getDetails().get(0).getStatus(), CouponStatus.STATUS_2.getCode())) {
            return null;
        }
//        List<String> couPonstoreIds = Lists.newArrayList();
        //TODO 判断该券是否在这个门店下(一个券可以在多个门店下使用)
        if (CollectionUtils.isNotEmpty(couponDetailResponseDto.getDetails().get(0).getActiveRestrictionVOS())) {
//            couponDetailResponseDto.getDetails().get(0).getActiveRestrictionVOS().forEach(activeRestrictionVOS -> {
//                couPonstoreIds.add(activeRestrictionVOS.getStoreIdPartner());
//            });
            GetCouponDetailResponseDto.Details detail = couponDetailResponseDto.getDetails().get(0);
            if (detail.getStorelimit() != 0 || detail.getStoreChannelLimit() != 0) {
                return null;
            }
        }
//        if (CollectionUtils.isNotEmpty(couPonstoreIds) && !couPonstoreIds.contains(storeId)) {
//            return null;
//        }
        //券返回的商品id
        List<String> skuIds = Lists.newArrayList();
        String skuId = couponDetailResponseDto.getDetails().get(0).getActiveProduct().get(0).getProductIdPartner();
        skuIds.add(String.valueOf(skuId));
        //TODO 通过skuid查询spuid
        Map<String, GetProductsVo> productsVoMap = itemService.getProducts(skuIds, partnerId, storeId , requestDto.getMenuType());
        GetProductsVo productsVo = productsVoMap.get(skuId);
        if (null == productsVo || !Objects.equals(productsVo.getStatus(), StoreItemStatus.PUT_ON_SALE.getCode())) {
            return null;
        }
        // 校验券的可用时间
        List<GetCouponDetailResponseDto.ActiveRedeemTimeInterval> activeRedeemTimeIntervalList = couponDetailResponseDto.getDetails().get(0).getActiveRedeemTimeIntervalList();
        boolean verificationPassed = checkCouonRedeemTime(activeRedeemTimeIntervalList);
        if (!verificationPassed){
            return null;
        }
        // 校验商品可用时间
        ValidateShopProductRequest request = getValidateShopProductRequest(productsVo, requestDto);
        ProductBaseResponse<ValiadShopProductResponse> valiadProductResponse = storeItemClient.validateShopProduct(request);
        if (null == valiadProductResponse || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, valiadProductResponse.getErrcode())
                || valiadProductResponse.getData() == null || CollectionUtils.isEmpty(valiadProductResponse.getData().getSuccessList())) {
            return null;
        }
        CheckSpqInfoResponseDto dto = new CheckSpqInfoResponseDto();
        dto.setCouponCode(couponCode);
        dto.setActiveCode(couponDetailResponseDto.getDetails().get(0).getActive().getActiveCode());
        dto.setCouponName(couponDetailResponseDto.getDetails().get(0).getTitle());
        dto.setActivityName(couponDetailResponseDto.getDetails().get(0).getActive().getActiveName());
        if (couponDetailResponseDto.getDetails().get(0).getActive().getMaxRedeemTimes() != null && couponDetailResponseDto.getDetails().get(0).getActive().getMaxRedeemTimes() > 1){
            if (couponDetailResponseDto.getDetails().get(0).getToday_available_times() != null){
                dto.setTodayAvailableTimes(couponDetailResponseDto.getDetails().get(0).getToday_available_times());
            } else {
                dto.setTodayAvailableTimes(1);
            }
        } else {
            dto.setTodayAvailableTimes(1);
        }
        dto.setPrice(productsVo.getFinalPrice());
        //套餐商品券优惠金额处理
        if(requestDto.getAddCartGoods() != null && CollectionUtils.isNotEmpty(requestDto.getAddCartGoods().getProductComboList())){
            dto.setPrice(productsVo.getOriginalPrice());
        }
        dto.setSpuId(productsVo.getSpuId());
        dto.setSpuName(productsVo.getSkuName());
        dto.setStockLimit(ObjectUtils.equals(1, productsVo.getStockLimit()));
        dto.setSkuId(productsVo.getSkuId());
        dto.setSkuName(StringUtils.isNotBlank(productsVo.getSkuName()) ? productsVo.getSkuName() : productsVo.getSpuName());
        dto.setPicture(productsVo.getSpuPicture());
        dto.setCouponType(0);
        return dto;
    }


    private boolean checkCouonRedeemTime(List<GetCouponDetailResponseDto.ActiveRedeemTimeInterval> activeRedeemTimeIntervalList) {
        boolean verificationPassed = false;
        if (CollectionUtils.isNotEmpty(activeRedeemTimeIntervalList)){
            for (GetCouponDetailResponseDto.ActiveRedeemTimeInterval dateLimit : activeRedeemTimeIntervalList){
                boolean dayCheck = true;
                String weekday = dateLimit.getWeekday(); // 日期限制 0011100 周日开始,0表示不可用
                if (StringUtils.isNotBlank(weekday)){ // 存在校验周几
                    char[] chars = weekday.toCharArray();
                    int dayOfWeek = LocalDate.now().getDayOfWeek().getValue();  // 从周一开始
                    if (dayOfWeek == 7){
                        dayOfWeek = 0;
                    }
                    if (Integer.parseInt(String.valueOf(chars[dayOfWeek])) == 0){ //限制
                        dayCheck = false;
                    }
                }
                boolean timeCheck = true;
                String begintime = dateLimit.getBegintime(); // 开始时间  00:00:00
                String endtime = dateLimit.getEndtime();  // 结束时间 12:59:59
                if (StringUtils.isNotBlank(begintime) && StringUtils.isNotBlank(endtime)){ // 存在校验时段
                    String[] beginTimeArr = begintime.split(":");
                    String[] endTimeArr = endtime.split(":");
                    LocalTime beginLocalTime = LocalTime.of(Integer.valueOf(beginTimeArr[0]), Integer.valueOf(beginTimeArr[1]), Integer.valueOf(beginTimeArr[2]));
                    LocalTime endLocalTime = LocalTime.of(Integer.valueOf(endTimeArr[0]), Integer.valueOf(endTimeArr[1]), Integer.valueOf(endTimeArr[2]));
                    LocalTime now = LocalTime.now();
                    if (now.isBefore(beginLocalTime) || now.isAfter(endLocalTime)){
                        timeCheck = false;
                    }
                }
                if (dayCheck && timeCheck){
                    verificationPassed = true;
                    break;
                }
            }
        } else {
            verificationPassed = true;
        }
        return verificationPassed;

    }

    private ValidateShopProductRequest getValidateShopProductRequest(GetProductsVo product, CheckSpqInfoRequestDto requestDto) {
        ValidateShopProductRequest request = new ValidateShopProductRequest();
        request.setChannel(requestDto.getMenuType());
        request.setPartnerId(requestDto.getPartnerId());
        request.setStoreId(requestDto.getStoreId());
        List<ValidateShopProductType> productTypeList = new ArrayList<>();
        ValidateShopProductType productType = new ValidateShopProductType();

        productType.setAttributeList(null);
        productType.setMemberDiscount(null);
        productType.setPrice(product.getFinalPrice().intValue());
        productType.setProductGroupTypeList(null);
        productType.setSkuId(product.getSkuId());
        productType.setSpuId(product.getSpuId());
        productType.setUuid(UUID.randomUUID().toString());
        productType.setValidateAttribute(0);
        productType.setValidatePrice(0);
        productType.setValidateStatuses(null);

        if(requestDto.getAddCartGoods() != null && CollectionUtils.isNotEmpty(requestDto.getAddCartGoods().getProductComboList())){
            List<ValidateSkuProductType> comboProductTypeList = new ArrayList<>();
            for (CartGoods.ComboxGoods comboxGoods : requestDto.getAddCartGoods().getProductComboList()){
                ValidateSkuProductType validateSkuProductType = new ValidateSkuProductType();
                validateSkuProductType.setProductId(comboxGoods.getSkuId());
                validateSkuProductType.setQty(comboxGoods.getQty());
                if(CollectionUtils.isNotEmpty(comboxGoods.getExtra())){
                    List<ProductAttributeValueType> attributeList = new ArrayList<>();
                    for (CartGoods.CartGoodsExtra extra : comboxGoods.getExtra()){
                        ProductAttributeValueType productAttributeValueType = new ProductAttributeValueType();
                        productAttributeValueType.setAttributeId(extra.getAttributeId());
                        productAttributeValueType.setAttributeValue(extra.getAttributeName());
                        attributeList.add(productAttributeValueType);
                    }
                    validateSkuProductType.setAttributeList(attributeList);
                }
                comboProductTypeList.add(validateSkuProductType);
            }
            productType.setComboProductTypeList(comboProductTypeList);
            productType.setIsCouponMarkUpSetMeal(1);
            productType.setPrice(product.getOriginalPrice().intValue());
        }

        productTypeList.add(productType);
        request.setProductTypeList(productTypeList);
        return  request;

    }

    /**
     * 换购券
     * 商品券支持多商品
     *
     * @param requestDto
     * @param goodsId
     * @return
     */
    @Override
    public CheckSpqInfoResponseDto checkSpqInfo(CheckSpqInfoRequestDto requestDto, String goodsId) {
        //老版本商品券校验
        if(StringUtils.isEmpty(goodsId)){
            return checkSpqInfo(requestDto);
        }
        String partnerId = requestDto.getPartnerId();
        String couponCode = requestDto.getCouponCode();
        String storeId = requestDto.getStoreId();
        //TODO 查询券详情券是否存在
        GetMemberCouponRequestVo requestVo = new GetMemberCouponRequestVo();
        requestVo.setPartnerId(partnerId);
        requestVo.setCouponCode(couponCode);
        requestVo.setStoreId(requestDto.getStoreId());
        requestVo.setCheckStoreId(true);
        GetCouponDetailResponseDto couponDetailResponseDto = this.getMemberCoupon(requestVo);
        if (couponDetailResponseDto == null || !couponDetailResponseDto.getResult().equals(ResponseCodeConstant.RESPONSE_SUCCESS_1) || CollectionUtils.isEmpty(couponDetailResponseDto.getDetails())) {
            return null;
        }
        boolean productValid = false;
        Integer couponType = 0;
        GetCouponDetailResponseDto.Details couponActivityDetail = null;
        for (GetCouponDetailResponseDto.Details detail : couponDetailResponseDto.getDetails()) {
            if (productValid) break;
            if (!CouponStatus.STATUS_0.getCode().equals(detail.getStatus()) && !CouponStatus.STATUS_2.getCode().equals(detail.getStatus())) continue;
            if(CouponTypeEnum.TYPE_0.getCode().equals(detail.getType()) && Integer.valueOf(1).equals(detail.getSubType())) {
                //黑名单商品券处理
                for (GetCouponDetailResponseDto.ActiveProduct activeProduct : detail.getActiveProduct()) {
                    if (goodsId.equals(activeProduct.getProductIdPartner())) {
                        throw new ServiceException(ResponseResult.SHOPPING_CART_COUPON_NOT_EXIST, "加购商品在商品券商品黑名单中。");
                    }
                }
                productValid = true;
                couponActivityDetail = detail;
                couponType = CouponTypeEnum.TYPE_4.getCode();
            } else {
                for (GetCouponDetailResponseDto.ActiveProduct activeProduct : detail.getActiveProduct()) {
                    if (goodsId.equals(activeProduct.getProductIdPartner())) {
                        productValid = true;
                        couponActivityDetail = detail;
                        couponType = CouponTypeEnum.TYPE_4.getCode();
                        break;
                    }
                }
            }
            if(CouponTypeEnum.TYPE_7.getCode().equals(detail.getType())){
                for (GetCouponDetailResponseDto.ActiveProduct activeProduct : detail.getActiveProduct()) {
                    if (goodsId.equals(activeProduct.getProductIdPartner())) {
                        productValid = true;
                        couponActivityDetail = detail;
                        couponType = CouponTypeEnum.TYPE_7.getCode();
                        break;
                    }
                }
            }
        }
        //检查商品是否有效
        if (!productValid) {
            return null;
        }
        //判断该券是否在这个门店下(一个券可以在多个门店下使用)
//        List<String> couponStoreIds = Lists.newArrayList();
        for (GetCouponDetailResponseDto.Details detail : couponDetailResponseDto.getDetails()) {
            if (!CouponStatus.STATUS_0.getCode().equals(detail.getStatus()) && !CouponStatus.STATUS_2.getCode().equals(detail.getStatus())) continue;
//            for (GetCouponDetailResponseDto.ActiveRestrictionVOS activeRestrictionVO : detail.getActiveRestrictionVOS()) {
//                couponStoreIds.add(activeRestrictionVO.getStoreIdPartner());
//            }
            if (detail.getStorelimit() != 0 || detail.getStoreChannelLimit() != 0) {
                return null;
            }
        }

        //券返回的商品id
        List<String> skuIds = Lists.newArrayList();
        String skuId = goodsId;
        skuIds.add(skuId);
        //通过skuid查询spuid
        Map<String, GetProductsVo> productsVoMap = itemService.getProducts(skuIds, partnerId, storeId, requestDto.getMenuType());
        GetProductsVo productsVo = productsVoMap.get(skuId);
        if (null == productsVo || !Objects.equals(productsVo.getStatus(), StoreItemStatus.PUT_ON_SALE.getCode())) {
            return null;
        }
        // 校验券的可用时间
        List<GetCouponDetailResponseDto.ActiveRedeemTimeInterval> activeRedeemTimeIntervalList = couponDetailResponseDto.getDetails().get(0).getActiveRedeemTimeIntervalList();
        boolean verificationPassed = checkCouonRedeemTime(activeRedeemTimeIntervalList);
        if (!verificationPassed){
            return null;
        }
        // 校验商品可用时间
        ValidateShopProductRequest request = getValidateShopProductRequest(productsVo, requestDto);
        ProductBaseResponse<ValiadShopProductResponse> valiadProductResponse = storeItemClient.validateShopProduct(request);
        if (null == valiadProductResponse || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, valiadProductResponse.getErrcode())
                || valiadProductResponse.getData() == null || CollectionUtils.isEmpty(valiadProductResponse.getData().getSuccessList())) {
            return null;
        }
        CheckSpqInfoResponseDto dto = new CheckSpqInfoResponseDto();
        if (couponDetailResponseDto.getDetails().get(0).getActive().getMaxRedeemTimes() != null && couponDetailResponseDto.getDetails().get(0).getActive().getMaxRedeemTimes() > 1){
            if (couponDetailResponseDto.getDetails().get(0).getToday_available_times() != null){
                dto.setTodayAvailableTimes(couponDetailResponseDto.getDetails().get(0).getToday_available_times());
            } else {
                dto.setTodayAvailableTimes(1);
            }
        } else {
            dto.setTodayAvailableTimes(1);
        }
        dto.setCouponCode(couponCode);
        dto.setActiveCode(couponActivityDetail.getActive().getActiveCode());
        dto.setCouponName(couponActivityDetail.getTitle());
        dto.setActivityName(couponActivityDetail.getActive().getActiveName());
        dto.setSpuId(productsVo.getSpuId());
        dto.setSpuName(productsVo.getSkuName());
        dto.setSkuId(productsVo.getSkuId());
        dto.setSkuName(StringUtils.isNotBlank(productsVo.getSkuName()) ? productsVo.getSkuName() : productsVo.getSpuName());
        dto.setPicture(productsVo.getSpuPicture());
        dto.setDefaultSpecName(productsVo.getDefaultSpecName());
        dto.setDefaultSpecId(productsVo.getDefaultSpecId());
        dto.setStockLimit(ObjectUtils.equals(1, productsVo.getStockLimit()));
        dto.setExtras(productsVo.getExtra());
        dto.setCouponType(couponType);
        dto.setPrice(productsVo.getFinalPrice());
        //套餐商品券优惠金额处理
        if(requestDto.getAddCartGoods() != null && CollectionUtils.isNotEmpty(requestDto.getAddCartGoods().getProductComboList())){
            dto.setPrice(productsVo.getOriginalPrice());
        }

        List<ValiadShopProductResult> successList = valiadProductResponse.getData().getSuccessList();
        dto.setProductBeans(successList.get(0).getProductType());
        return dto;
    }

    @Override
    public GetProductsVo getSpqProductInfo(CheckSpqInfoRequestDto requestDto) {
        return this.getSpqProductInfo(requestDto,null);
    }


    /**
     * 换购券
     * 商品券支持多商品
     *
     * @param requestDto
     * @param goodsId
     * @return
     */
    @Override
    public GetProductsVo getSpqProductInfo(CheckSpqInfoRequestDto requestDto, String goodsId) {
        String partnerId = requestDto.getPartnerId();
        String couponCode = requestDto.getCouponCode();
        String storeId = requestDto.getStoreId();
        //TODO 查询券详情券是否存在
        GetMemberCouponRequestVo requestVo = new GetMemberCouponRequestVo();
        requestVo.setPartnerId(partnerId);
        requestVo.setCouponCode(couponCode);
        requestVo.setStoreId(requestDto.getStoreId());
        GetCouponDetailResponseDto couponDetailResponseDto = this.getMemberCoupon(requestVo);
        if (couponDetailResponseDto == null || !couponDetailResponseDto.getResult().equals(ResponseCodeConstant.RESPONSE_SUCCESS_1) || CollectionUtils.isEmpty(couponDetailResponseDto.getDetails())) {
            return null;
        }

        if (CollectionUtils.isEmpty(couponDetailResponseDto.getDetails())) {
            return null;
        }
        //券返回的商品id
        String skuId ;
        List<String> skuIds = Lists.newArrayList();
        if (StringUtils.isEmpty(goodsId)) {
            if(CouponTypeEnum.TYPE_0.getCode().equals(couponDetailResponseDto.getDetails().get(0).getType())
                    && Integer.valueOf(1).equals(couponDetailResponseDto.getDetails().get(0).getSubType())) {
                throw new ServiceException(ResponseResult.SHOPPING_CART_PRODUCT_CAN_NOT_USE, "老版本不支持商品券黑名单商品，请升级小程序。");
            }
            //券返回的商品id
            skuId = couponDetailResponseDto.getDetails().get(0).getActiveProduct().get(0).getProductIdPartner();
            skuIds.add(String.valueOf(skuId));
        }else {
            skuId = goodsId;
        }
        skuIds.add(skuId);
        //TODO 通过skuid查询spuid
        Map<String, GetProductsVo> productsVoMap = itemService.getProducts(skuIds, partnerId, storeId, requestDto.getMenuType());
        GetProductsVo productsVo = productsVoMap.get(skuId);
        if (null == productsVo || !Objects.equals(productsVo.getStatus(), StoreItemStatus.PUT_ON_SALE.getCode())) {
            return null;
        }

        // 校验商品可用时间
        ValidateShopProductRequest request = getValidateShopProductRequest(productsVo, requestDto);
        ProductBaseResponse<ValiadShopProductResponse> valiadProductResponse = storeItemClient.validateShopProduct(request);
        if (null == valiadProductResponse || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, valiadProductResponse.getErrcode())
                || valiadProductResponse.getData() == null || CollectionUtils.isEmpty(valiadProductResponse.getData().getSuccessList())) {
            return null;
        }

        return productsVo;
    }

    @Override
    public GetCouponBarCodeResponseVo getCouponBarCode(String couponCode) {
        byte[] bytes = BarcodeUtil.generateBarCode128(couponCode, 6D, null, true, false);
        String base64Image = Base64.getEncoder().encodeToString(bytes);
        String base64Prefix = "data:image/png;base64,";
        GetCouponBarCodeResponseVo getCouponBarCodeResponseVo = new GetCouponBarCodeResponseVo();
        getCouponBarCodeResponseVo.setBase64Image(base64Prefix + base64Image);
        return getCouponBarCodeResponseVo;
    }


    public CheckSpqInfoResponseDto checkSpqInfo(CheckSpqInfoRequestDto requestDto, String goodsId,Integer goodsType) {
        String partnerId = requestDto.getPartnerId();
        String couponCode = requestDto.getCouponCode();
        String storeId = requestDto.getStoreId();
        //TODO 查询券详情券是否存在
        GetMemberCouponRequestVo requestVo = new GetMemberCouponRequestVo();
        requestVo.setPartnerId(partnerId);
        requestVo.setCouponCode(couponCode);
        requestVo.setStoreId(requestDto.getStoreId());
        GetCouponDetailResponseDto couponDetailResponseDto = this.getMemberCoupon(requestVo);
        if (couponDetailResponseDto == null || !couponDetailResponseDto.getResult().equals(ResponseCodeConstant.RESPONSE_SUCCESS_1) || CollectionUtils.isEmpty(couponDetailResponseDto.getDetails())) {
            return null;
        }
        GetCouponDetailResponseDto.Details details = couponDetailResponseDto.getDetails().get(0);
        //校验商品券是否可用
        if (!Objects.equals(details.getStatus(), CouponStatus.STATUS_0.getCode())
                && !Objects.equals(details.getStatus(), CouponStatus.STATUS_2.getCode())) {
            return null;
        }
        List<String> couPonstoreIds = Lists.newArrayList();
        //TODO 判断该券是否在这个门店下(一个券可以在多个门店下使用)
        if (CollectionUtils.isNotEmpty(details.getActiveRestrictionVOS())) {
            details.getActiveRestrictionVOS().forEach(activeRestrictionVOS -> {
                couPonstoreIds.add(activeRestrictionVOS.getStoreIdPartner());
            });
        }
        if (CollectionUtils.isNotEmpty(couPonstoreIds) && !couPonstoreIds.contains(storeId)) {
            return null;
        }
        //券返回的商品id
        List<String> skuIds = Lists.newArrayList();
        String skuId = details.getActiveProduct().get(0).getProductIdPartner();
        skuIds.add(String.valueOf(skuId));
        //TODO 通过skuid查询spuid
        Map<String, GetProductsVo> productsVoMap = itemService.getProducts(skuIds, partnerId, storeId , requestDto.getMenuType());
        GetProductsVo productsVo = productsVoMap.get(skuId);
        if (null == productsVo || !Objects.equals(productsVo.getStatus(), StoreItemStatus.PUT_ON_SALE.getCode())) {
            return null;
        }
        // 校验券的可用时间
        List<GetCouponDetailResponseDto.ActiveRedeemTimeInterval> activeRedeemTimeIntervalList = details.getActiveRedeemTimeIntervalList();
        boolean verificationPassed = checkCouonRedeemTime(activeRedeemTimeIntervalList);
        if (!verificationPassed){
            return null;
        }
        // 校验商品可用时间
        ValidateShopProductRequest request = getValidateShopProductRequest(productsVo, requestDto);
        ProductBaseResponse<ValiadShopProductResponse> valiadProductResponse = storeItemClient.validateShopProduct(request);
        if (null == valiadProductResponse || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, valiadProductResponse.getErrcode())
                || valiadProductResponse.getData() == null || CollectionUtils.isEmpty(valiadProductResponse.getData().getSuccessList())) {
            return null;
        }

        boolean productValid = false;
        Integer couponType = 0;
        for (GetCouponDetailResponseDto.Details detail : couponDetailResponseDto.getDetails()) {
            if (productValid) break;
            if (!CouponStatus.STATUS_0.getCode().equals(detail.getStatus()) && !CouponStatus.STATUS_2.getCode().equals(detail.getStatus())) continue;
            for (GetCouponDetailResponseDto.ActiveProduct activeProduct : detail.getActiveProduct()) {
                if (goodsId.equals(activeProduct.getProductIdPartner())) {
                    productValid = true;
                    couponType = CouponTypeEnum.TYPE_4.getCode();
                    break;
                }
            }
            if(CouponTypeEnum.TYPE_7.getCode().equals(detail.getType())){
                for (GetCouponDetailResponseDto.ActiveProduct activeProduct : detail.getActiveProduct()) {
                    if (goodsId.equals(activeProduct.getProductIdPartner())) {
                        productValid = true;
                        couponType = CouponTypeEnum.TYPE_7.getCode();
                        break;
                    }
                }
            }
        }
        //检查商品是否有效
        if (!productValid) {
            return null;
        }
        //判断该券是否在这个门店下(一个券可以在多个门店下使用)
        List<String> couponStoreIds = Lists.newArrayList();
        for (GetCouponDetailResponseDto.Details detail : couponDetailResponseDto.getDetails()) {
            if (!CouponStatus.STATUS_0.getCode().equals(detail.getStatus()) && !CouponStatus.STATUS_2.getCode().equals(detail.getStatus())) continue;
            for (GetCouponDetailResponseDto.ActiveRestrictionVOS activeRestrictionVO : detail.getActiveRestrictionVOS()) {
                couponStoreIds.add(activeRestrictionVO.getStoreIdPartner());
            }
        }
        if (CollectionUtils.isNotEmpty(couponStoreIds) && !couponStoreIds.contains(storeId)) {
            return null;
        }
        CheckSpqInfoResponseDto dto = new CheckSpqInfoResponseDto();
        if (details.getActive().getMaxRedeemTimes() != null && details.getActive().getMaxRedeemTimes() > 1){
            if (details.getToday_available_times() != null){
                dto.setTodayAvailableTimes(details.getToday_available_times());
            } else {
                dto.setTodayAvailableTimes(1);
            }
        } else {
            dto.setTodayAvailableTimes(1);
        }
        dto.setCouponCode(couponCode);
        dto.setActiveCode(details.getActive().getActiveCode());
        dto.setCouponName(details.getTitle());
        dto.setActivityName(details.getActive().getActiveName());
        dto.setPrice(productsVo.getFinalPrice());
        dto.setSpuId(productsVo.getSpuId());
        dto.setSpuName(productsVo.getSkuName());
        dto.setSkuId(productsVo.getSkuId());
        dto.setSkuName(StringUtils.isNotBlank(productsVo.getSkuName()) ? productsVo.getSkuName() : productsVo.getSpuName());
        dto.setPicture(productsVo.getSpuPicture());
        dto.setDefaultSpecName(productsVo.getDefaultSpecName());
        dto.setDefaultSpecId(productsVo.getDefaultSpecId());
        dto.setStockLimit(ObjectUtils.equals(1, productsVo.getStockLimit()));
        dto.setExtras(productsVo.getExtra());
        dto.setCouponType(couponType);
        return dto;
    }


    /**
     * 批量查询活动详情
     *
     * @param partnerId
     * @param activityCodes
     * @param trackingNo
     * @return
     */
    public List<Active> batchQueryActivityInfo(String partnerId, List<String> activityCodes, String trackingNo) {
        String appSecret = this.getAppSecret(partnerId);
        BatchQueryActivityInfoRequestDto requestDto = new BatchQueryActivityInfoRequestDto();
        requestDto.setActiveCode(activityCodes);
        // 书写逻辑
        requestDto.setPartnerId(Integer.valueOf(partnerId));
        String sign = SignUtil.createMD5Sign(requestDto, appSecret);
        requestDto.setSign(sign);
        BatchQueryActivityInfoResponseDto batchQueryActivityInfoResponseDto = couponOnlineClient.batchQueryActivityInfo(requestDto);
        if (batchQueryActivityInfoResponseDto == null || !Objects.equals(batchQueryActivityInfoResponseDto.getStatusCode(), ResponseCodeConstant.RESPONSE_SUCCESS_0_STR) || CollectionUtils.isEmpty(batchQueryActivityInfoResponseDto.getActivities())) {
            return null;
        }
        return batchQueryActivityInfoResponseDto.getActivities();
    }

}
