package cn.freemud.demo.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.demo.adapter.service.CheckAdapter;
import cn.freemud.demo.adapter.service.DistributeAdapter;
import cn.freemud.demo.entities.bo.CheckAdapterBO;
import cn.freemud.demo.entities.bo.DistributeAdapterBO;
import cn.freemud.demo.entities.bo.GetCalCostBO;
import cn.freemud.demo.entities.bo.goods.ShoppingCartGoodsBO;
import cn.freemud.demo.entities.bo.coupon.CheckSpqBO;
import cn.freemud.demo.entities.bo.coupon.GetCheckSpqBo;
import cn.freemud.demo.entities.bo.goods.*;
import cn.freemud.demo.entities.bo.goods.update.UpdateAddGoodsBO;
import cn.freemud.demo.entities.bo.promotion.GetCalculationDiscountBO;
import cn.freemud.demo.entities.bo.store.GetStoreBO;
import cn.freemud.demo.entities.bo.store.GetStoreInfoBO;
import cn.freemud.demo.entities.bo.store.StoreInfoBO;
import cn.freemud.demo.manager.customer.CustomerManager;
import cn.freemud.demo.manager.product.ProductManager;
import cn.freemud.demo.manager.store.StoreManager;
import cn.freemud.demo.service.impl.AbstractUpdateGoodsQtyService;
import cn.freemud.demo.utils.CommonUtils;
import cn.freemud.entities.dto.CheckSpqInfoRequestDto;
import cn.freemud.entities.dto.CheckSpqInfoResponseDto;
import cn.freemud.entities.dto.StoreDeliveryInfoDto;
import cn.freemud.entities.vo.ActivityClassifyCouponBean;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.enums.*;
import cn.freemud.service.CouponService;
import cn.freemud.utils.PropertyConvertUtil;
import cn.freemud.utils.WebUtil;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.util.*;

@Service
public class PlatformUpdateGoodsQtyService extends AbstractUpdateGoodsQtyService {

    private static Integer MAX_SHOP_LENGTH = 32;

    @Autowired
    private StoreManager storeManager;
    @Autowired
    private CustomerManager customerManager;

    @Autowired
    private CouponService couponService;

    @Autowired
    private cn.freemud.demo.adapter.service.CalculationSharingAdapter calculationSharingAdapter;

    @Autowired
    private DistributeAdapter distributeAdapter;

    @Autowired
    private CheckAdapter checkAdapter;

    @Override
    public BaseResponse checkCustomParams(UpdateAddGoodsBO baseRequestDTO) {

        return ResponseBuilder.success();
    }

    @Override
    public CalCostBO getDiscountResultBefore(UpdateAddGoodsBO baseRequestDTO, DiscountResultBO discountResultBO) {
        GetCalCostBO bo = new GetCalCostBO();
        bo.setPartnerId(baseRequestDTO.getPartnerId());
        bo.setReceiveId(baseRequestDTO.getReceiveId());
        bo.setShopId(baseRequestDTO.getShopId());
        bo.setOrderType(baseRequestDTO.getOrderType());
        bo.setManagerService(baseRequestDTO.getManagerService());


        bo.setUserId(baseRequestDTO.getUserId());
        bo.setAppId(baseRequestDTO.getAppId());

        bo.setDiscountResultBO(discountResultBO);

        return calculationSharingAdapter.convert2CalCostBO(bo, true);
    }


    @Override
    public SetMessageBO customDistribute(UpdateAddGoodsBO baseRequestDTO, DistributeBO calCostBO, SetMessageBO commonSetMessageBO) {
        DistributeAdapterBO bo = new DistributeAdapterBO();
        bo.setCouponCode(baseRequestDTO.getCouponCode());
        bo.setPartnerId(baseRequestDTO.getPartnerId());
        bo.setShopId(baseRequestDTO.getShopId());
        bo.setUserId(baseRequestDTO.getUserId());
        distributeAdapter.adapter(calCostBO, commonSetMessageBO, bo, null, 1);
        return commonSetMessageBO;

    }

    @Override
    public AddGoodsToShoppingCartBO checkCustomBusinessRules(UpdateAddGoodsBO baseRequestDTO, CheckBussinessRulesBO checkBussinessRulesBO, AddGoodsToShoppingCartBO addGoodsToShoppingCartBO) {
        CheckAdapterBO bo = new CheckAdapterBO();
        bo.setMenuType(baseRequestDTO.getMenuType());
        bo.setPartnerId(baseRequestDTO.getPartnerId());
        bo.setShopId(baseRequestDTO.getShopId());
        bo.setCouponCode(baseRequestDTO.getCouponCode());
        bo.setUserId(baseRequestDTO.getUserId());
        bo.setOrderType(baseRequestDTO.getOrderType());
        checkAdapter.adapter(checkBussinessRulesBO, addGoodsToShoppingCartBO, bo);

        return addGoodsToShoppingCartBO;
    }

