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.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.AbnormalStateEnum;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.request.SdkUpdateAbnormalState;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.sdk.api.assortment.message.enums.OrderType;
import com.freemud.sdk.api.assortment.order.enums.PayRefundStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
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;
    @Resource
    private OrderSdkService orderSdkService;

    @Value("${mccafe.partner.id}")
    private String macCafePartnerId;
    @Value("${mcCafe.withOrderBuy.cardId}")
    private String macCafeCardId;

    @Override
    public BaseResponse<OrderManagerResponse> orderConfirm(OrderManagerRequest request, OrderBeanV1 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 (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 (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())){

            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, OrderBeanV1 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.mcCafeRefund(orderManagerRequest, orderBean);
            if(refundResponse.getPayRefundStatus().getCode().equals(PayRefundStatus.SUCCESS.getCode())) {
                //订单拒单
                saasOrderHandle.mcCafeOrderReject(orderManagerRequest, refundResponse, orderBean);
                //冲正库存
                stockHandle.revert(orderManagerRequest, orderBean);
            } else {
                SdkUpdateAbnormalState sdkUpdateAbnormalState = new SdkUpdateAbnormalState();
                sdkUpdateAbnormalState.setOrderCode(request.getOrderId());
                sdkUpdateAbnormalState.setPartnerId(request.getPartnerId());
                sdkUpdateAbnormalState.setAbnormalState(AbnormalStateEnum.ABNORMAL.getCode());
                sdkUpdateAbnormalState.setAbnormalDesc("支付退款失败，订单入机失败回调异常");
                sdkUpdateAbnormalState.setOrderClient(OrderClientType.SAAS.getIndex());
                sdkUpdateAbnormalState.setOperator(request.getOperator());
                orderSdkService.updateAbnormalState(sdkUpdateAbnormalState);
            }
        }
        return ResponseUtil.success();
    }

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

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

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



    /**
     * 同意退款
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderAgreeRefund(OrderManagerRequest request, OrderBeanV1 orderBean) {
        //支付退款
        PayRefundResponse refundResponse = paymentHandle.mcCafeRefund(request, orderBean);
        if(refundResponse.getPayRefundStatus().getCode().equals(PayRefundStatus.SUCCESS.getCode())) {
            //订单拒单
            saasOrderHandle.mcCafeRefundAgree(request, refundResponse, orderBean);
            //冲正库存
            stockHandle.revert(request, orderBean);
        } else {
            SdkUpdateAbnormalState sdkUpdateAbnormalState = new SdkUpdateAbnormalState();
            sdkUpdateAbnormalState.setOrderCode(request.getOrderId());
            sdkUpdateAbnormalState.setPartnerId(request.getPartnerId());
            sdkUpdateAbnormalState.setAbnormalState(AbnormalStateEnum.ABNORMAL.getCode());
            sdkUpdateAbnormalState.setAbnormalDesc("支付退款失败，订单入机失败回调异常");
            sdkUpdateAbnormalState.setOrderClient(OrderClientType.SAAS.getIndex());
            sdkUpdateAbnormalState.setOperator(request.getOperator());
            orderSdkService.updateAbnormalState(sdkUpdateAbnormalState);
        }
        return ResponseUtil.success();
    }

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


    /**
     * 商家取消
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderCancel(OrderManagerRequest request, OrderBeanV1 orderBean) {
        //支付退款
        PayRefundResponse refundResponse = paymentHandle.mcCafeRefund(request, orderBean);
        if(refundResponse.getPayRefundStatus().getCode().equals(PayRefundStatus.SUCCESS.getCode())) {
            //订单拒单
            saasOrderHandle.orderCancel(request, refundResponse, orderBean);
            //冲正库存
            stockHandle.revert(request, orderBean);
        } else {
            SdkUpdateAbnormalState sdkUpdateAbnormalState = new SdkUpdateAbnormalState();
            sdkUpdateAbnormalState.setOrderCode(request.getOrderId());
            sdkUpdateAbnormalState.setPartnerId(request.getPartnerId());
            sdkUpdateAbnormalState.setAbnormalState(AbnormalStateEnum.ABNORMAL.getCode());
            sdkUpdateAbnormalState.setAbnormalDesc("支付退款失败，订单入机失败回调异常");
            sdkUpdateAbnormalState.setOrderClient(OrderClientType.SAAS.getIndex());
            sdkUpdateAbnormalState.setOperator(request.getOperator());
            orderSdkService.updateAbnormalState(sdkUpdateAbnormalState);
        }
        return ResponseUtil.success();
    }

}
