package cn.pluss.platform.logist;

import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.device.MercOrderExpressDetailService;
import cn.pluss.platform.device.MercOrderExpressService;
import cn.pluss.platform.entity.MercOrderExpress;
import cn.pluss.platform.entity.MercOrderExpressDetail;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.util.XmlUtil;
import cn.pluss.platform.yt.*;
import cn.pluss.platform.yt.constant.YtConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * TODO
 * 物流快递回调处理业务类
 * @author crystal
 * @date 2022/3/24 14:39
 */
@Slf4j
@Component
public class LogistCallbackHandler {

    @Resource
    private YtLogistHandler ytLogistHandler;

    @Resource
    private MercOrderExpressService mercOrderExpressService;

    @Resource
    private MercOrderExpressDetailService mercOrderExpressDetailService;
    /**
     * 物流回调处理
     * @param entity
     * @return
     */
    public String execute(YtLogisticsEntity entity) {
        log.info("【圆通物流回调】回调参数:{}", JSON.toJSONString(entity));
        String reqData = entity.getLogistics_interface();
        YtUpdateInfo data = ytLogistHandler.resolvXml(reqData);
        try {
            log.info("[圆通物流回调]解析业务参数为:{}",JSON.toJSONString(data));
            String logistNo = data.getTxLogisticID();
            MsgException.checkBlank(logistNo,"上送物流单号为空！");
            MercOrderExpress express = mercOrderExpressService.getByLogistNo(logistNo);
            MsgException.checkNull(express,"该物流单号未匹配到对应的订单！");
            MercOrderExpressDetail detail = new MercOrderExpressDetail(data,express);
            mercOrderExpressDetailService.save(detail);
            String status = YtStatusEnum.getValueByCode(data.getInfoContent());
            if(!express.getStatus().equals(status)){
                express.setStatus(status);
                mercOrderExpressService.updateById(express);
            }
            YtLogisticsResponse resp = YtLogisticsResponse.build(data.getLogisticProviderID(), data.getTxLogisticID(), true, null);
            return XmlUtil.createXml(YtConstant.YT_RESPONSE_XML_ELEMENT, JSONObject.parseObject(JSON.toJSONString(resp), Map.class),StandardCharsets.UTF_8.toString());
        }catch (Exception e){
            YtLogisticsResponse resp = YtLogisticsResponse.build(data.getLogisticProviderID(), data.getTxLogisticID(), false, e.getMessage());
            return XmlUtil.createXml(YtConstant.YT_RESPONSE_XML_ELEMENT, JSONObject.parseObject(JSON.toJSONString(resp), Map.class),StandardCharsets.UTF_8.toString());
        }
    }
}
