/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: CocoOrderRelationServiceImpl
 * @Description:
 * @author: pengfei.liu
 * @date: 2020/11/23
 * @version V1.0
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

package cn.freemud.service.order.impl;

import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.dto.order.BusinessDate;
import cn.freemud.entities.vo.CreateOrderBaseVo;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.ProductVo;
import cn.freemud.entities.vo.QueryOrderResponseVo;
import cn.freemud.enums.CreateOrderType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.impl.CheckOrder;
import cn.freemud.service.order.OrderRelationService;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductDiscountV1;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderSendCouponResp;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.order.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.request.order.OrderProductAddInfoDto;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
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.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("cocoOrderRelationService")
public class CocoOrderRelationServiceImpl implements OrderRelationService {


    //门店SDK
    @Autowired
    private StoreCenterService storeCenterService;

    @Autowired
    private CheckOrder checkOrder;

    @Override
    public void createOrderTimeCheck(StoreResponse.BizVO storeResponseDto, CreateOrderVo createOrderVo) {

        // 只有外卖单才做下单时间判断
        if (!CreateOrderType.TAKE_OUT.getCode().equals(createOrderVo.getOrderType())){
             return;
        }

        // 如果是明天的预约单，不做时间检查
        // 设置预约时间
        Date takeMealDateTime = checkOrder.getOrderExpectTime(createOrderVo.getTakeMealFlag(), createOrderVo.getTakeMealTime(), createOrderVo.getExpectTime(),
                CreateOrderType.getByCode(createOrderVo.getOrderType()), storeResponseDto.getServiceTime(), storeResponseDto);

        Date todayEnd = DateUtil.setEndDay(new Date());

        if(takeMealDateTime != null && todayEnd.before(takeMealDateTime)){
            return;
        }

        //获取门店当天营业时间
        // coco只有一个营业时间，如果返回多个就报错
        Date todayEndDate = null;
        List<String> todayBusinessTimes = storeCenterService.getTodayBusinessTime(Integer.parseInt(storeResponseDto.getBusinessType()), storeResponseDto.getBusinessHoursDay());
        if (CollectionUtils.isEmpty(todayBusinessTimes) || 1 < todayBusinessTimes.size() ) {
            throw new ServiceException(ResponseResult.STORE_BUSINESS_HOUR_ERROR);
        }
        BusinessDate businessDate = checkOrder.getStoreBusinessDate(todayBusinessTimes.get(0), true);
        todayEndDate = businessDate.getEndDate();

        // 当前时间+15分钟 > 门店打烊时间，返回错误
        Date  nowAddDate = DateUtil.addMinutes(new Date(),15);
        if(nowAddDate.after(todayEndDate)){
            throw new ServiceException(ResponseResult.STORE_WILL_COLSE);
        }
    }

    @Override
    public void createOrderTimeCheck(StoreResponse.BizVO storeResponseDto, CreateOrderBaseVo createOrderVo) {
        // 只有外卖单才做下单时间判断
        if (!CreateOrderType.TAKE_OUT.getCode().equals(createOrderVo.getOrderType())){
            return;
        }

        // 如果是明天的预约单，不做时间检查
        // 设置预约时间
        Date takeMealDateTime = checkOrder.getOrderExpectTime(createOrderVo.getTakeMealFlag(), createOrderVo.getTakeMealTime(), createOrderVo.getExpectTime(),
                CreateOrderType.getByCode(createOrderVo.getOrderType()), storeResponseDto.getServiceTime(), storeResponseDto);

        Date todayEnd = DateUtil.setEndDay(new Date());

        if(takeMealDateTime != null && todayEnd.before(takeMealDateTime)){
            return;
        }

        //获取门店当天营业时间
        // coco只有一个营业时间，如果返回多个就报错
        Date todayEndDate = null;
        List<String> todayBusinessTimes = storeCenterService.getTodayBusinessTime(Integer.parseInt(storeResponseDto.getBusinessType()), storeResponseDto.getBusinessHoursDay());
        if (CollectionUtils.isEmpty(todayBusinessTimes) || 1 < todayBusinessTimes.size() ) {
            throw new ServiceException(ResponseResult.STORE_BUSINESS_HOUR_ERROR);
        }
        BusinessDate businessDate = checkOrder.getStoreBusinessDate(todayBusinessTimes.get(0), true);
        todayEndDate = businessDate.getEndDate();

        // 当前时间+15分钟 > 门店打烊时间，返回错误
        Date  nowAddDate = DateUtil.addMinutes(new Date(),15);
        if(nowAddDate.after(todayEndDate)){
            throw new ServiceException(ResponseResult.STORE_WILL_COLSE);
        }
    }

