package com.seer.teach.mall.shipping.jt.service;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.exception.RemoteCallException;
import com.seer.teach.mall.service.ILogisticsService;
import com.seer.teach.mall.shipping.jt.client.JtExpressExecutor;
import com.seer.teach.mall.shipping.jt.config.JtSdkConfig;
import com.seer.teach.mall.shipping.jt.exception.JtApiException;
import com.seer.teach.mall.shipping.jt.requet.Item;
import com.seer.teach.mall.shipping.jt.requet.JsLogisticsRequest;
import com.seer.teach.mall.shipping.jt.requet.Receiver;
import com.seer.teach.mall.shipping.jt.requet.Sender;
import com.seer.teach.mall.shipping.jt.resp.BillRespData;
import com.seer.teach.mall.shipping.jt.resp.TraceResp;
import com.seer.teach.mall.entity.OrderEntity;
import com.seer.teach.mall.entity.OrderGoodsEntity;
import com.seer.teach.mall.entity.SenderConfigEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class JTLogisticsServiceImpl implements ILogisticsService {

    private final JtExpressExecutor executor;

    private final JtSdkConfig jtSdkConfig;

    /**
     * 创建极兔订单
     *
     * @param order
     */
    @Override
    public String submitOrder(OrderEntity order, List<OrderGoodsEntity> orderGoodsEntityList, SenderConfigEntity senderConfig) {
        JsLogisticsRequest request = new JsLogisticsRequest();

        request.setTxlogisticId(order.getOrderSn());
        request.setExpressType(JtExpressEnums.ExpressType.STANDARD.getCode());
        request.setOrderType(JtExpressEnums.OrderType.MONTHLY_SETTLEMENT.getCode());
        request.setDeliveryType(JtExpressEnums.DeliveryType.DELIVERY_TO_HOME.getCode());
        request.setServiceType(JtExpressEnums.ServiceType.DOOR_PICKUP.getCode());
        request.setGoodsType(JtExpressEnums.GoodsType.DAILY_NECESSITIES.getCode());
        request.setPayType(JtExpressEnums.PayType.PREPAID_MONTHLY.getCode());
       // req.setWeight(channel.getWeight());

        Sender sender = new Sender();
        sender.setName(senderConfig.getName());
        sender.setMobile(senderConfig.getMobile());
        sender.setPhone(senderConfig.getPhone());
        sender.setCountryCode(senderConfig.getCountryCode());
        sender.setProv(senderConfig.getProv());
        sender.setCity(senderConfig.getCity());
        sender.setArea(senderConfig.getArea());
        sender.setAddress(senderConfig.getAddress());
        request.setSender(sender);

        Receiver receiver = new Receiver();
        receiver.setName(order.getConsignee());
        receiver.setMobile(order.getMobile());
        receiver.setPhone(order.getMobile());
        receiver.setCountryCode("CHN");
        receiver.setProv(order.getProvince());
        receiver.setCity(order.getCity());
        receiver.setArea(order.getDistrict());
        receiver.setAddress(order.getAddress());

        request.setReceiver(receiver);

        List<Item> items = new ArrayList<>();
        for (OrderGoodsEntity goods : orderGoodsEntityList) {
            Item item = new Item();
            item.setItemName(goods.getGoodsName());
            item.setNumber(goods.getNumber());
        }
        request.setItems(items);
        try {
            String resultStr = executor.executorAuth(BeanUtil.beanToMap(request), jtSdkConfig.getCreateOrderUrl());
            log.info("极兔订单创建结果：{}",resultStr);
            JSONObject jsonObject = JSONObject.parse(resultStr);
            if( Objects.nonNull(jsonObject) && jsonObject.containsKey("data")){
                JSONObject data = jsonObject.getJSONObject("data");
                if( Objects.nonNull(data)){
                    BillRespData billRespData = data.toJavaObject(BillRespData.class);
                    return billRespData.getBillCode();
                }
            }
            throw new JtApiException(jsonObject.getString("msg"));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CommonException(ResultCodeEnum.JT_CREATE_ORDER_ERROR);
        }
    }

    @Override
    public List<TraceResp> queryLogisticsTrace(String billCode) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("billCodes",billCode);
        try {
            JSONObject jsonObject = JSONObject.parse(executor.executor(requestMap, jtSdkConfig.getQueryTraceUrl()));
            log.info("极兔订单轨迹查询结果：{}",jsonObject.toJSONString());
            JSONArray data = jsonObject.getJSONArray("data");
            if (data == null || data.isEmpty()) {
                return Collections.emptyList();
            }
            JSONObject details = data.getJSONObject(0);
            return details.getList("details",TraceResp.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new CommonException(ResultCodeEnum.JT_QUERY_TRACE_ERROR);
        }
    }
}