/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: OrderCallBackMQService
 * @Package cn.freemud.amp.service
 * @Description:
 * @author: ping.wu
 * @date: 2019/4/16 14:29
 * @version V1.0
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.amp.service;

import cn.freemud.amp.config.OrderCallBackConfig;
import cn.freemud.amqp.Header;
import cn.freemud.amqp.MQAction;
import cn.freemud.amqp.MQMessage;
import cn.freemud.amqp.MQService;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.entities.dto.OrderExtInfoDto;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.WechatReportOrderDto;
import cn.freemud.entities.vo.OrderCallBackRequestVo;
import cn.freemud.redis.RedisCache;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformWxapp;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformWxappManager;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.NewOrderStatus;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderItemResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderSettlementResp;
import com.freemud.sdk.api.assortment.orderdistributor.request.DisRequest;
import com.freemud.sdk.api.assortment.orderdistributor.service.OrderDistributionService;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class OrderCallBackMQService {
    private static ApplicationContext context;

    @Autowired
    private MQService mqService;

    @Autowired
    private OrderDistributionService orderDistributionService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private AssortmentOpenPlatformWxappManager openPlatformWxappManager;

    public void sendOrderMQ(OrderCallBackRequestVo body) {
        //发送订单回调
        Header header = new Header(MQAction.UPDATE.getAction(), "call-back-service-api",
                OrderCallBackConfig.QUEUE_ROUTING_KEY, OrderCallBackConfig.QUEUE_NAME);
        MQMessage<OrderCallBackRequestVo> message = new MQMessage<>(header, body);
        mqService.convertAndSend(OrderCallBackConfig.EXCHANGE_NAME, OrderCallBackConfig.QUEUE_ROUTING_KEY, message);
        //订单状态变更通知开放平台
        OrderInfoReqs orderInfoReqs = getOrderInfoReqs(body);
        if (orderInfoReqs != null) {
            orderDistributionService.pushOrder(convent2DisRequest(body, orderInfoReqs.getOrderState()));
        }
        //微信数据上传（创建新订单&支付成功时上传）
        sendWechatReportMQ(body);
    }
    private void sendWechatReportMQ(OrderCallBackRequestVo body) {
        try {
            OrderInfoReqs orderInfoReqs = getWechatReportOrderInfoReqs(body);
            if (orderInfoReqs != null) {
                OrderExtInfoDto orderExtInfoDto = JSONObject.parseObject(orderInfoReqs.getExtInfo(), OrderExtInfoDto.class);
                UserLoginInfoDto userLoginInfoDto = getUserLoginInfoBySessionId(orderExtInfoDto.getSessionId());
                WechatReportOrderDto wechatReportOrderDto = getWechatReportOrderDto(orderInfoReqs, orderExtInfoDto, userLoginInfoDto);
                Header header = new Header(MQAction.UPDATE.getAction(), "call-back-service-api",
                        OrderCallBackConfig.QUEUE_ROUTING_KEY, OrderCallBackConfig.QUEUE_NAME);
                MQMessage<WechatReportOrderDto> message = new MQMessage<>(header, wechatReportOrderDto);
                mqService.convertAndSend(OrderCallBackConfig.TOPIC_EXCHANGE_NAME, OrderCallBackConfig.WECHAT_REPORT_QUEUE_ROUTING_KEY, message);
            }
        } catch (Exception ex) {
            ErrorLog.printErrorLog("sendWechatReportMQError",body.getOrderCode(),body,ex);
        }
    }
    private DisRequest convent2DisRequest(OrderCallBackRequestVo orderBean, Integer orderState) {
        DisRequest disRequest = new DisRequest();
        disRequest.setExtJson(orderBean.getContent());
        disRequest.setStatus(orderState.toString());
        disRequest.setPartnerId(orderBean.getPartnerId());
        disRequest.setOrderCode(orderBean.getOrderCode());
        disRequest.setVer("2");
        disRequest.setOperateType(orderBean.getOperateType().toString());
        return disRequest;
    }

    private OrderInfoReqs getOrderInfoReqs(OrderCallBackRequestVo body) {
        // 订单所有状态正常变化通知通知开放平台
        if (!ObjectUtils.equals("1", body.getMsgType()) || body.getOperateType() == null || body.getOperateType() == 0) {
            return null;
        }
        OrderInfoReqs orderInfoReqs = null;
        try {
            orderInfoReqs = JSONObject.parseObject(body.getContent(), OrderInfoReqs.class);
        } catch (Exception ex) {
            ErrorLog.infoConvertJson(context.getEnvironment().getProperty("spring.application.name"), LogThreadLocal.getTrackingNo(), this.getClass(), "parseObjectOrderInfoReqsError", ex);
            return null;
        }
        // 未支付订单不通知开放平台
        if (ObjectUtils.equals(1, orderInfoReqs.getPayState()) || ObjectUtils.equals(NewOrderStatus.PENDING_PAYMENT.getIndex(), orderInfoReqs.getOrderState())) {
            return null;
        }
        return orderInfoReqs;
    }

    private OrderInfoReqs getWechatReportOrderInfoReqs(OrderCallBackRequestVo body) {
        // 订单所有状态正常变化通知通知开放平台
        if (!ObjectUtils.equals("1", body.getMsgType()) || body.getOperateType() == null || body.getOperateType() == 2) {
            return null;
        }
        try {
            OrderInfoReqs orderInfoReqs = JSONObject.parseObject(body.getContent(), OrderInfoReqs.class);
            if (orderInfoReqs != null && OrderClientType.SAAS.getIndex().equals(orderInfoReqs.getOrderClient()) &&
                    ((body.getOperateType() == 0 && NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderInfoReqs.getOrderState())) ||
                            (body.getOperateType() == 1 && NewOrderStatus.PLACE_AN_ORDER.getIndex().equals(orderInfoReqs.getOrderState())))) {
                return orderInfoReqs;
            }
        } catch (Exception ex) {
            ErrorLog.infoConvertJson(context.getEnvironment().getProperty("spring.application.name"), LogThreadLocal.getTrackingNo(), this.getClass(), "parseObjectOrderInfoReqsError", ex);
            return null;
        }
        return null;
    }

    private UserLoginInfoDto getUserLoginInfoBySessionId(String sessionId) {
        String redisKey = RedisKeyConstant.SAAS_USER_INFO_SESSIONID_KEY_PREFIX + sessionId;
        Map<String, Object> map = redisCache.getValue(redisKey);
        UserLoginInfoDto userLoginInfoDto = new UserLoginInfoDto();
        userLoginInfoDto.setOpenId(String.valueOf(map.get("openid")));
        userLoginInfoDto.setWxAppid(String.valueOf(map.get("wxAppid")));
        userLoginInfoDto.setSessionKey(String.valueOf(map.get("session_key")));
        userLoginInfoDto.setMobile(String.valueOf(map.get("mobile")));
        userLoginInfoDto.setAppsecret(String.valueOf(map.get("appsecret")));
        userLoginInfoDto.setMemberId(String.valueOf(map.get("memberId")));
        userLoginInfoDto.setPartnerId(String.valueOf(map.get("partnerId")));
        userLoginInfoDto.setUnionId(String.valueOf(map.get("unionId")));
        userLoginInfoDto.setNewMemeber(Boolean.valueOf(map.get("newMember").toString()));
        userLoginInfoDto.setNickName(String.valueOf(map.get("nickName")));
        return userLoginInfoDto;
    }

    private WechatReportOrderDto getWechatReportOrderDto(OrderInfoReqs orderInfoReqs, OrderExtInfoDto orderExtInfoDto, UserLoginInfoDto userLoginInfoDto) {
        WechatReportOrderDto wechatReportOrderDto = new WechatReportOrderDto();
        wechatReportOrderDto.setAppId(userLoginInfoDto.getWxAppid());
        wechatReportOrderDto.setPartnerId(orderInfoReqs.getPartnerId());
        wechatReportOrderDto.setShopId(orderInfoReqs.getStoreId());
        wechatReportOrderDto.setSubMchId(orderExtInfoDto.getPlatformMchId());
        wechatReportOrderDto.setGmtCreate(Long.parseLong(orderInfoReqs.getCreateTime()));
        if (StringUtils.isBlank(orderExtInfoDto.getPlatformMchId())) {
            // 获取当前商户微信支付mchId
            AssortmentOpenPlatformWxapp wxApp = openPlatformWxappManager.findByPartnerIdAndWxappId(userLoginInfoDto.getPartnerId(), userLoginInfoDto.getWxAppid());
            wechatReportOrderDto.setSubMchId(wxApp == null ? "" : wxApp.getMchId());
        }
        wechatReportOrderDto.setPayVoucher(orderInfoReqs.getPayRequestNo());
        wechatReportOrderDto.setSubAppId(userLoginInfoDto.getWxAppid());
        wechatReportOrderDto.setOutShopNo(orderInfoReqs.getStoreId());
        wechatReportOrderDto.setSubOpenId(userLoginInfoDto.getOpenId());
        wechatReportOrderDto.setLoginToken(userLoginInfoDto.getSessionKey());
        wechatReportOrderDto.setUserAmount(orderInfoReqs.getSettlementAmount().intValue());
        wechatReportOrderDto.setOutOrderNo(orderInfoReqs.getOrderCode());
        wechatReportOrderDto.setTransactionId(orderExtInfoDto.getPaid_no());
        wechatReportOrderDto.setOutTradeNo(orderExtInfoDto.getPayTransId());

        // 计算优惠金额
        int discountAmount = 0;
        List<OrderSettlementResp> accountList = orderInfoReqs.getOrderSettlementDetailList();
        if(accountList != null && !CollectionUtils.isEmpty(accountList)) {
            for(OrderSettlementResp accountBean : accountList) {
                try {
                    Long price = accountBean.getSettlementAmount() == null ? 0 : accountBean.getSettlementAmount().longValue();
                    if(price < 0) {
                        discountAmount = discountAmount - price.intValue();
                    }
                } catch (Exception e) {
                }
            }
        }
        wechatReportOrderDto.setTotalAmount(discountAmount+orderInfoReqs.getSettlementAmount().intValue());
        wechatReportOrderDto.setDiscountAmount(discountAmount);
        //订单状态 (2—用户下单；1—支付完成)
        wechatReportOrderDto.setStatus(NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderInfoReqs.getOrderState()) ? 2 : 1);
        // 菜品列表
        List<WechatReportOrderDto.DishInfo> dishList = new ArrayList<>();
        for (OrderItemResp item : orderInfoReqs.getOrderItemList()) {
            WechatReportOrderDto.DishInfo dishInfo = new WechatReportOrderDto.DishInfo();
            dishInfo.setOutDishNo(item.getProductId());
            dishInfo.setCount(item.getProductQuantity());
            dishInfo.setName(item.getProductName());
            dishInfo.setPrice(item.getProductPrice().intValue());
            dishList.add(dishInfo);
        }
        wechatReportOrderDto.setDishList(dishList);
        return wechatReportOrderDto;
    }
}