    @Override
    public void queryOrdrBuild(QueryOrderResponseVo queryOrderResponseVo,QueryOrderByIdResponse response) {

        List<QueryOrderResponseVo.chooseGood> chooseGoods = new ArrayList<>();

        List<OrderSendCouponResp> orderSendCouponRespList = response.getData().getOrderSendCouponRespList();

        if(orderSendCouponRespList != null && !orderSendCouponRespList.isEmpty()){
            orderSendCouponRespList.forEach(orderSendCouponResp -> {
                QueryOrderResponseVo.chooseGood chooseGood = new QueryOrderResponseVo.chooseGood();
                chooseGood.setGoodsName(orderSendCouponResp.getGoodsName());
                chooseGoods.add(chooseGood);
            });

            queryOrderResponseVo.setChooseGoods(chooseGoods);
        }

        Map<String, ProductBeanV1> productMap = new HashMap<>();
        List<ProductBeanV1> productList = response.getData().getProductList();
        if(productList != null && !productList.isEmpty()){
            for(ProductBeanV1 productBean : productList){
                if(StringUtils.isEmpty(productBean.getExtInfo())){
                    continue;
                }

                OrderProductAddInfoDto orderProductAddInfoDto = JSONObject.parseObject(productBean.getExtInfo(),OrderProductAddInfoDto.class);
                productMap.put(orderProductAddInfoDto.getCartGoodsUid(),productBean);
            }
        }


        // 赠品合并到主商品
        List<ProductVo> products = queryOrderResponseVo.getProducts();
        // 有购物车行id的是主
        List<ProductVo> masterProducts = products.stream().filter(product ->
            !StringUtils.isEmpty(product.getCid())).collect(Collectors.toList());

        // 没有购物车行id的是赠品
        Map<String, Integer> giftMap = new HashMap<>();
        List<ProductVo> giftProducts = products.stream().filter(product ->
                StringUtils.isEmpty(product.getCid())).collect(Collectors.toList());
        if(giftProducts != null && !giftProducts.isEmpty()){
            giftProducts.forEach(giftProduct ->{
                giftMap.put(giftProduct.getOcid(),giftProduct.getQty());
            });
        }
        Long itemAmount = 0L;
        List<ProductVo> productVos = new ArrayList<>();
        if(null != masterProducts && !masterProducts.isEmpty()){
            for(ProductVo product : masterProducts){
                Integer giftQty = giftMap.get(product.getCid()) == null ? 0 : giftMap.get(product.getCid());
                product.setQty(product.getQty() + giftQty);

                // 商品原单价=商品原单价+小料原单价
                List<ProductVo> smallMaterial = product.getSetMaterialProducts();
                Long smallMaterialOriTotal = 0L;
                if(smallMaterial != null && !smallMaterial.isEmpty()){
                    for(ProductVo sm : smallMaterial){
                        smallMaterialOriTotal = smallMaterialOriTotal + sm.getOriginalPrice();
                    }
                }
                // 商品现单价 = 商品现单价+小料现单价
                smallMaterialOriTotal = smallMaterialOriTotal == null ? 0 : smallMaterialOriTotal;
                product.setOriginalPrice(smallMaterialOriTotal + (product.getOriginalPrice() == null ? 0L : product.getOriginalPrice()));
                itemAmount = itemAmount + product.getOriginalPrice() * product.getQty();

                // 如果商品参加了第二件半价活动，要把该行拆成数量为1的多行
                ProductBeanV1 productBean = productMap.get(product.getCid());
                if(productBean == null || productBean.getDiscountList() == null || productBean.getDiscountList().isEmpty()){
                    continue;
                }
                boolean halfFlag = false;
                List<ProductDiscountV1> discountList = productBean.getDiscountList();
                for(ProductDiscountV1 productDiscount : discountList){
                    if(ObjectUtils.equals(productDiscount.getDiscountType(), OldOrderAccountType.SECOND_DISCOUNT.getCode())){
                        halfFlag = true;
                        break;
                    }
                }
                if(halfFlag){
                    Integer  num = product.getQty();
                    for(int i = 0 ; i < num-1 ; i++){
                        ProductVo newProduct = JSONObject.parseObject(JSONObject.toJSONString(product),ProductVo.class);
                        newProduct.setQty(1);

                        productVos.add(newProduct);
                    }

                    product.setQty(1);
                }

            }

        }

        masterProducts.addAll(productVos);

        queryOrderResponseVo.setProducts(masterProducts);
        // 商品总价
        queryOrderResponseVo.setItemAmount(itemAmount);
    }


}
