package cn.freemud.service.impl;

import cn.freemud.adapter.ShoppingCartConvertAdapter;
import cn.freemud.constant.CustomerScoreConstant;
import cn.freemud.entities.dto.ActivityCalculationDiscountResponseDto;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.dto.user.GetUserScoreUseDetailRequest;
import cn.freemud.entities.dto.user.GetUserScoreUserDetailResponse;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.IPromotionService;
import cn.freemud.service.thirdparty.CustomScoreClient;
import cn.freemud.utils.LogUtil;
import com.freemud.application.sdk.api.constant.FMStatusCode;
import com.freemud.application.sdk.api.log.ErrorLog;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title:
 * @Package: cn.freemud.service.impl
 * @Descripttion:
 * @author: shuhu.hou
 * @date: 2019/5/11
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
@Service
public class CustomerScoreService implements IPromotionService {
    @Autowired
    private CustomScoreClient customScoreClient;

    @Override
    public void updateShoppingCartGoodsDiscount(CouponPromotionVO couponPromotionVO, ActivityQueryDto activityQueryDto, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, List<CartGoods> cartGoodsList, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, UserLoginInfoDto userLoginInfoDto, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (shoppingCartInfoRequestVo == null || shoppingCartInfoRequestVo.getUseCustomerScore() == null || shoppingCartInfoRequestVo.getUseCustomerScore() == null || shoppingCartInfoRequestVo.getUseCustomerScore().equals(CustomerScoreConstant.NO_DISPLAY.getValue())) {
            return;
        }
        GetUserScoreUseDetailRequest request = new GetUserScoreUseDetailRequest();
        request.setMemberId(userLoginInfoDto.getMemberId());
        request.setPaidAmount(getValue(shoppingCartGoodsResponseVo.getTotalAmount()));
        request.setPartnerId(userLoginInfoDto.getPartnerId());
        GetUserScoreUserDetailResponse userScoreUseDetail = null;
        try {
            // 加入try catch是为了custom服务挂掉，购物车服务可以也可以正常
            userScoreUseDetail = customScoreClient.getUserScoreUseDetail(request);
        } catch (Exception ex) {
            ErrorLog.printErrorLog("getUserScoreUseDetailError", "/user/scoreUseDetail", request, ex);
        }
        if (userScoreUseDetail != null && userScoreUseDetail.getCode().equals(FMStatusCode.SUCCESS.getCode()) && userScoreUseDetail.getResult() != null) {
            Integer discountAmount = 0;
            if (CustomerScoreConstant.SUBSTRACT.getValue().equals(shoppingCartInfoRequestVo.getUseCustomerScore())) {
                //设置 购物车总金额=购物车总价-积分扣减金额
                discountAmount = getValue(userScoreUseDetail.getResult().getReduceAmount());
            }
            //设置 积分抵扣VO
            ShoppingCartCustomerScoreVo customerScoreVo = new ShoppingCartCustomerScoreVo();
            customerScoreVo.setCurrentScore(getValue(userScoreUseDetail.getResult().getCurrentScore()));
            customerScoreVo.setReduceAmount(getValue(userScoreUseDetail.getResult().getReduceAmount()));
            customerScoreVo.setReducePriceLimit(getValue(userScoreUseDetail.getResult().getReducePriceLimit()));
            customerScoreVo.setOverlayOffers(userScoreUseDetail.getResult().getOverlayOffers());
            customerScoreVo.setScoreReduceState(getValue(userScoreUseDetail.getResult().getScoreState()));
            // 是否可优惠同享{0所有订单均可抵扣,1仅限原价订单才可抵扣（享受了促销活动、或使用了优惠券，不能进行积分抵扣
            if (getValue(userScoreUseDetail.getResult().getOverlayOffers()) == 0) {
                customerScoreVo.setScoreReduceState(getValue(userScoreUseDetail.getResult().getScoreState()));
            } else {
                if (StringUtils.isNotBlank(shoppingCartInfoRequestVo.getCouponCode()) || (calculationDiscountResult != null && calculationDiscountResult.getTotalDiscountAmount().intValue() > 0)
                        || (calculationDiscountResult != null && !CollectionUtils.isEmpty(calculationDiscountResult.getDiscounts()))) {
                    //是否有换购
                    int type81 = 0;
                    for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount discount : calculationDiscountResult.getDiscounts()) {
                        if (ActivityTypeEnum.TYPE_81.getCode().equals(discount.getType())) {
                            type81 = 1;
                            break;
                        }
                    }
                    //集点
                    int discountCount = calculationDiscountResult.getDiscounts().size();
                    int type211 = 0;
                    for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount discount : calculationDiscountResult.getDiscounts()) {
                        if (discount.getType().equals(221)) {
                            type211 += 1;
                            break;
                        }
                    }
                    discountCount = discountCount - type211;
                    //积分抵扣开关禁用 有换购活动 且选中了换购商品
                    // - 有换购且选中了换购商品
                    // - 有换购且没有选中换购商品 且除集点以外还有其他促销
                    if ((type81 == 0 && discountCount >= 1)
                            || (type81 == 1 && !CollectionUtils.isEmpty(shoppingCartInfoRequestVo.getSendGoods()))
                            || (type81 == 1 && discountCount > 1)) {
                        customerScoreVo.setScoreReduceState(5);
                        userScoreUseDetail.getResult().setScoreState(5);
                        discountAmount = 0;
                        customerScoreVo.setReduceAmount(0);
                    }
                }
            }

