package com.prolog.cs.biz.outbound.service.impl.faceorder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.prolog.cs.basic.common.model.BaseCommonDict;
import com.prolog.cs.biz.outbound.model.dto.faceorder.DbFaceOrderAddDTO;
import com.prolog.cs.biz.outbound.model.dto.faceorder.SfFaceOrderAddDTO;
import com.prolog.cs.biz.outbound.model.entity.WmsFaceOrder;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import org.springframework.stereotype.Component;

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

/**
 * 德邦快递
 */
@Component
public class DbFaceOrderHandler extends BaseFaceOrderHandler{

    @Override
    String getUrl() {
        BaseCommonDict baseCommonDict = getRequestUrls().stream().filter(item -> "DBL".equals(item.getDictCode())).findFirst().orElse(null);
        if(baseCommonDict == null){
            throw new BizException("请配置德邦快递创建面单请求地址！");
        }
        return baseCommonDict.getDictName();
    }

    @Override
    public List<WmsFaceOrder> convertResult(JSONObject result) {
        RestMessage restMessage = JSON.parseObject(result.toJSONString(), RestMessage.class);
        if(restMessage == null || !restMessage.isSuccess() || restMessage.getData() == null){
            throw new BizException("请求面单失败!");
        }
        List<WmsFaceOrder> wmsFaceOrders = new ArrayList<>();

        Object data1 = restMessage.getData();
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(data1));
        Object obj = jsonArray.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));

        Object carrierSfResultInfo = jsonObject.get("carrierDbResultInfo");
        DbFaceOrderAddDTO dto = JSON.parseObject(JSON.toJSONString(carrierSfResultInfo),DbFaceOrderAddDTO.class);

        String[] waybillcodes = dto.getWayBillCode().split(",");
        for (String waybillcode : waybillcodes) {
            WmsFaceOrder faceOrder = new WmsFaceOrder();
            faceOrder.setWaybillCode(waybillcode);
            faceOrder.setParentWaybillCode(dto.getWayBillNo());

            wmsFaceOrders.add(faceOrder);
        }

        return wmsFaceOrders;
    }
}
