package cn.freemud.consumer;

import cn.freemud.amp.body.OrderBody;
import cn.freemud.amp.constant.QueueMetadata;
import cn.freemud.amp.util.BodyConvertUtil;
import cn.freemud.amqp.MQMessage;
import cn.freemud.config.OrderReportFactory;
import cn.freemud.enums.OrderReportEnum;
import cn.freemud.enums.PayCodeEnum;
import cn.freemud.order.entity.OpenPlatformPartner;
import cn.freemud.order.entity.OpenPlatformPartnerPaymentAuth;
import cn.freemud.order.entity.OpenPlatformPartnerPaymentConfig;
import cn.freemud.order.entity.OpenPlatformPartnerReportDetail;
import cn.freemud.order.mapper.OpenPlatformPartnerDao;
import cn.freemud.order.mapper.OpenPlatformPartnerPaymentAuthDao;
import cn.freemud.order.mapper.OpenPlatformPartnerPaymentConfigDao;
import cn.freemud.order.mapper.OpenPlatformPartnerReportDetailDao;
import cn.freemud.resposne.SynchronizationOrderResponse;
import cn.freemud.service.SynchronizedOrderService;
import cn.freemud.util.UUIDUtil;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;

import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;


/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.freemud.mail.core
 * @Description: 微信订单数据上送消费者
 * @author: lox
 * @date: 2019/2/22 14:15
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
@Slf4j
public class WechatOrderPushConsumer {

    private static Gson gson = new Gson();


    @Autowired
    private OpenPlatformPartnerReportDetailDao assortmentOpenPlatformPartnerReportDetailManager;

    @Autowired
    private OpenPlatformPartnerPaymentConfigDao assortmentOpenPlatformPartnerPaymentConfigManager;

    @Autowired
    private OpenPlatformPartnerDao assortmentOpenPlatformPartnerManager;

    @Autowired
    private OpenPlatformPartnerPaymentAuthDao openPlatformPartnerPaymentAuthDao;

