package cn.freemud.service.mccafe.impl;

import cn.freemud.amqp.Header;
import cn.freemud.amqp.MQAction;
import cn.freemud.amqp.MQMessage;
import cn.freemud.amqp.MQService;
import cn.freemud.service.mccafe.CouponClientService;
import cn.freemud.service.mccafe.MCCafeOrderCenterSdkService;
import cn.freemud.utils.AppLogUtil;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.api.assortment.datamanager.meal.MealCacheManager;
import com.freemud.api.assortment.datamanager.order.config.ManagerOrderBeanConfig;
import com.freemud.api.assortment.datamanager.order.manager.AssortmentOrderManager;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.couponcenter.offline.service.OfflineCouponSdkService;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
import com.freemud.application.sdk.api.membercenter.service.MemberPropertyService;
import com.freemud.application.sdk.api.membercenter.service.MemberScoreService;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.service.OrderDownLoadSdkService;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest;
import com.freemud.application.sdk.api.promotioncenter.service.PromotionSdkService;
import com.freemud.application.sdk.api.stockapi.service.StockSdkService;
import com.freemud.application.sdk.api.storecenter.request.vo.GetOrgTreeListRequest;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.application.sdk.api.structure.service.MessageCenterClient;
import com.freemud.sdk.api.assortment.order.adapter.ActivitySdkAdapter;
import com.freemud.sdk.api.assortment.order.adapter.MemberSdkAdapter;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
import com.freemud.sdk.api.assortment.order.enums.ResponseResult;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.response.order.BaseOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant.RESPONSE_SUCCESS;
import static com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant.RESPONSE_SUCCESS_STR;

@Import(ManagerOrderBeanConfig.class)
@Service
public class MCCafeOrderCenterSdkServiceImpl implements MCCafeOrderCenterSdkService {

    @Autowired
    private StockSdkService stockSdkService;
    @Autowired
    private PromotionSdkService promotionSdkService;
    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private MemberSdkAdapter memberSdkAdapter;
    @Autowired
    private ActivitySdkAdapter activitySdkAdapter;
    @Autowired
    private MQService mqService;
    @Autowired
    private MemberScoreService memberScoreService;
    @Autowired
    private MemberPropertyService memberPropertyService;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private OrderDownLoadSdkService orderDownLoadSdkService;
    @Autowired
    private MealCacheManager mealCacheManager;
    @Autowired
    private AssortmentOrderManager assortmentOrderManager;
    @Autowired(required = false)
    private MessageCenterClient messageCenterClient;
    @Autowired
    private AssortmentCustomerInfoManager assortmentCustomerInfoManager;
    @Autowired
    private MemberCenterService memberCenterService;
    @Autowired
    private OfflineCouponSdkService offlineCouponSdkService;
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private CouponClientService couponClientService;

    @Override
    public CreateOrderResponse createMCCafeOrderFlow(CreateOrderRequest config) {
        com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest request = orderSdkAdapter.convent2NEWCreateMCCafeOrderRequest(config.getBaseCreateOrderRequest());
        com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp<OrderInfoReqs> order = orderSdkService.createOrder(request, config.getTrackingNo());
        CreateOrderResponse createOrderResponse = orderSdkAdapter.convent2NEWOrderInfoReqs(order);
        if (!RESPONSE_SUCCESS.equals(createOrderResponse.getErrcode())
                || createOrderResponse.getData() == null) {
            return getCreateOrderResponse(createOrderResponse.getErrcode().toString(), createOrderResponse.getErrmsg(), null);
        }
        return createOrderResponse;
    }

