/**
 * 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.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.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.response.order.QueryOrderByIdResponse;
import io.swagger.models.auth.In;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
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 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);
        }


        // 赠品合并到主商品
        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());
            });
        }

        if(null != masterProducts && !masterProducts.isEmpty()){
            masterProducts.forEach(product -> {
                Integer giftQty = product.getQty();
                if(giftQty == 0){
                    return;
                }
                product.setQty(product.getQty() + giftQty);
            });
        }

        queryOrderResponseVo.setProducts(masterProducts);
    }

}
