package cn.freemud.management.service;

import cn.freemud.management.adapter.MessagePushAdapter;
import cn.freemud.management.entities.dto.request.order.CalculateCenter;
import cn.freemud.management.enums.DeliveryStatus;
import cn.freemud.management.enums.OperateType;
import cn.freemud.management.enums.OrderSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.structure.request.PushMessageNoticeDto;
import com.freemud.application.sdk.api.structure.service.MessageCenterClient;
import com.freemud.sdk.api.assortment.message.request.MessagePushOrderTemplateRequest;
import com.freemud.sdk.api.assortment.message.request.MessageTemplateRequest;
import com.freemud.sdk.api.assortment.message.service.IMessageTemplatePushService;
import com.freemud.sdk.api.assortment.order.request.order.AssortmentUpdateDeliveryAbnormalRequest;
import com.freemud.sdk.api.assortment.order.request.order.BaseQueryOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.UpdateDeliveryInfoByIdRequest;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;


@Service
public class OrderBaseService {

    private static final int SUCCESS = 100;

    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private MessageCenterClient messageCenterClient;
    @Autowired
    private MessagePushAdapter messagePushAdapter;
    @Autowired
    @Qualifier("messageTemplatePushOrderService")
    private IMessageTemplatePushService<MessagePushOrderTemplateRequest> messageTemplatePushService;

    @Value("${saas.order.message.push}")
    private String pushConfig;

    public OrderBeanV1 getByOrderCode(String orderCode) {
        BaseQueryOrderRequest queryRequest = new BaseQueryOrderRequest();
        queryRequest.setOrderId(orderCode);
        QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(queryRequest);
        if (ObjectUtils.notEqual(response.getErrcode(), SUCCESS) || response.getData() == null) {
            return null;
        }
        return response.getData();
    }

    public void sendMessage(OrderBeanV1 orderBean, OperateType opType, String reason) {
        //发送消息到pos消息中心
        PushMessageNoticeDto pushMessageNoticeDto1 = null;
        try {
            pushMessageNoticeDto1 = messagePushAdapter.convent2PushMessageNoticeDto1(orderBean, opType);
            messageCenterClient.createMessage(pushMessageNoticeDto1, LogThreadLocal.getTrackingNo());
        } catch (Exception e) {
            ErrorLog.printErrorLog("sendMessageCenterError", "", pushMessageNoticeDto1, e);
        }

        //订阅消息改造，走订单回调order-call-back-queue,迁移成功代码删除
        if(!grayPush(orderBean.getCompanyId(),orderBean.getShopId(),pushConfig)){
            return;
        }
        //发送微信模板消息
        if (orderBean.getExtInfo() != null && !(OrderSource.SAAS.getSource().equals(orderBean.getSource()) || OrderSource.ALIPAY.getSource().equals(orderBean.getSource()))) {
            return;
        }
        MessageTemplateRequest<MessagePushOrderTemplateRequest> messageTemplateRequest = null;
        try {
            messageTemplateRequest = messagePushAdapter.convent2MessageTemplateRequest(orderBean, reason, opType);
            if (messageTemplateRequest!=null && messageTemplateRequest.getMessageEventType() != null) {
                BaseResponse baseResponse = messageTemplatePushService.sendTemplateMsg(messageTemplateRequest);
                if(baseResponse != null && !ResponseResultEnum.SUCCESS.getCode().equals(baseResponse.getCode())){
                    ApiLog.printLog("sendTemplateMsg",orderBean.getOid(), JSONObject.toJSONString(baseResponse),null);
                }
            }
        } catch (Exception e) {
            ErrorLog.printErrorLog("sendTemplateMsgError", "", messageTemplateRequest, e);
        }

    }

    /**
     * 创建配送单一车 -> 更新订单为异常单
     *
     * @param partnerId
     * @param orderCode
     * @param deliveryId
     */
    public void updateDeliveryAbnormal(String partnerId, String orderCode, String deliveryId, String operator,String msg) {
        AssortmentUpdateDeliveryAbnormalRequest request = AssortmentUpdateDeliveryAbnormalRequest.builder()
                .abnormalDesc("配送异常"+ msg)
                .deliveryId(deliveryId)
                .orderCode(orderCode)
                .partnerId(partnerId)
                .operator(StringUtils.isNotBlank(operator) ? operator : "sys")
                .build();
        orderCenterSdkService.updateDeliveryAbnormal(request);
    }

    /**
     * 创建配送单成功后 -> 更新订单配送信息
     *
     * @param orderCode
     * @param deliveryId
     */
    public void updateDeliverySuccess(String orderCode, String deliveryId, String operator) {
        // 创建配送单成功
        UpdateDeliveryInfoByIdRequest updateDeliveryInfoByIdRequest = new UpdateDeliveryInfoByIdRequest();
        updateDeliveryInfoByIdRequest.setDeliveryId(deliveryId);
        updateDeliveryInfoByIdRequest.setOrderId(orderCode);
        updateDeliveryInfoByIdRequest.setOrderSubState(DeliveryStatus.WATINGORDER.getCode());
        operator = StringUtils.isNotBlank(operator) ? operator : "sys";
        updateDeliveryInfoByIdRequest.setOperator(operator);
        updateDeliveryInfoByIdRequest.setRemark("创建运单成功");
        orderCenterSdkService.updateDeliveryInfoById(updateDeliveryInfoByIdRequest);
    }

    public boolean grayPush(String partnerId, String storeId,String config) {
        if (StringUtils.isBlank(config)) return false;
        CalculateCenter center = JSON.parseObject(config, CalculateCenter.class);
        Boolean enable = false;
        if (!center.getEnable()) return false;
        switch (center.getType()) {
            case 2:
                enable = true;
                break;
            case 1: {
                //商户+门店级别
                String real = partnerId.concat(storeId);
                if (Arrays.asList(center.getGrayList().split(",")).contains(real)) {
                    enable = true;
                }
                //商户级别
                else if (Arrays.asList(center.getGrayList().split(",")).contains(partnerId)) {
                    enable = true;
                }
            }
        }
        if (center.getEnable() && enable) {
            enable = true;
        }
        return enable;
    }
}