    private BaseOrderResponse updateMCCafeStockAndScore(OrderBeanV1 orderBean, List<CreateOrderProductRequest> products, ActivityUpdateStockRequest updateStockRequest,
                                                        List<CreateOrderAccountRequest> accounts, MqMessageRequest mqMessageRequest, String menuType) {
//        //TODO 转换获取库存信息,扣减库存
//        UpdateStocksRequest updateStocksRequest = orderSdkAdapter.getUpdateProductStock(orderBean, products, StockChangeType.REDUCE,menuType);
//        if (updateStocksRequest != null && CollectionUtils.isNotEmpty(updateStocksRequest.getProductStocks())) {
//            BaseResponse baseResponse = stockSdkService.reducesStocks(updateStocksRequest, "");
//            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
//                    "updateStock", JSONObject.toJSONString(updateStocksRequest), JSONObject.toJSONString(baseResponse));
//            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
//                //TODO 失败取消订单
//                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
//                        AfterSalesType.SYSTEM_CANCEL, "商品库存不足", "", null);
//                orderCenterSdkService.orderCancel(cancelOrderRequest);
//                return BaseOrderResponse.getErrorBaseOrderResponse(baseResponse.getCode(), "商品库存不足");
//            }
//        }
//        //TODO 扣减活动库存
//        ActivityUpdateStockRequest activityUpdateStockRequest = orderSdkAdapter.convert2ActivityUpdateStockRequest(orderBean, updateStockRequest);
//        if (activityUpdateStockRequest != null && CollectionUtils.isNotEmpty(activityUpdateStockRequest.getStock())) {
//            BaseResponse activityResponse = promotionSdkService.subtractStock(activityUpdateStockRequest, "");
//            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
//                    "subtractStock", JSONObject.toJSONString(activityUpdateStockRequest), JSONObject.toJSONString(activityResponse));
//            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, activityResponse.getCode())) {
//                //TODO 失败取消订单,异步冲正库存
//                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
//                        AfterSalesType.SYSTEM_CANCEL, "活动库存不足", "", null);
//                orderCenterSdkService.orderCancel(cancelOrderRequest);
//                //失败异步冲正库存，取消订单
//                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
//                return BaseOrderResponse.getErrorBaseOrderResponse(activityResponse.getCode(), "活动库存不足");
//            }
//        }
        // 扣减积分，扣减失败冲正积分返回错误
//        UseScoreRequest userScoreRequest = orderSdkAdapter.convent2UserScoreRequest(orderBean, accounts, true);
//        if (userScoreRequest != null) {
//            BaseResponse userScoreResponse = memberScoreService.useScore(userScoreRequest, "");
//            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, userScoreResponse.getCode())) {
//                //TODO 失败取消订单,异步冲正库存
//                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
//                        AfterSalesType.SYSTEM_CANCEL, "积分不足", "", null);
//                orderCenterSdkService.orderCancel(cancelOrderRequest);
//                //失败异步冲正库存，取消订单
//                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
//                return BaseOrderResponse.getErrorBaseOrderResponse(userScoreResponse.getCode(), "积分不足");
//            }
//        }

//        CouponBaseResponse couponBaseResponse = couponClientService.lock(orderBean, accounts);
//        if (couponBaseResponse!=null){
//
//            if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponBaseResponse.getStatusCode())) {
//                //TODO 失败取消订单,异步冲正库存
//                CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
//                        AfterSalesType.SYSTEM_CANCEL, "冻结券码失败", "", null);
//                orderCenterSdkService.orderCancel(cancelOrderRequest);
//                //失败异步冲正库存，取消订单
//                backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
//                return BaseOrderResponse.getErrorBaseOrderResponse(couponBaseResponse.getStatusCode(), "冻结券码失败");
//            }
//        }

        // 如果是到店，则冻结优惠券，失败提示下单失败并冲正库存积分等
        // 如果是外卖，则核销优惠券，失败提示下单失败并冲正库存积分等
//        if(OldOrderType.TAKE_OUT.getCode().equals(orderBean.getType())) {
//            CouponRedeemResponse couponRedeemResponse = couponClientService.redeemBatch(orderBean, accounts);
//
//            if (couponRedeemResponse!=null){
//
//                if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponRedeemResponse.getStatusCode())) {
//                    //TODO 失败取消订单,异步冲正库存
//                    CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
//                            AfterSalesType.SYSTEM_CANCEL, "核销券码失败", "", null);
//                    orderCenterSdkService.orderCancel(cancelOrderRequest);
//                    //失败异步冲正库存，取消订单
//                    backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
//                    return BaseOrderResponse.getErrorBaseOrderResponse(couponRedeemResponse.getStatusCode(), "核销券码失败");
//                }
//            }
//        } else if(OldOrderType.COLLECT_GOODS.getCode().equals(orderBean.getType()) || OldOrderType.EAT_IN.getCode().equals(orderBean.getType())) {
//            CouponBaseResponse couponBaseResponse = couponClientService.lockBatch(orderBean, accounts);
//
//            if (couponBaseResponse!=null){
//
//                if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, couponBaseResponse.getStatusCode())) {
//                    //TODO 失败取消订单,异步冲正库存
//                    CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
//                            AfterSalesType.SYSTEM_CANCEL, "冻结券码失败", "", null);
//                    orderCenterSdkService.orderCancel(cancelOrderRequest);
//                    //失败异步冲正库存，取消订单
//                    backOrdersNotifyActivity(orderBean, mqMessageRequest.getBackOrdersNotifyActivityQueue(), mqMessageRequest.getBackOrdersNotifyActivityExchange());
//                    return BaseOrderResponse.getErrorBaseOrderResponse(couponBaseResponse.getStatusCode(), "冻结券码失败");
//                }
//            }
//        }

        return BaseOrderResponse.getErrorBaseOrderResponse(RESPONSE_SUCCESS_STR, "");
    }


