package com.gree.mall.miniapp.logic;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import com.gree.mall.miniapp.bean.order.BuyGood;
import com.gree.mall.miniapp.bean.order.OrderBuyBean;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.enums.FreightTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.FreightTemplateDetailService;
import com.gree.mall.miniapp.plus.service.FreightTemplateService;
import com.gree.mall.miniapp.plus.service.GoodsService;
import com.gree.mall.miniapp.plus.service.UserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FreightLogic {

    @Autowired
    FreightTemplateService freightTemplateService;
    @Autowired
    FreightTemplateDetailService freightTemplateDetailService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    UserAddressService userAddressService;
    @Autowired
    CommonLogic commonLogic;


    public BigDecimal getFreightAmountV2(OrderBuyBean freightBean, HttpServletRequest request) throws RemoteServiceException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        if(StringUtils.isNotBlank(freightBean.getUserAddressId())) {
            UserAddress userAddress = userAddressService.getById(freightBean.getUserAddressId());
            BigDecimal freightAmountV2 = this.getFreightAmountV2(userAddress.getProvince(), userAddress.getCity(), userAddress.getArea(), freightBean.getBuyGoods(),currentCompanyWechat);
            return freightAmountV2;
        }
        return BigDecimal.valueOf(0);
    }


    public BigDecimal getFreightAmountV2(String province, String city, String area, List<BuyGood> buyGoods, AdminCompanyWechat adminCompanyWechat) throws RemoteServiceException {
        BigDecimal totalAmount = new BigDecimal(0.00);
        log.info("运费商品列表{}", JSON.toJSON(buyGoods));
        if (buyGoods != null && buyGoods.size() > 0) {

            for (BuyGood buyGood : buyGoods) {
                BigDecimal freightItem = computeAmountItem(province,city,area,buyGood,adminCompanyWechat);
                totalAmount = totalAmount.add(freightItem);
            }
        }
        return totalAmount;
    }


    public BigDecimal computeAmountItem(String province, String city, String area, BuyGood buyGood, AdminCompanyWechat adminCompanyWechat) throws RemoteServiceException {
        Goods goods = goodsService.getById(buyGood.getGoodsId());
        if (goods != null && FreightTypeEnum.UNIFIED.toString().equals(goods.getFreightType())) {
            return goods.getFreight().multiply(new BigDecimal(buyGood.getNum()));
        }
        FreightTemplate freightTemplate = freightTemplateService.lambdaQuery()
                .eq(FreightTemplate::getFreightTemplateId, goods.getFreightTemplateId())
                .one();

        if (freightTemplate == null) {
            log.info("异常商品id{}", buyGood.getGoodsId());
            throw new RemoteServiceException("暂不支持该地区的配送服务...");
        }
        if(StringUtils.isNotBlank(province) && StringUtils.isNotBlank(city)) {
            FreightTemplateDetail one = freightTemplateDetailService.lambdaQuery()
                    .eq(FreightTemplateDetail::getFreightTemplateId, freightTemplate.getFreightTemplateId())
                    .eq(FreightTemplateDetail::getProvince, province)
                    .eq(FreightTemplateDetail::getCity, city)
//                .eq(FreightTemplateDetail::getArea, area)
                    .eq(FreightTemplateDetail::getCompanyWechatId,adminCompanyWechat.getCompanyWechatId())
                    .eq(FreightTemplateDetail::getStatus, true)
                    .one();
            if (one == null) {
                throw new RemoteServiceException("暂不支持该地区的配送服务");
            }
            Integer firstLimit = one.getFirstLimit();
            Integer continuousLimit = one.getContinuousLimit();
            if(firstLimit == 0){
                return BigDecimal.valueOf(0);
            }
            if(continuousLimit == 0){
                return one.getFirstAmount();
            }
            int num = buyGood.getNum();
            BigDecimal conAmount = new BigDecimal(0.00);
            if (num > firstLimit) {
                int xj = (num - firstLimit) / continuousLimit + ((num - firstLimit) % continuousLimit == 0 ? 0 : 1);
                conAmount = one.getContinuousAmount().multiply(new BigDecimal(xj));
            }
            return one.getFirstAmount().add(conAmount);
        }
        return BigDecimal.valueOf(0);
    }


}
