package cn.freemud.management.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.management.entities.dto.request.delivery.DeliveryOrderAssemblyackRequest;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.entities.dto.response.order.OrderManagerResponse;
import cn.freemud.management.entities.dto.response.pay.PayRefundResponse;
import cn.freemud.management.enums.OrderStatus;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.service.OrderManagerService;
import cn.freemud.management.service.handle.*;
import cn.freemud.management.thirdparty.DeliveryMCCafeClient;
import cn.freemud.management.util.ResponseUtil;
import com.freemud.application.sdk.api.deliverycenter.response.DeliveryResponseDto;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderCostResp;
import com.freemud.sdk.api.assortment.message.enums.OrderType;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: McoffeMangerServiceImpl
 * @Package cn.freemud.management.service.impl
 * @Description:
 * @author: shuhu.hou
 * @date: 2020/8/9 15:26
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class McCafeMangerServiceImpl implements OrderManagerService {
    @Resource
    private SaasOrderHandle saasOrderHandle;
    @Resource
    private CouponHandle couponHandle;
    @Resource
    private DeliveryHandle deliveryHandle;
    @Resource
    private PaymentHandle paymentHandle;
    @Resource
    private StockHandle stockHandle;
    @Resource
    private DeliveryMCCafeClient deliveryMCCafeClient;

    @Override
    public BaseResponse<OrderManagerResponse> orderConfirm(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        OrderManagerRequest orderManagerRequest =new OrderManagerRequest();
        BeanUtils.copyProperties(request,orderManagerRequest);
        if (!OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus()) && !OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())){
            return ResponseUtil.error(ResponseResult.ORDER_STATUS_FAILED);
        }
        if (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
            // 订单接单
            saasOrderHandle.orderConfirm(orderManagerRequest, orderBean);
        }
        if (!Objects.equals(orderBean.getOrderType(), OrderType.TAKE_OUT.getCode())) {
            // 异步核销券码
            couponHandle.asyncVerificationCoupon(orderBean);
        }
        if (StringUtils.isNotEmpty(request.getPickUpGoodsNo())){
            //更新取餐码
            BaseResponse baseResponse = saasOrderHandle.updatePickUpGoodNo(request, orderBean);
            if (!ResponseResult.SUCCESS.getCode().equals(baseResponse.getCode())){
                return ResponseUtil.error(ResponseResult.ORDER_UPDATE_PICKUP_FAILED);
            }

            if (Objects.equals(orderBean.getOrderType(), OrderType.TAKE_OUT.getCode())) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                DeliveryOrderAssemblyackRequest assemblyAckRequest = new DeliveryOrderAssemblyackRequest();
                assemblyAckRequest.setOrderKey(request.getOrderId());
                assemblyAckRequest.setDisplayOrderNumber(request.getPickUpGoodsNo());
                assemblyAckRequest.setAssemblyTimeUTC(dateFormat.format(DateUtil.addHours(new Date(), -8)));
                assemblyAckRequest.setStoreId(orderBean.getShopId());
                //入机成功通知配送
                DeliveryResponseDto deliveryResponse = deliveryMCCafeClient.assemblyAck(assemblyAckRequest);
                if (deliveryResponse == null || !StringUtils.equals(ResponseResult.SUCCESS.getCode(), deliveryResponse.getCode() + "")) {
                    return ResponseUtil.error(ResponseResult.DELIVERY_ASSEMBLY_ACK_ERROR);
                }
            }
        }

        return ResponseUtil.success();
    }

    @Override
    public BaseResponse<OrderManagerResponse> orderReject(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        OrderManagerRequest orderManagerRequest =new OrderManagerRequest();
        BeanUtils.copyProperties(request,orderManagerRequest);
        //根据是否是外卖单来判断
        if (Objects.equals(orderBean.getOrderType(), OrderType.TAKE_OUT.getCode())) {
            // 订单接单
            BaseResponse<OrderManagerResponse> orderManagerResponseBaseResponse = orderConfirm(request, orderBean);
            if (ResponseResult.SUCCESS.getCode().equals(orderManagerResponseBaseResponse.getCode())){
                //通知配送服务停单
                deliveryHandle.haltedDelivery(orderBean);
            }

        }else {
            //支付退款
            PayRefundResponse refundResponse = paymentHandle.refund(orderManagerRequest, orderBean);
            //随单购月卡进行卡作废
            if (CollectionUtils.isNotEmpty(orderBean.getOrderCostDetailList())){
                OrderCostResp orderCostResp = orderBean.getOrderCostDetailList().stream().filter(t -> 10 == t.getCostType()).findFirst().orElse(null);
                if (orderCostResp != null){
                    String note = orderCostResp.getNote();
                    // todo 调用券码作废券接口

                }
            }
            //订单拒单
            saasOrderHandle.orderReject(orderManagerRequest, refundResponse, orderBean);
            //冲正库存
            stockHandle.revert(orderManagerRequest, orderBean);
            // 券码解冻
            couponHandle.unlock(orderBean);
        }
        return ResponseUtil.success();
    }

    /**
     * 制作完成
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderDone(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        // 订单制作完成
        saasOrderHandle.orderDone(request, orderBean);
        return ResponseUtil.success();
    }

    /**
     * 订单配送
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderDelivery(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        // 订单配送
        saasOrderHandle.orderDelivery(request, orderBean);
        return ResponseUtil.success();
    }

    /**
     * 订单完成
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderAffirm(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        // 订单完成
        saasOrderHandle.orderAffirm(request, orderBean);
        return ResponseUtil.success();
    }



    /**
     * 同意退款
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderAgreeRefund(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //支付退款
        PayRefundResponse refund = paymentHandle.refund(request, orderBean);
        //订单拒单
        saasOrderHandle.refundAgree(request,refund, orderBean);
        //冲正库存
        stockHandle.revert(request, orderBean);
        return ResponseUtil.success();
    }

    /**
     * 拒绝退款
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderRejectRefund(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //拒绝退款
        saasOrderHandle.refundReject(request,orderBean);
        return ResponseUtil.success();
    }


    /**
     * 商家取消
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderCancel(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //支付退款
        PayRefundResponse refund = paymentHandle.refund(request, orderBean);
        //订单拒单
        saasOrderHandle.orderCancel(request,refund, orderBean);
        //冲正库存
        stockHandle.revert(request, orderBean);
        return ResponseUtil.success();
    }

}