    @Autowired
    private StoreCenterService storeCenterService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QueueMetadata.WechatPush.WECHAT_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = QueueMetadata.EXCHANGE_NAME, type = ExchangeTypes.TOPIC, durable = "true"), key = QueueMetadata.WechatPush.WECHAT_QUEUE_NAME_ROUTING_KEY),
            containerFactory = "rabbitListenerContainerFactory", admin = "rabbitAdmin")
    @RabbitHandler
    public void message(Message message) {
        MQMessage<OrderBody> mqMessage = BodyConvertUtil.orderJsonStringConvertToOrderBody(message);
        OrderBody orderBody = mqMessage.getBody();
        if(orderBody == null || orderBody.getOrderBean() == null || orderBody.getSyncStatusInfo() == null){
            return;
        }
        OpenPlatformPartnerPaymentConfig configQuery = new OpenPlatformPartnerPaymentConfig();
        configQuery.setPartnerId(orderBody.getOrderBean().getCompanyId());
        configQuery.setAppId(orderBody.getSyncStatusInfo().getWxAppid());
        configQuery.setStatus((byte) 1);
        List<OpenPlatformPartnerPaymentConfig> configs = assortmentOpenPlatformPartnerPaymentConfigManager.select(configQuery);
        if (CollectionUtils.isEmpty(configs)) {
            this.orderReport(OrderReportEnum.SAOBEI, orderBody,"","","","","",1);
            this.orderReport(OrderReportEnum.WECHAT, orderBody,"","","","","",1);
            return;
        }
        OpenPlatformPartnerPaymentConfig config = configs.get(0);
        OpenPlatformPartnerPaymentAuth queryPaymentAuth = new OpenPlatformPartnerPaymentAuth();
        queryPaymentAuth.setId(config.getAuthId());
        OpenPlatformPartnerPaymentAuth paymentAuth = openPlatformPartnerPaymentAuthDao.selectOne(queryPaymentAuth);
        if(paymentAuth == null){
            log.error("WechatOrderPushConsumer body:{} 配置信息错误", JSONObject.toJSONString(orderBody));
            return;
        }
        OrderBody.SyncStatusInfo syncStatusInfo = orderBody.getSyncStatusInfo();
        syncStatusInfo.setMchId(paymentAuth.getSpMtchid());
        orderBody.seSyncStatusInfo(syncStatusInfo);

        this.orderReport(OrderReportEnum.WECHAT, orderBody, paymentAuth.getSpMtchid(), config.getSubMchid(),config.getAppId(), paymentAuth.getSerialNo(), paymentAuth.getPrivateKey(),paymentAuth.getType().intValue());

    }

    private void orderReport(OrderReportEnum orderReportEnum, OrderBody orderBody,String mtchId,String subMchId,String subAppid,String serialNo,String privateKey,Integer type) {
        Byte isSuccess = (byte) 1;
        SynchronizedOrderService synchronizedOrderService = OrderReportFactory.getSynchronizedOrderService(orderReportEnum);

        try {
            SynchronizationOrderResponse synchronizationOrderResponse = synchronizedOrderService.synchronizationOrder(UUIDUtil.getUUID(), orderBody,mtchId,subMchId,serialNo,privateKey,type);
            if (synchronizationOrderResponse == null || !synchronizationOrderResponse.getResult()) {
                isSuccess = (byte) 0;
                log.error("WechatOrderPushConsumer body:{} 发送失败", JSONObject.toJSONString(orderBody));
            }
        } catch (JSONException ex) {
            isSuccess = (byte) 0;
            log.error("WechatOrderPushConsumer error:{} 转换出错", ExceptionUtils.getStackTrace(ex));
        } catch (Exception e) {
            isSuccess = (byte) 0;
            log.error("WechatOrderPushConsumer body:{} error:{} 发送异常", JSONObject.toJSONString(orderBody), ExceptionUtils.getStackTrace(e));
        }
        this.addPartnerReportDetail(orderBody, isSuccess, subMchId,subAppid);
    }


    private void addPartnerReportDetail(OrderBody order, Byte status,String subMchid,String subAppid) {
        Byte reportType = (byte) 1;
        OrderBody.OrderBean orderBean = order.getOrderBean();
        if (orderBean.getStatus() == 1) {
            reportType = (byte) 2;
        }
        //String partnerId, String brandId, String brandName, String storeId,
        // String storeName, Byte reportType, Byte status, String orderId, String dealNo, String thirdDealNo
        String partnerName = "";
        String storeName = "";

        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(orderBean.getCompanyId());
        storeInfoRequest.setStoreCode(orderBean.getShopId());
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, UUIDUtil.getUUID());
        if (storeResponse != null && storeResponse.getStatusCode() == 100 && storeResponse.getBizVO() != null) {
            storeName = storeResponse.getBizVO().getStoreName();
        }
        OpenPlatformPartner queryPartner = new OpenPlatformPartner();
        queryPartner.setPartnerId(orderBean.getCompanyId());
        List<OpenPlatformPartner> partners = assortmentOpenPlatformPartnerManager.select(queryPartner);
;        if (!CollectionUtils.isEmpty(partners)) {
            partnerName = partners.get(0).getPartnerName();
        }
        OpenPlatformPartnerReportDetail detail = new OpenPlatformPartnerReportDetail();
        detail.setPartnerId(orderBean.getCompanyId());
        detail.setBrandName(partnerName);
        detail.setStoreId(orderBean.getShopId());
        detail.setStoreName(storeName);
        detail.setReportType(reportType);
        detail.setStatus(status);
        detail.setOrderId(orderBean.getOid());
        detail.setDealNo(order.getSyncStatusInfo().getOutTradeNo());
        detail.setThirdDealNo(order.getSyncStatusInfo().getEndTransId());
        detail.setWxOrderId(order.getSyncStatusInfo().getTransactionId());
        detail.setPayAmount(order.getOrderBean().getAmount());
        detail.setSubMchid(subMchid);
        detail.setSubAppid(subAppid);
        assortmentOpenPlatformPartnerReportDetailManager.insertSelective(detail);
    }


}