    private void backOrdersNotifyActivity(OrderBeanV1 orderBean, String backOrdersChangeOrderStatusConsumerQueue, String backOrdersNotifyActivityExchange) {
        if (null == orderBean || backOrdersChangeOrderStatusConsumerQueue == null || backOrdersNotifyActivityExchange == null) {
            return;
        }
        String oid = orderBean.getOid();
        Integer status = orderBean.getStatus();
        if (StringUtils.isEmpty(oid)) {
            return;
        }
        AppLogUtil.infoLog("backOrdersStatusChange", oid, String.valueOf(status));
        OrderStatusChangeRequestDto requestDto = new OrderStatusChangeRequestDto();
        requestDto.setOid(oid);
        requestDto.setOrderStatus(status);
        try {
            Header header = new Header(MQAction.INSERT.getAction(), "backOrdersStatusChange", oid, backOrdersChangeOrderStatusConsumerQueue);
            MQMessage<OrderStatusChangeRequestDto> message = new MQMessage<>(header, requestDto);
            mqService.convertAndSend(backOrdersNotifyActivityExchange, backOrdersChangeOrderStatusConsumerQueue, message);
        } catch (Exception e) {
            //TODO 邮件告警
            ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                    "backOrdersStatusChangeNotify_error", backOrdersNotifyActivityExchange, backOrdersChangeOrderStatusConsumerQueue);
        }
    }

    private CreateOrderResponse getCreateOrderResponse(String code, String message, OrderBeanV1 data) {
        CreateOrderResponse baseOrderResponse = new CreateOrderResponse();
        baseOrderResponse.setErrcode(Integer.valueOf(code));
        baseOrderResponse.setErrmsg(message);
        baseOrderResponse.setData(data);
        return baseOrderResponse;
    }

    /**
     * 查询门店的组织机构
     * @param partnerId
     * @param storeCode
     * @return
     */
    private List<String> getOrgIds(String partnerId, String storeCode) {
        GetOrgTreeListRequest request = new GetOrgTreeListRequest();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeCode);
        BaseResponse<List<String>> orgList = storeCenterService.getOrgList(request, LogThreadLocal.getTrackingNo());
        if (orgList != null && ResponseResult.SUCCESS.getCode().equals(orgList.getCode())) {
            return orgList.getData();
        }
        return null;
    }
}
