package cn.freemud.service;

import cn.freemud.amp.body.OrderBody;
import cn.freemud.config.OpenStoreCloudService;
import cn.freemud.constant.OrderStatus;
import cn.freemud.request.CommonPushRequest;
import cn.freemud.request.CreateOrderCallbackVO;
import cn.freemud.request.OpenPlatformOrderPushConfigRequest;
import cn.freemud.request.OrderStatusChangeVO;
import cn.freemud.resposne.CommonPushResponse;
import cn.freemud.resposne.OpenPlatformOrderPushConfigResponse;
import cn.freemud.resposne.SynchronizationOrderResponse;
import cn.freemud.util.CustomBeanUtil;
import cn.freemud.util.RSACrypt;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title:
 * @Package: cn.freemud.service
 * @Descripttion:
 * @author: shuhu.hou
 * @date: 2019/4/28
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
@Service
public class OpenPlatformOrderPushServiceImpl implements SynchronizedOrderService {

    @Autowired
    private OpenStoreCloudService cloudService;
    @Value("${configuration.openPlatform.orderPush.url}")
    private String getConfigUrl;


    @Override
    public SynchronizationOrderResponse synchronizationOrder(String uuid, OrderBody orderBody,String mtchId,String subMchId,String serialNo,String privateKey,Integer type) {
        OpenPlatformOrderPushConfigResponse.Config callBackConfig = getCallBackConfig(orderBody.getOrderBean().getCompanyId(), orderBody.getOrderBean().getCompanyId());
        if (callBackConfig == null) {
            return new SynchronizationOrderResponse(false, "推送配置未配置或配置服务异常");
        }
        CommonPushRequest commonPushRequest = new CommonPushRequest();
        commonPushRequest.setVer("1");
        commonPushRequest.setPartnerId(orderBody.getOrderBean().getCompanyId());
        //todo: 暂时先用商户id
        commonPushRequest.setAppId(orderBody.getOrderBean().getCompanyId());
        commonPushRequest.setUrl(callBackConfig.getCallBackUrl());
        String requestBody;
        if (orderBody.getOrderBean().getStatus().equals(OrderStatus.ORDER)) {
            CreateOrderCallbackVO createOrderCallbackVO = new CreateOrderCallbackVO();
            createOrderCallbackVO.setAction("order.create");
            createOrderCallbackVO.setTimeStamp(System.currentTimeMillis() + "");
            createOrderCallbackVO.setStoreId(orderBody.getOrderBean().getShopId());
            createOrderCallbackVO.setOrderCode(orderBody.getOrderBean().getOid());
            requestBody = JSONObject.toJSONString(createOrderCallbackVO);
        } else {
            OrderStatusChangeVO orderStatusChangeVO = new OrderStatusChangeVO();
            orderStatusChangeVO.setAction("order.statusChange");
            orderStatusChangeVO.setOrderCode(orderBody.getOrderBean().getOid());
            orderStatusChangeVO.setStatusCode(orderBody.getOrderBean().getStatus().toString());
            orderStatusChangeVO.setStoreId(orderBody.getOrderBean().getShopId());
            orderStatusChangeVO.setTimeStamp(System.currentTimeMillis() + "");
            requestBody = JSONObject.toJSONString(orderStatusChangeVO);
        }
        commonPushRequest.setRequestBody(requestBody);
        String sign = createSign(requestBody, callBackConfig.getPublicKey(),uuid);
        if (!StringUtils.isEmpty(sign)) {
            return new SynchronizationOrderResponse(false, "加签失败");
        }
        commonPushRequest.setSign(sign);
        CommonPushResponse commonPushResponse = cloudService.doSend(uuid, callBackConfig.getCallBackUrl(), commonPushRequest, CommonPushResponse.class);
        if (!commonPushResponse.getStatusCode().equals("100")) {
            return new SynchronizationOrderResponse(false, commonPushResponse.getMessage());
        }
        return new SynchronizationOrderResponse(true, commonPushResponse.getMessage());
    }

    private OpenPlatformOrderPushConfigResponse.Config getCallBackConfig(String partnerId, String devId) {
        OpenPlatformOrderPushConfigRequest request = new OpenPlatformOrderPushConfigRequest();
        request.setDevId(devId);
        request.setPartnerId(partnerId);
        OpenPlatformOrderPushConfigResponse config = cloudService.getConfig("", getConfigUrl, request, OpenPlatformOrderPushConfigResponse.class);
        if (config != null && config.getStatusCode().equals("100")) {
            return config.getData();
        }
        return null;
    }

    private <T> String createSign(T requestBody, String publicKey,String uuid) {
        Map<String, Object> stringObjectMap = CustomBeanUtil.sortStrMapByKey(CustomBeanUtil.java2Map(requestBody));
        StringBuilder buf = new StringBuilder();
        for (String key : stringObjectMap.keySet()) {
            String val = stringObjectMap.get(key).toString();
            if (key.equals("sign")) {
                buf.append(key.toLowerCase() + "=" + val);
            }
            buf.append("&");
        }
        String buff = buf.toString();
        if (buff.equals("") == false) {
            buff = buff.substring(0, buff.length() - 1);
        }
        String sign;
        try {
            sign = RSACrypt.publicEncrypt(buff, RSACrypt.getPublicKey(publicKey));
        } catch (Exception e) {
            ErrorLog.infoConvertJson(SDKCommonBaseContextWare.getAppName(), LogThreadLocal.getTrackingNo(),
                    getClass(), "OpenPushOrderConsumer异常", e);
            sign = "";
        }
        return sign;
    }

}
