/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: CheckOrder
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: ping.wu
 * @date: 2019/5/8 10:01
 * @version V1.0
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.service.impl;

import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.StoreDeliveryInfoDto;
import cn.freemud.entities.dto.UserDeliveryInfoDto;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.delivery.WeixinDeliveryAddressDto;
import cn.freemud.entities.dto.shoppingCart.GetShoppingCartGoodsApportionDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.ShoppingCartInfoRequestVo;
import cn.freemud.entities.vo.delivery.DeliveryAmountVo;
import cn.freemud.enums.CouponFlag;
import cn.freemud.enums.OrderChannelType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.delivery.ThirdDeliveryServiceImpl;
import cn.freemud.service.thirdparty.ShoppingCartClient;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CheckMallOrder {

    @Autowired
    private ShoppingCartClient shoppingCartClient;
    @Autowired
    private CheckOrder checkOrder;
    // 缓存取用户数据用
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ThirdDeliveryServiceImpl thirdDeliveryService;

    /**
     * 下单会员相关校验
     */
    public UserLoginInfoDto checkOrderByMember(CreateOrderVo createOrderVo, String trackingNo) {
        // 通过sessionId查询缓存中会员id
        UserLoginInfoDto userLoginInfoDto = userService.getUserLoginInfoBySessionId(createOrderVo.getSessionId());
        createOrderVo.setUserId(userLoginInfoDto.getMemberId());
        return userLoginInfoDto;
    }

    /**
     * 下单门店相关校验
     */
    public StoreResponse.BizVO checkOrderByStore(CreateOrderVo createOrderVo, String trackingNo) {
        return checkOrder.checkOrderByStore(createOrderVo, trackingNo);
    }

    /**
     * 下单配送相关校验
     */
    public void checkOrderByDelivery(CreateOrderVo createOrderVo, UserLoginInfoDto userLoginInfoDto,
                                         StoreResponse.BizVO storeResponseDto,Long totalAmount, String trackingNo) {
        StoreDeliveryInfoDto storeDeliveryInfoDto = this.getStoreDeliveryInfo(storeResponseDto, userLoginInfoDto.getWxAppId());
        //订单金额小于起送费提示
        if (storeDeliveryInfoDto.getDeliveryLimitAmount() > totalAmount) {
            throw new ServiceException(ResponseResult.STORE_DISCONTENT_DELIVERY_FEE);
        }
        storeDeliveryInfoDto.setEnableTakeaway(true);
        this.checkReceiveAddress(storeDeliveryInfoDto, createOrderVo);
    }

    public ShoppingCartGoodsDto getShoppingCartGoodsDto(CreateOrderVo createOrderVo) {
        ShoppingCartInfoRequestVo shoppingCartInfoRequestVo = ShoppingCartInfoRequestVo.builder()
                .partnerId(createOrderVo.getPartnerId())
                .shopId(createOrderVo.getShopId())
                .version(createOrderVo.getVersion())
                .sessionId(createOrderVo.getSessionId())
                .orderType(createOrderVo.getOrderType())
                .reachStoreType(createOrderVo.getReachStoreType())
                .flag(CouponFlag.NO.getCode())
                .useCustomerScore(createOrderVo.getUseCustomerScore())
                .channelType(OrderChannelType.SAASMALL.getCode())
                .build();
        // 通过购物车获取优惠信息
        GetShoppingCartGoodsApportionDto requestDto = new GetShoppingCartGoodsApportionDto();
        requestDto.setShoppingCartInfoRequestVo(shoppingCartInfoRequestVo);
        //加价购商品 校验放购物车校验
        requestDto.setPremiumExchangeActivity(createOrderVo.getPremiumExchangeActivity());
        cn.freemud.base.entity.BaseResponse<ShoppingCartGoodsDto> apportionResponse = shoppingCartClient.getShoppingCartGoodsApportionNew(requestDto);
        if (!ObjectUtils.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, apportionResponse.getCode())) {
            ResponseResult responseResult = ResponseResult.getResponseResult(apportionResponse.getCode());
            throw new ServiceException(responseResult != null ? responseResult : ResponseResult.SHOPPING_CART_GETINFO_ERROR );
        }
        if (apportionResponse.getResult() == null || CollectionUtils.isEmpty(apportionResponse.getResult().getProducts())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_GETINFO_INVAILD);
        }
        ShoppingCartGoodsDto shoppingCartGoodsDto = apportionResponse.getResult();
        if (shoppingCartGoodsDto.getOriginalTotalAmount() == null) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_GETINFO_INVAILD);
        }
        return shoppingCartGoodsDto;
    }


    /**
     * 获取门店配送信息
     */
    public StoreDeliveryInfoDto getStoreDeliveryInfo(StoreResponse.BizVO storeResponseDto, String wxAppid) {
        StoreDeliveryInfoDto storeDeliveryInfoDto = new StoreDeliveryInfoDto();
        storeDeliveryInfoDto.setPartnerId(storeResponseDto.getPartnerId());
        storeDeliveryInfoDto.setStoreId(storeResponseDto.getStoreCode());
        storeDeliveryInfoDto.setStoreName(storeResponseDto.getStoreName());

        storeDeliveryInfoDto.setDeliveryLimitAmount(0L);
        storeDeliveryInfoDto.setDeliveryAmount(0L);
        storeDeliveryInfoDto.setDefaultDeliveryRange(0L);
        storeDeliveryInfoDto.setAddRangeAmount(0L);
        storeDeliveryInfoDto.setAddRangeCount(0L);
        storeDeliveryInfoDto.setDeliveryHoursDay(storeResponseDto.getDeliveryHoursDay());
        storeDeliveryInfoDto.setLongitude(storeResponseDto.getLongitude());
        storeDeliveryInfoDto.setLatitude(storeResponseDto.getLatitude());
        storeDeliveryInfoDto.setScopeConfig(storeResponseDto.getScopeConfig());
        if (StringUtils.isNotEmpty(storeResponseDto.getDeliveryRadius())) {
            storeDeliveryInfoDto.setDeliveryRadius(Integer.valueOf(storeResponseDto.getDeliveryRadius()));
        } else {
            storeDeliveryInfoDto.setDeliveryRadius(0);
        }
        storeDeliveryInfoDto.setDeliveryType("third");
        storeDeliveryInfoDto.setPushOrderTime(0);
        return storeDeliveryInfoDto;
    }

    /**
     * 校验收货地址是否可配送
     */
    public void checkReceiveAddress(StoreDeliveryInfoDto storeDeliveryInfoDto, CreateOrderVo createOrderVo) {
        WeixinDeliveryAddressDto weixinDeliveryAddress = createOrderVo.getWeixinDeliveryAddress();
        if(weixinDeliveryAddress == null || StringUtils.isEmpty(weixinDeliveryAddress.getProvinceName())) {
            throw new ServiceException(ResponseResult.DELIVERY_INFO_ERROR);
        }
        cn.freemud.base.entity.BaseResponse<DeliveryAmountVo> deliveryAmountVoBaseResponse = thirdDeliveryService.queryDeliveryAmount(createOrderVo.getWeixinDeliveryAddress());
        if(deliveryAmountVoBaseResponse == null || !ResponseResult.SUCCESS.getCode().equals(deliveryAmountVoBaseResponse.getCode())) {
            throw new ServiceException(ResponseResult.DELIVERY_INFO_NOT_DELIVERY);
        }
        DeliveryAmountVo deliveryAmountVo = deliveryAmountVoBaseResponse.getResult();
        UserDeliveryInfoDto userDeliveryInfoDto = UserDeliveryInfoDto.builder()
                .deliveryLimitAmount(storeDeliveryInfoDto.getDeliveryLimitAmount())
                .userEnableTakeaway(true)
                .realDeliveryAmount(deliveryAmountVo.getDeliveryAmount().longValue())
                .storeId(storeDeliveryInfoDto.getStoreId())
                .storeName(storeDeliveryInfoDto.getStoreName())
                .receiveMobile(weixinDeliveryAddress.getTelNumber())
                .receiveUserName(weixinDeliveryAddress.getUserName())
                .receiveProvince(weixinDeliveryAddress.getProvinceName())
                .receiveCity(weixinDeliveryAddress.getCityName())
                .receiveRegion(weixinDeliveryAddress.getCountyName())
                .receiveAddress(weixinDeliveryAddress.getDetailInfo())
                .storeDeliveryInfoDto(storeDeliveryInfoDto).build();
        createOrderVo.setUserDeliveryInfoDto(userDeliveryInfoDto);
    }

}