            customerScoreVo.setUseScore(getValue(userScoreUseDetail.getResult().getUseScore()));
            String msg = "";

            // 积分抵扣状态 1积分可用  2积分不足  3 积分抵扣开关禁用 4、订单金额不满足开启积分抵现要求
            switch (userScoreUseDetail.getResult().getScoreState()) {
                case 1:
                    msg = String.format("共%s积分，可用%s积分抵¥%s", getValue(userScoreUseDetail.getResult().getCurrentScore()), getValue(userScoreUseDetail.getResult().getUseScore()), ((double) userScoreUseDetail.getResult().getReduceAmount()) / 100);
                    break;
                case 2:
                    String[] split = userScoreUseDetail.getResult().getScoreReduceRate().split(":");
                    msg = String.format("共%s积分，每%s积分可抵¥%s", getValue(userScoreUseDetail.getResult().getCurrentScore()), split[0], split[1]);
                    break;
                case 5:
                    msg = "已享受优惠，无法再参与积分抵扣";
                    break;
                case 4:
                    msg = String.format("共%s积分，订单满¥%s可开启积分抵现", getValue(userScoreUseDetail.getResult().getCurrentScore()), ((double) userScoreUseDetail.getResult().getReducePriceLimit()) / 100);
                    break;
                default:
                    break;
            }
            customerScoreVo.setCustomerScorePrompt(msg);
            shoppingCartGoodsResponseVo.setCustomerScoreVo(customerScoreVo);
            shoppingCartGoodsResponseVo.setTotalDiscountAmount(shoppingCartGoodsResponseVo.getTotalDiscountAmount() + discountAmount);
            shoppingCartGoodsResponseVo.setTotalAmount(shoppingCartGoodsResponseVo.getTotalAmount() - discountAmount);
        }
        return;
    }

    private Integer getValue(Object object) {
        Integer result = 0;
        try {
            if (object != null) {
                if (object instanceof Integer) {
                    result = (Integer) object;
                } else if (object instanceof String) {
                    result = Integer.parseInt((String) object);
                } else if (object instanceof Double) {
                    result = (int) ((double) object);
                } else if (object instanceof Float) {
                    result = (int) ((float) object);
                } else if (object instanceof BigDecimal) {
                    result = ((BigDecimal) object).intValue();
                } else if (object instanceof Long) {
                    result = ((Long) object).intValue();
                }
            }
        } catch (Exception ex) {
            LogUtil.error("getScoreValueFail", "", "", ex);
        }
        return result;
    }

    @Override
    public void updateShoppingCartGoodsApportion(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo, ActivityCalculationDiscountResponseDto.CalculationDiscountResult calculationDiscountResult, ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo.PremiumExchangeActivity premiumExchangeActivity, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        if (shoppingCartGoodsResponseVo.getCustomerScoreVo() != null) {
            shoppingCartGoodsDto.setScoreReduceAmount(shoppingCartGoodsResponseVo.getCustomerScoreVo().getReduceAmount() == null ? 0 : shoppingCartGoodsResponseVo.getCustomerScoreVo().getReduceAmount().longValue());
            shoppingCartGoodsDto.setReduceScore(shoppingCartGoodsResponseVo.getCustomerScoreVo().getUseScore() == null ? 0 : shoppingCartGoodsResponseVo.getCustomerScoreVo().getUseScore().longValue());
        }
    }


}
