package cn.freemud.service.impl;

import ch.qos.logback.classic.Level;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ApplicationConstant;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.GetProductInfoDto;
import cn.freemud.entities.dto.ProductInfosDto;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartGoodsBaseResponseVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.thirdparty.StoreItemClient;
import cn.freemud.service.thirdparty.StoreItemClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
//import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import com.freemud.sdk.api.assortment.shoppingcart.constant.ShoppingCartConstant;
import com.freemud.sdk.api.assortment.shoppingcart.enums.BusinessTypeEnum;
import com.freemud.sdk.api.assortment.shoppingcart.request.CheckCartRequest;
import com.freemud.sdk.api.assortment.shoppingcart.request.GetProductInfoRequest;
import com.freemud.sdk.api.assortment.shoppingcart.service.ShoppingCartBaseService;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import com.freemud.sdk.api.assortment.shoppingcart.util.ShoppingSdkLogUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.freemud.entities.dto.GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: AssortmentSdkService
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: jiaxin.liu
 * @date: 2019/4/20 15:20
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class AssortmentSdkService {

    @Autowired
    private StoreItemClient storeItemClient;

    @Value("${mccafe.partner.id}")
    private String mcCafePartnerId;
    @Value("${mccafe.universal.shopId}")
    private String mcCafeUniversalShopId;

    /**
     * 调用聚合sdk获取单个商品行信息
     *
     * @param partnerId
     * @param userId
     * @param storeId
     * @param cartGoodsUid
     * @return
     */
    public CartGoods getCartGoodsBySdk(String partnerId, String userId, String storeId, String cartGoodsUid, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, userId);
        cartParamDto.setCartGoodsUid(cartGoodsUid);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setUserId(userId);
        cartParamDto.setBizType(bizType);
        BaseResponse<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods> baseResponse = shoppingCartService.getCartGoods(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || baseResponse.getResult() == null) {
            return null;
        }

        return JSONObject.parseObject(JSONObject.toJSONString(baseResponse.getResult()),CartGoods.class);
    }

    /**
     * 调用聚合sdk更新商品行数量信息
     *
     * @param partnerId
     * @param userId
     * @param storeId
     * @param cartGoodsUid
     * @param qty
     * @return
     */
    public List<CartGoods> updateGoodsQtyBySdk(String partnerId, String userId, String storeId, String cartGoodsUid, Integer qty, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        int buyType = 0 ;
        return updateNowBuyGoodsQtyBySdk(buyType,partnerId, userId, storeId, cartGoodsUid, qty, tableNumber, shoppingCartService,bizType);
    }

    /**
     * 调用聚合sdk获取缓存中购物车信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public List<CartGoods> getShoppingCart(String partnerId, String storeId, String useId, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        int buyType = 0 ;
        return  getNowBuyShoppingCart( buyType, partnerId,  storeId,  useId,  sessionId,  tableNumber,  shoppingCartService,bizType);
    }

    public List<CartGoods> getShoppingCartSendGoods(String partnerId, String storeId, String useId, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService) {
        int buyType = 0 ;
        return  getNowBuyShoppingCartSendGoods( buyType, partnerId,  storeId,  useId,  sessionId,  tableNumber,  shoppingCartService);
    }

    /**
     * 调用聚合sdk获取缓存中购物车信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public List<CartGoods> getShoppingCartForCoupon(String partnerId, String storeId, String useId, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setBizType(bizType);
        // 根据不同点餐类型获取不同购物车实例
        BaseResponse<List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods>> baseResponse = shoppingCartService.getCartGoodsList(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || CollectionUtils.isEmpty(baseResponse.getResult())) {
            return new ArrayList<>();
        }

        return JSONArray.parseArray(JSONObject.toJSONString(baseResponse.getResult()), CartGoods.class);
    }

    /**
     * 调用聚合sdk获取缓存中购物车代金券信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public String getShoppingCartCoupon(String partnerId, String storeId, String useId, ShoppingCartBaseServiceImpl shoppingCartService, Integer type) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setCouponType(type);

        BaseResponse<String> baseResponse = shoppingCartService.getCartCouponCode(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || StringUtils.isEmpty(baseResponse.getResult())) {
            return "";
        }

        return baseResponse.getResult();
    }

    /**
     * 调用聚合sdk设置缓存中购物车信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public List<CartGoods> setShoppingCart(String partnerId, String storeId, String useId, List<CartGoods> cartGoodsList, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        int buyType = 0;
        return setNowBuyShoppingCart(buyType,partnerId, storeId, useId , cartGoodsList, sessionId,  tableNumber,  shoppingCartService,bizType);
    }


    public List<CartGoods> setShoppingCartSendGoods(String partnerId, String storeId, String useId, List<CartGoods> cartGoodsList, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService) {
        int buyType = 0;
        return setNowBuyShoppingCartSendGoods(buyType,partnerId, storeId, useId , cartGoodsList, sessionId,  tableNumber,  shoppingCartService);
    }

    /**
     * 调用聚合sdk设置缓存中购物车信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public List<CartGoods> setNowBuyShoppingCart(int buyType,String partnerId, String storeId, String useId, List<CartGoods> cartGoodsList, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setSessionId(sessionId);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setUserId(useId);
        cartParamDto.setBizType(bizType);
        //立即购买==1 ，设置新的缓存key
        if(buyType == ShoppingCartConstant.NOW_BUY_TYPE) {
            cartParamDto.setBuyType(buyType);
        }
        cartParamDto.setCartGoodsList(JSONArray.parseArray(JSONObject.toJSONString(cartGoodsList), com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.class));
        BaseResponse<List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods>> baseResponse = null;
        if(!mcCafePartnerId.equals(partnerId) || !mcCafeUniversalShopId.equals(storeId)) {
            baseResponse = shoppingCartService.setCartGoodsList(cartParamDto, LogThreadLocal.getTrackingNo());
        } else {
            baseResponse = shoppingCartService.setCartGoodsList(cartParamDto, LogThreadLocal.getTrackingNo(), 7, TimeUnit.DAYS);
        }
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode())) {
            return null;
        }

        return JSONArray.parseArray(JSONObject.toJSONString(baseResponse.getResult()), CartGoods.class);
    }

    public List<CartGoods> setNowBuyShoppingCartSendGoods(int buyType,String partnerId, String storeId, String useId, List<CartGoods> cartGoodsList, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setSessionId(sessionId);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setUserId(useId);
        //立即购买==1 ，设置新的缓存key
        if(buyType == ShoppingCartConstant.NOW_BUY_TYPE) {
            cartParamDto.setBuyType(buyType);
        }
        cartParamDto.setCartGoodsList(JSONArray.parseArray(JSONObject.toJSONString(cartGoodsList), com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.class));
        BaseResponse<List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods>> baseResponse = shoppingCartService.setCartSendGoodsList(cartParamDto, LogThreadLocal.getTrackingNo(), 3, TimeUnit.DAYS);
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode())) {
            return null;
        }

        return JSONArray.parseArray(JSONObject.toJSONString(baseResponse.getResult()), CartGoods.class);
    }

    /**
     * 调用聚合sdk设置缓存中购物车代金券
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public String setShoppingCartCouponCode(String partnerId, String storeId, String useId, String couponCode, ShoppingCartBaseService shoppingCartService, Integer type) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setCouponCode(couponCode);
        cartParamDto.setCouponType(type);
        BaseResponse<String> baseResponse = shoppingCartService.setCartCouponCode(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode())) {
            return null;
        }

        return baseResponse.getResult();
    }

    /**
     * 调用SDK校验购物车
     *
     * @param oldAllCartGoodsList
     * @param partnerId
     * @param storeId
     * @param shoppingCartGoodsResponseVo
     * @param orderType
     */
    public CheckCartRequest checkShoppingCartSdk(List<CartGoods> oldAllCartGoodsList, String partnerId, String storeId, ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo
            , Integer orderType, String tableNumber, String menuType ,ShoppingCartBaseService shoppingCartService) {
        CheckCartRequest checkCartRequest = new CheckCartRequest();
        checkCartRequest.setCartGoodsList(JSONArray.parseArray(JSONObject.toJSONString(oldAllCartGoodsList), com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods.class));
        checkCartRequest.setOrderWay(orderType);
        checkCartRequest.setPartnerId(partnerId);
        checkCartRequest.setShoppingCartGoodsResponseVo(JSONObject.parseObject(JSONObject.toJSONString(shoppingCartGoodsResponseVo), com.freemud.sdk.api.assortment.shoppingcart.domain.ShoppingCartGoodsResponseVo.class));
        checkCartRequest.setStoreId(storeId);
        checkCartRequest.setTableNumber(tableNumber);
        checkCartRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        checkCartRequest.setMenuType(BusinessTypeEnum.getByType(menuType).getCode());
        BaseResponse<CheckCartRequest> baseResponse ;
        baseResponse= shoppingCartService.checkAllCartGoodsNew(checkCartRequest);
        if (baseResponse == null) {
            return null;
        }
        return baseResponse.getResult();
    }

    /**
     * 调用SDK获取商品详情
     *
     * @param partnerId
     * @param storeId
     * @param goodsIds
     * @return
     */
    public List<ProductBeanDTO> getProductsInfoSdk(String partnerId, String storeId, List<String> goodsIds,String menuType, ShoppingCartBaseService shoppingCartService) {
        GetProductInfoRequest request = new GetProductInfoRequest();
        request.setGoodsIds(goodsIds);
        request.setPartnerId(partnerId);
        request.setStoreId(storeId);
        request.setTrackingNo(LogThreadLocal.getTrackingNo());
        request.setMenuType(BusinessTypeEnum.getByType(menuType).getCode());
        BaseResponse<List<ProductBeanDTO>> baseResponse = shoppingCartService.getProductsInfo(request);
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || CollectionUtils.isEmpty(baseResponse.getResult())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_PRODUCT_NOT_EXIST);
        }
        return baseResponse.getResult();
    }

    /**
     * 调用获取商品详情
     *
     * @param partnerId
     * @param storeId
     * @param goodsIds
     * @return
     */
    public List<ProductBean> getProductsInfo(String partnerId, String storeId, List<String> goodsIds, String menuType, ShoppingCartBaseService shoppingCartService) {

        //移除空的goodsId及spq的商品券
        goodsIds = goodsIds.parallelStream().filter(StringUtils::isNotEmpty).filter(goodsId -> !goodsId.startsWith(CommonsConstant.COUPON_PREFIX)).collect(Collectors.toList());

        GetProductInfoDto getProductInfoDto = new GetProductInfoDto();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setShopId(storeId);
        getProductInfoDto.setProductInfoType(2);
        getProductInfoDto.setProductIds(goodsIds);
        getProductInfoDto.setChannel(BusinessTypeEnum.getByType(menuType).getCode());

        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
        if (!ResponseCodeConstant.RESPONSE_SUCCESS.equals(productInfosDto.getErrcode()) || CollectionUtils.isEmpty(productInfosDto.getData().getProducts())) {
            return null;
        }
        return productInfosDto.getData().getProducts();

    }

    /**
     * 组装CartParamDto信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto getCartParamDto(String partnerId, String storeId, String useId) {
        int buyType = 0;
        return  getNowBuyCartParamDto(buyType, partnerId,  storeId,  useId);
    }

    /**
     * 立即购买虚拟购物车
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @param buyType 购买类型
     * @return
     */
    public List<CartGoods> getNowBuyShoppingCart(int buyType,String partnerId, String storeId, String useId, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setSessionId(sessionId);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setUserId(useId);
        cartParamDto.setBizType(bizType);
        if(buyType == ShoppingCartConstant.NOW_BUY_TYPE) {
            cartParamDto.setBuyType(buyType);
        }
        // 根据不同点餐类型获取不同购物车实例
        BaseResponse<List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods>> baseResponse = shoppingCartService.getCartGoodsList(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || CollectionUtils.isEmpty(baseResponse.getResult())) {
            return new ArrayList<>();
        }
        return JSONArray.parseArray(JSONObject.toJSONString(baseResponse.getResult()), CartGoods.class);
    }

    public List<CartGoods> getNowBuyShoppingCartSendGoods(int buyType,String partnerId, String storeId, String useId, String sessionId, String tableNumber, ShoppingCartBaseService shoppingCartService) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, useId);
        cartParamDto.setSessionId(sessionId);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setUserId(useId);
        if(buyType == ShoppingCartConstant.NOW_BUY_TYPE) {
            cartParamDto.setBuyType(buyType);
        }
        // 根据不同点餐类型获取不同购物车实例
        BaseResponse<List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods>> baseResponse = shoppingCartService.getCartSendGoodsList(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode()) || CollectionUtils.isEmpty(baseResponse.getResult())) {
            return new ArrayList<>();
        }
        return JSONArray.parseArray(JSONObject.toJSONString(baseResponse.getResult()), CartGoods.class);
    }

    /**
     * 调用聚合sdk更新商品行数量信息
     *
     * @param partnerId
     * @param userId
     * @param storeId
     * @param cartGoodsUid
     * @param qty
     * @return
     */
    public List<CartGoods> updateNowBuyGoodsQtyBySdk(int buyType,String partnerId, String userId, String storeId, String cartGoodsUid, Integer qty, String tableNumber, ShoppingCartBaseService shoppingCartService,Integer bizType) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = getCartParamDto(partnerId, storeId, userId);
        cartParamDto.setCartGoodsUid(cartGoodsUid);
        cartParamDto.setQty(qty);
        cartParamDto.setTableNumber(tableNumber);
        cartParamDto.setUserId(userId);
        cartParamDto.setBizType(bizType);
        //立即购买==1 ，设置新的缓存key
        if(buyType == ShoppingCartConstant.NOW_BUY_TYPE) {
            cartParamDto.setBuyType(buyType);
        }
        BaseResponse<List<com.freemud.sdk.api.assortment.shoppingcart.domain.CartGoods>> baseResponse = shoppingCartService.updateGoodsQty(cartParamDto, LogThreadLocal.getTrackingNo());
        if (baseResponse == null || !ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode())) {
            return null;
        }

        return JSONArray.parseArray(JSONObject.toJSONString(baseResponse.getResult()), CartGoods.class);
    }

    /**
     * 组装NowyCartParamDto信息
     *
     * @param partnerId
     * @param storeId
     * @param useId
     * @return
     */
    public com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto getNowBuyCartParamDto(int buyType,String partnerId, String storeId, String useId) {
        com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto cartParamDto = new com.freemud.sdk.api.assortment.shoppingcart.domain.CartParamDto();
        cartParamDto.setPartnerId(partnerId);
        cartParamDto.setUserId(useId);
        cartParamDto.setStoreId(storeId);
        //立即购买==1 ，设置新的缓存key
        if(buyType == ShoppingCartConstant.NOW_BUY_TYPE) {
            cartParamDto.setBuyType(buyType);
        }
        return cartParamDto;
    }

}
