package cn.freemud.service.impl.calculate.promotion;

import cn.freemud.base.util.JsonUtil;
import cn.freemud.constant.CustomerScoreConstant;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.calculate.CalculationDiscountResult;
import cn.freemud.entities.dto.calculate.Discount;
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.ShoppingCartCustomerScoreVo;
import cn.freemud.entities.vo.ShoppingCartGoodsResponseVo;
import cn.freemud.entities.vo.ShoppingCartInfoRequestVo;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.thirdparty.CustomerApplicationClient;
import com.freemud.application.sdk.api.constant.FMStatusCode;
import com.freemud.application.sdk.api.log.ErrorLog;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: cn.freemud.service.impl.calculate.promotion ScoreSharingService
 * @Description: 积分抵扣
 * @author: family
 * @date: 2020/9/9
 * @Copyright: www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class ScoreSharingService {

    @Autowired
    private CustomerApplicationClient customScoreClient;

    public void scoreResponse(CalculationDiscountResult discountResult
            , 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.errorConvertJson(this.getClass(), JsonUtil.toJSONString(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 (discountResult != null && !CollectionUtils.isEmpty(discountResult.getDiscounts())) {
                    //是否有换购
                    int type81 = 0;
                    for (Discount discount : discountResult.getDiscounts()) {
                        if (ActivityTypeEnum.TYPE_81.getCode().equals(discount.getType())) {
                            type81 = 1;
                            break;
                        }
                    }
                    //集点
                    long discountCount = discountResult.getDiscounts().stream().filter(discount -> !ActivityTypeEnum.TYPE_221.getCode().equals(discount.getType())).count();

                    //积分抵扣开关禁用 有换购活动 且选中了换购商品
                    // - 有换购且选中了换购商品
                    // - 有换购且没有选中换购商品 且除集点以外还有其他促销
                    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;
    }

    public void equally(ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo
            , ShoppingCartGoodsDto shoppingCartGoodsDto) {

        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());
        }
    }

    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) {
            ErrorLog.errorConvertJson(this.getClass(),"getScoreValueFail",ex);
        }
        return result;
    }
}
