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 com.freemud.application.sdk.api.couponcenter.offline.response.CouponRedeemResponse;
import com.freemud.sdk.api.assortment.order.enums.OldOrderType;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.alibaba.fastjson.JSONObject;
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.response.CouponBaseResponse;
import com.freemud.application.sdk.api.couponcenter.offline.service.OfflineCouponSdkService;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
import com.freemud.application.sdk.api.membercenter.request.UserScoreRequest;
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.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateFatherSonOrderReq;
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.request.UpdateStocksRequest;
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.enums.StockChangeType;
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.CreateFatherSonOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
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.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

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.convent2NEWCreateOrderRequest(config.getBaseCreateOrderRequest());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<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);
        }
        BaseOrderResponse baseOrderResponse = updateMCCafeStockAndScore(createOrderResponse.getData(), config.getBaseCreateOrderRequest().getProducts(), config.getBaseCreateOrderRequest().getActivityUpdateStockRequest(),
                config.getBaseCreateOrderRequest().getAccounts(), config.getMqMessageRequest(),config.getBaseCreateOrderRequest().getMenuType());
        if (!RESPONSE_SUCCESS.equals(baseOrderResponse.getErrcode())) {
            return getCreateOrderResponse(baseOrderResponse.getErrcode().toString(), baseOrderResponse.getErrmsg(), null);
        }
        return createOrderResponse;
    }

    private BaseOrderResponse updateMCCafeStockAndScore(QueryOrdersResponse.DataBean.OrderBean 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(), "活动库存不足");
            }
        }
        // 扣减积分，扣减失败冲正积分返回错误
        UserScoreRequest 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(QueryOrdersResponse.DataBean.OrderBean 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;
        }
        ApiLog.info("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, QueryOrdersResponse.DataBean.OrderBean 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;
    }
}
