package cn.freemud.service.impl;

import cn.freemud.constant.CustomerScoreConstant;
import cn.freemud.entities.dto.GetUserScoreUserDetailDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.promotion.*;
import cn.freemud.entities.vo.GetUserScoreUseDetailVo;
import cn.freemud.entities.vo.ShoppingCartCustomerScoreVo;
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;

/**
 * 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 updateDiscountApportion(ShoppingCartGoodsResponse shoppingCartGoodsResponse, OrderBeanRequest request, CalculationDiscountResultDto calculationDiscountResult, CouponPromotionDto couponPromotionDto, ActivityQueryDto activityQueryDto,Boolean isApportion) {
        if (request == null || request.getUseCustomerScore() == null || request.getUseCustomerScore() == null || request.getUseCustomerScore().equals(CustomerScoreConstant.NO_DISPLAY.getValue())) {
            return;
        }
        GetUserScoreUseDetailVo getUserScoreUseDetailVo = new GetUserScoreUseDetailVo();
        getUserScoreUseDetailVo.setMemberId(request.getUserId());
        getUserScoreUseDetailVo.setPaidAmount(getValue(shoppingCartGoodsResponse.getTotalAmount()));
        getUserScoreUseDetailVo.setPartnerId(request.getPartnerId());
        GetUserScoreUserDetailDto userScoreUseDetail = null;
        try {
            // 加入try catch是为了custom服务挂掉，购物车服务可以也可以正常
            userScoreUseDetail = customScoreClient.getUserScoreUseDetail(getUserScoreUseDetailVo);
        } 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(request.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(couponPromotionDto.getCouponCode()) || (calculationDiscountResult != null && calculationDiscountResult.getTotalDiscountAmount().intValue() > 0)
                        || (calculationDiscountResult != null && !CollectionUtils.isEmpty(calculationDiscountResult.getDiscounts()))) {
                    //是否有换购
                    int type81 = 0;
                    for (CalculationGoodsActivityDto discount : calculationDiscountResult.getDiscounts()) {
                        if (ActivityTypeEnum.TYPE_81.getCode().equals(discount.getType())) {
                            type81 = 1;
                            break;
                        }
                    }
                    //集点
                    long discountCount = calculationDiscountResult.getDiscounts().stream().filter(discount -> !ActivityTypeEnum.TYPE_211.getCode().equals(discount.getType())).count();
                    /*
                    int discountCount = calculationDiscountResult.getDiscounts().size();
                    int type211 = 0;
                    for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Discount discount : calculationDiscountResult.getDiscounts()) {
                        if (ActivityTypeEnum.TYPE_221.getCode().equals(discount.getType())) {
                            type211 += 1;
                            break;
                        }
                    }
                    discountCount = discountCount - type211;
                     */
                    //积分抵扣开关禁用 有换购活动 且选中了换购商品
                    // - 有换购且选中了换购商品
                    // - 有换购且没有选中换购商品 且除集点以外还有其他促销
                    if ((type81 == 0 && discountCount >= 1)
                            || (type81 == 1 && !CollectionUtils.isEmpty(shoppingCartGoodsResponse.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);
            shoppingCartGoodsResponse.setCustomerScoreVo(customerScoreVo);
            shoppingCartGoodsResponse.setScoreReduceAmount(customerScoreVo.getReduceAmount().longValue());
            shoppingCartGoodsResponse.setReduceScore(customerScoreVo.getUseScore().longValue());
            shoppingCartGoodsResponse.setTotalDiscountAmount(shoppingCartGoodsResponse.getTotalDiscountAmount() + discountAmount);
            shoppingCartGoodsResponse.setTotalAmount(shoppingCartGoodsResponse.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;
    }


}