    private Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId, String wxappid, /*ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo,*/ Integer orderType, ManagerServiceBO managerServiceBO) {
        Long deliveryAmount = 0L;
        // 如果订单的收获地址为空，且订单是外卖单，返回运费
        // 主要是为了兼容coco不传收获地址，需要获取固定运费的情况
        if (StringUtils.isBlank(receiveId) && !Objects.equals(orderType, CreateOrderType.TAKE_OUT.getCode())) {
            return deliveryAmount;
        }
        deliveryAmount = Long.parseLong(getDeliveryAmount(receiveId, partnerId, storeId, managerServiceBO).toString());
        // shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(0);
        return deliveryAmount;

    }

    private Integer getDeliveryAmount(String receiveId, String partnerId, String storeId, ManagerServiceBO managerServiceBO) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        Integer amount = 0;
        if (StringUtils.isBlank(receiveId)) {
            return amount;
        }
        QueryReceiveAddressByIdBO queryReceive = new QueryReceiveAddressByIdBO();
        queryReceive.setAddressId(receiveId);
        queryReceive.setPartnerId(partnerId);
        //查询会员后货地址经纬度
        ReceiveAddressBO receiveAddressBO = customerManager.queryReceiveAddressById(queryReceive, managerServiceBO.getCustomerService());
        StoreInfoRequest request = new StoreInfoRequest();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeId);
        //查询门店信息，获取门店经纬度
        GetStoreInfoBO getStoreInfoBO = new GetStoreInfoBO();
        getStoreInfoBO.setPartnerId(partnerId);
        getStoreInfoBO.setStoreId(storeId);
        StoreInfoBO storeResponse = storeManager.getStoreInfo(getStoreInfoBO, managerServiceBO.getStoreService());

        //查询门店外卖配送配置
        DeliveryConfigBO deliveryConfigBO = storeManager.findDeliveryConfigByPartnerIdAndStoreId(partnerId, storeId, managerServiceBO.getStoreService());

        StoreDeliveryInfoDto storeDeliveryInfoDto = new StoreDeliveryInfoDto();
        storeDeliveryInfoDto.setPartnerId(partnerId);
        storeDeliveryInfoDto.setStoreId(storeId);
        storeDeliveryInfoDto.setStoreName(storeResponse.getStoreName());
        storeDeliveryInfoDto.setDeliveryLimitAmount(deliveryConfigBO == null ? 0 : deliveryConfigBO.getDeliveryLimitAmount());
        storeDeliveryInfoDto.setDeliveryAmount(deliveryConfigBO == null ? 0 : deliveryConfigBO.getDeliveryAmount());
        storeDeliveryInfoDto.setDefaultDeliveryRange(deliveryConfigBO == null ? 0L : deliveryConfigBO.getDefaultDeliveryRange());
        storeDeliveryInfoDto.setAddRangeAmount(deliveryConfigBO == null ? 0L : deliveryConfigBO.getAddRangeAmount());
        storeDeliveryInfoDto.setAddRangeCount(deliveryConfigBO == null ? 0L : deliveryConfigBO.getAddRangeCount());
        storeDeliveryInfoDto.setPoint2DList(getDeliveryPoint2DList(storeResponse.getDistributionScope()));
        storeDeliveryInfoDto.setDeliveryHoursDay(storeResponse.getDeliveryHoursDay());
        storeDeliveryInfoDto.setLongitude(storeResponse.getLongitude());
        storeDeliveryInfoDto.setLatitude(storeResponse.getLatitude());
        storeDeliveryInfoDto.setScopeConfig(storeResponse.getScopeConfig());
        if (StringUtils.isNotEmpty(storeResponse.getDeliveryRadius())) {
            storeDeliveryInfoDto.setDeliveryRadius(Integer.valueOf(storeResponse.getDeliveryRadius()));
        } else {
            storeDeliveryInfoDto.setDeliveryRadius(0);
        }
        storeDeliveryInfoDto.setEnableTakeaway(true);
        String userLongitude = receiveAddressBO.getLongitude();
        String userLatitude = receiveAddressBO.getLatitude();
        amount = getUserRealDeliveryAmount(storeDeliveryInfoDto, userLongitude, userLatitude).intValue();
        return amount;
    }

    /**
     * 获取配送范围内集合
     */
    private List<Point2D.Double> getDeliveryPoint2DList(String distributionScope) {
        if (StringUtils.isBlank(distributionScope)) {
            return Collections.emptyList();
        }
        /**
         * 如果点不为整数，返回空
         */
        String[] points = distributionScope.split(",");
        if (points.length % 2 != 0) {
            return Collections.emptyList();
        }
        List<String> pointList = Arrays.asList(points);
        List<Point2D.Double> point2DList = Lists.newArrayList();
        for (int i = 0; i < pointList.size(); i++) {
            Double pointX = Double.parseDouble(pointList.get(i));
            Double pointY = Double.parseDouble(pointList.get(++i));
            point2DList.add(new Point2D.Double(pointX, pointY));
        }
        return point2DList;
    }

    /**
     * 计算用户收货地址实际配送费
     *
     * @param storeDeliveryInfoDto 门店配送信息
     * @param userLongitude        用户地址经度
     * @param userLatitude         用户地址维度
     * @return
     */
    public Long getUserRealDeliveryAmount(StoreDeliveryInfoDto storeDeliveryInfoDto, String userLongitude, String userLatitude) {
        if (!checkUserEnableDelivery(storeDeliveryInfoDto, userLongitude, userLatitude)) {
            return 0L;
        }
        // TODO 用户收货地址距离门店距离 单位米 如果门店没有设置阶层配送费，配送费默认=基础配送费
        if (storeDeliveryInfoDto.getAddRangeCount() == null || storeDeliveryInfoDto.getAddRangeCount() <= 0) {
            return storeDeliveryInfoDto.getDeliveryAmount();
        }
        if (storeDeliveryInfoDto.getAddRangeAmount() == null || storeDeliveryInfoDto.getAddRangeAmount() <= 0) {
            return storeDeliveryInfoDto.getDeliveryAmount();
        }
        double distance = getDistance(storeDeliveryInfoDto.getLongitude(), storeDeliveryInfoDto.getLatitude(),
                userLongitude, userLatitude);
        Long defaultDeliveryRange = storeDeliveryInfoDto.getDefaultDeliveryRange();
        Long deliveryAmount = storeDeliveryInfoDto.getDeliveryAmount();
        Long addRangeCount = storeDeliveryInfoDto.getAddRangeCount();
        Long addRangeAmount = storeDeliveryInfoDto.getAddRangeAmount();
        if (new BigDecimal(distance).compareTo(new BigDecimal(defaultDeliveryRange)) <= 0) {
            return deliveryAmount;
        } else {
            //计算实际配送费
            BigDecimal extraAmount = (new BigDecimal(distance).subtract(new BigDecimal(defaultDeliveryRange)))
                    .divide(new BigDecimal(addRangeCount), 0, BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(addRangeAmount));
            BigDecimal realAmount = new BigDecimal(deliveryAmount).add(extraAmount);
            return realAmount.longValue();
        }
    }

    /**
     * 判断收货地址是否在配送范围
     *
     * @param storeDeliveryInfoDto 门店配送信息
     * @param userLongitude        用户经度
     * @param userLatitude         用户维度
     * @return
     */
    public boolean checkUserEnableDelivery(StoreDeliveryInfoDto storeDeliveryInfoDto, String userLongitude, String userLatitude) {
        if (!storeDeliveryInfoDto.getEnableTakeaway()) {
            return false;
        }
        //兼容老版本 为空设置默认按自定义配送
        if (storeDeliveryInfoDto.getScopeConfig() == null) {
            storeDeliveryInfoDto.setScopeConfig(ScopeConfigType.DEFINITION.getCode());
        }
        if (ScopeConfigType.getByCode(storeDeliveryInfoDto.getScopeConfig()) == null) {
            return false;
        }
        ScopeConfigType scopeConfigType = ScopeConfigType.getByCode(storeDeliveryInfoDto.getScopeConfig());
        if (ScopeConfigType.RADIUS.equals(scopeConfigType)) {
            if (storeDeliveryInfoDto.getDeliveryRadius() == null || storeDeliveryInfoDto.getDeliveryRadius() <= 0) {
                return false;
            }
            //用户收货地址距离门店距离 单位米
            double distance = getDistance(storeDeliveryInfoDto.getLongitude(), storeDeliveryInfoDto.getLatitude(),
                    userLongitude, userLatitude);
            if (distance > storeDeliveryInfoDto.getDeliveryRadius().doubleValue()) {
                return false;
            }
            return true;
        }
        List<Point2D.Double> points = storeDeliveryInfoDto.getPoint2DList();
        if (CollectionUtils.isEmpty(points)) {
            return false;
        }
        Point2D.Double point2D = new Point2D.Double(Double.parseDouble(userLongitude), Double.parseDouble(userLatitude));
        return WebUtil.IsPtInPoly(point2D, points);
    }

    /**
     * 获取两个点的距离 单位米
     *
     * @param shopLng
     * @param shopLat
     * @param addressLng
     * @param addressLat
     * @return
     */
    public double getDistance(String shopLng, String shopLat, String addressLng, String addressLat) {
        if (StringUtils.isBlank(shopLng) || StringUtils.isBlank(shopLat) || StringUtils.isBlank(addressLng) || StringUtils.isBlank(addressLat)) {
            return 100000;
        }
        return WebUtil.calDistance(Double.valueOf(shopLng), Double.valueOf(shopLat), Double.valueOf(addressLng), Double.valueOf(addressLat));
    }

    /**
     * 公共DTO头
     *
     * @param partnerId
     * @param storeId
     * @param userId
     * @param appId
     * @param orderType
     * @return
     */
    private GetCalculationDiscountBO commonSharingDto(String partnerId, String storeId, String userId, String appId, Integer orderType) {
        GetCalculationDiscountBO calculationSharingDiscountRequestDto = new GetCalculationDiscountBO();

        calculationSharingDiscountRequestDto.setPartnerCode(partnerId);
        calculationSharingDiscountRequestDto.setStoreId(storeId);
        calculationSharingDiscountRequestDto.setIsShowGoodsActivity(1);
        calculationSharingDiscountRequestDto.setUserId(userId);
        calculationSharingDiscountRequestDto.setAppId(appId);
        calculationSharingDiscountRequestDto.setVer(1);
        calculationSharingDiscountRequestDto.setSelectActivityList(new ArrayList<>());
        ActivityChannelEnum activityChannelEnum = PropertyConvertUtil.orderTypeConvert2ActivityChannel(orderType);
        if (!Objects.isNull(activityChannelEnum)) {
            calculationSharingDiscountRequestDto.setChannel(activityChannelEnum.getCode());
        }

        //==========================  购物车查询特有逻辑  =================================
        // 到店自取包装费设为null,外卖要计算包装费，flag为1表示去结算
        // 兼容老版本判断null
        if (Objects.equals(orderType, CreateOrderType.COLLECT_GOODS.getCode())) {
            calculationSharingDiscountRequestDto.setProductChannel(BusinessTypeEnum.SAAS_PICKUP.getCode());
        } else if (Objects.equals(orderType, CreateOrderType.TAKE_OUT.getCode())) {
            calculationSharingDiscountRequestDto.setProductChannel(BusinessTypeEnum.SAAS_DELIVERY.getCode());
        }
        return calculationSharingDiscountRequestDto;
    }

    /**
     * 实物商品
     * @param calculationDiscountGoodsList
     * @param cartGoods
     */
    private void setCommonDiscountGoods(List<GetCalculationDiscountBO.CalculationDiscountGoods> calculationDiscountGoodsList
            , CartGoods cartGoods) {

        GetCalculationDiscountBO.CalculationDiscountGoods calculationDiscountGoods = new GetCalculationDiscountBO.CalculationDiscountGoods();
        calculationDiscountGoods.setGoodsId(cartGoods.getGoodsId());
        calculationDiscountGoods.setCartGoodsUid(cartGoods.getCartGoodsUid());
        calculationDiscountGoods.setGoodsQuantity(cartGoods.getQty());
        //if (cartGoods.getGoodsType().equals(GoodsTypeEnum.SET_MEAL_GOODS))
        if (CollectionUtils.isNotEmpty(cartGoods.getProductGroupList()) || CollectionUtils.isNotEmpty(cartGoods.getProductComboList())) {
            calculationDiscountGoods.setOriginalPrice(cartGoods.getFinalPrice()!=null ? cartGoods.getFinalPrice() : cartGoods.getOriginalPrice());
        }
        else {
            calculationDiscountGoods.setOriginalPrice(cartGoods.getOriginalPrice());
        }
        calculationDiscountGoods.setMemberDiscount(cartGoods.getMemberDiscount());
        calculationDiscountGoods.setSpuId(cartGoods.getSpuId());
        //商品加料
        if (CollectionUtils.isNotEmpty(cartGoods.getProductMaterialList())) {
            ArrayList<GetCalculationDiscountBO.CalculationDiscountGoods.Material> materials = new ArrayList<>();
            for (CartGoods.MaterialGoods materialGoods : cartGoods.getProductMaterialList()) {
                GetCalculationDiscountBO.CalculationDiscountGoods.Material material = new GetCalculationDiscountBO.CalculationDiscountGoods.Material();
                material.setType(1);
                material.setGoodsId(materialGoods.getSpuId());
                material.setGoodsQuantity(1);
                material.setOriginalPrice(materialGoods.getFinalPrice());
                materials.add(material);
            }
            calculationDiscountGoods.setSmallMaterial(materials);
        }
        //商品组或是套餐或是固定搭配
        if (CollectionUtils.isNotEmpty(cartGoods.getProductComboList())) {
            ArrayList<GetCalculationDiscountBO.CalculationDiscountGoods.GroupCombox> groupBoxes = new ArrayList<>();
            for (CartGoods.ComboxGoods boxes : cartGoods.getProductComboList()) {
                GetCalculationDiscountBO.CalculationDiscountGoods.GroupCombox combo = new GetCalculationDiscountBO.CalculationDiscountGoods.GroupCombox();
                combo.setGoodsId(boxes.getGoodsId());
                combo.setGoodsQuantity(boxes.getQty());
                combo.setOriginalPrice(boxes.getOriginalPrice().intValue());
                groupBoxes.add(combo);
            }
            calculationDiscountGoods.setMeal(true);
            calculationDiscountGoods.setGroupCombox(groupBoxes);
            calculationDiscountGoods.setOriginalPrice(cartGoods.getFinalPrice());
        }

        //可选搭配
        if (CollectionUtils.isNotEmpty(cartGoods.getProductGroupList())) {
            ArrayList<GetCalculationDiscountBO.CalculationDiscountGoods.Material> groups = new ArrayList<>();
            for (CartGoods.ComboxGoods group : cartGoods.getProductGroupList()) {
                GetCalculationDiscountBO.CalculationDiscountGoods.Material material = new GetCalculationDiscountBO.CalculationDiscountGoods.Material();
                material.setType(2);
                material.setGoodsId(group.getGoodsId());
                material.setGoodsQuantity(group.getQty());
                material.setOriginalPrice(group.getFinalPrice());
                groups.add(material);
            }
            calculationDiscountGoods.setSmallMaterial(groups);
        }
        calculationDiscountGoodsList.add(calculationDiscountGoods);
    }

    private void setSpqDiscountGoods(List<GetCalculationDiscountBO.CalculationDiscountGoods> calculationDiscountGoodsList
            , CartGoods cartGoods
            , String goodsId
            , Long originalPrice
            ,String couponCode) {
        GetCalculationDiscountBO.CalculationDiscountGoods calculationDiscountGoods = new GetCalculationDiscountBO.CalculationDiscountGoods();
        calculationDiscountGoods.setGoodsId(goodsId);
        calculationDiscountGoods.setCartGoodsUid(cartGoods.getCartGoodsUid());
        calculationDiscountGoods.setGoodsQuantity(cartGoods.getQty());
        calculationDiscountGoods.setOriginalPrice(originalPrice);
        calculationDiscountGoods.setMemberDiscount(100);
        calculationDiscountGoods.setCouponCode(couponCode);
        this.setCalculationDiscountGoods(calculationDiscountGoodsList,calculationDiscountGoods);
    }

    /**
     * 需要促销计算的商品
     * @param calculationDiscountGoodsList
     * @param calculationDiscountGoods
     */
    private void setCalculationDiscountGoods(List<GetCalculationDiscountBO.CalculationDiscountGoods> calculationDiscountGoodsList
            ,GetCalculationDiscountBO.CalculationDiscountGoods calculationDiscountGoods) {
        int index = 0;
        //当商品已经存在时，需要累加数量
        if ((index = calculationDiscountGoodsList.indexOf(calculationDiscountGoods))>=0) {
            GetCalculationDiscountBO.CalculationDiscountGoods old = calculationDiscountGoodsList.get(index);
            calculationDiscountGoodsList.get(index).setGoodsQuantity(old.getGoodsQuantity()+calculationDiscountGoods.getGoodsQuantity());
        }
        else {
            calculationDiscountGoodsList.add(calculationDiscountGoods);
        }

    }

    public ActivityClassifyCouponBean createEmptyActivityCouponBean() {
        ActivityClassifyCouponBean activityClassifyCouponBean = new ActivityClassifyCouponBean();
        activityClassifyCouponBean.setCouponNum(0);
        activityClassifyCouponBean.setDisableCouponNum(0);
        activityClassifyCouponBean.setUsableCouponNum(0);
        activityClassifyCouponBean.setDisableCoupons(Lists.newArrayList());
        activityClassifyCouponBean.setUsableCoupons(Lists.newArrayList());
        return activityClassifyCouponBean;
    }

}
