package com.ms.biz.spi.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinritemai.cloud.base.api.BaseRequest;
import com.jinritemai.cloud.base.api.BaseResponse;
import com.jinritemai.cloud.base.api.ExtensionService;
import com.jinritemai.cloud.base.api.ExtensionServiceHandler;
import com.ms.biz.common.R;
import com.ms.biz.common.Ret;
import com.ms.biz.common.SPIBaseService;
import com.ms.api.dto.dsorder.DsMessageCallbackDTO;
import com.ms.api.dto.dsorder.DsMessageCallbackRequestDTO;
import com.ms.biz.service.DsMessageService;
import com.ms.biz.tool.CommonTool;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 1688分销采购单消息
 * @author elf
 */
@ExtensionService("dsMessageCallback")
@Slf4j
@AllArgsConstructor
public class DsMessageCallbackService extends SPIBaseService implements ExtensionServiceHandler<DsMessageCallbackRequestDTO, Ret> {
    private DsMessageService dsMessageService;

    @Override
    public BaseResponse<Ret> handle(BaseRequest<DsMessageCallbackRequestDTO> req) {
        log.info("DsMessageCallbackRequestDTO: " + req);
        try {
            DsMessageCallbackRequestDTO request =  req.getData();
            log.info("receiveCallback: " + JSON.toJSONString(request));
            String body = request.getBody();
            DsMessageCallbackDTO message = JSONObject.parseObject(body, DsMessageCallbackDTO.class);
            log.info("DsMessageCallbackDTO: " + JSON.toJSONString(message));
            dsMessageService.addDsMessage(message.getShopId(), message.getPlatformPushMsgId(), message.getBizId(), message.getBizType(), message.getData());
            return R.ok(CommonTool.successResult());
        } catch (RuntimeException e) {
            log.error("dsMessageCallbackError", e);
            return R.ok(Ret.fail(e.getMessage()));
        } catch (Throwable e) {
            log.error("dsMessageCallbackError", e);
            return R.ok(Ret.fail("系统异常"));
        }
    }
}
