package org.dromara.job.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.*;
import com.google.j2objc.annotations.LoopTranslation;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddOrderListGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddOrderNumberListIncrementGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddOrderListGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddOrderNumberListIncrementGetResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.aspectj.weaver.Utils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.translation.annotation.Translation;
import org.dromara.job.mapper.ShopOrderDetailMapper;
import org.dromara.job.mapper.ShopOrderMapper;
import org.dromara.job.service.IPddService;
import org.dromara.zhishu.domain.TShopOrder;
import org.dromara.zhishu.domain.TShopOrderDetail;
import org.dromara.zhishu.enums.PddOrderEnum;
import org.dromara.zhishu.enums.PddResCodeEnum;
import org.dromara.zhishu.util.JsonObjUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.dromara.job.domains.ShopOrderVO;


import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;


@RequiredArgsConstructor
@Log4j2
@Service("pddJobServiceImpl")
public class PddServiceImpl implements IPddService {

    private final ShopOrderMapper shopOrderMapper;
    private final ShopOrderDetailMapper shopOrderDetailMapper;

    //同步三个月以内历史订单（根据成交时间）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getConfirmOrderList(ShopOrderVO orderVO) throws Exception {
        //todo 租户编码暂时写死tenant_id 000000
        String clientId = "203c5a7ba8bd4b8488d5e26f93052642";
        String clientSecret = "892ffaa86e12b7a3d8d2942b669d9aa520ad8179";
//        String accessToken = "6778e421d0ac477e81fb009418ca8f056842cba0";
        PopClient client = new PopHttpClient(clientId, clientSecret);

        PddOrderListGetRequest request = new PddOrderListGetRequest();

        //获取日期，遍历三个月内时间作比较，查询近三个月每一天的订单

        //当前日期
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        today = LocalDate.parse(today.format(formatter), formatter);

        LocalDate threeMonthsAgo = today.minusMonths(3);
        System.out.println("------------------三月前的日期"+threeMonthsAgo+"--------------");


        QueryWrapper<TShopOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.select("DISTINCT DATE(confirm_time) as confirm_date")
            .groupBy("DATE(confirm_time)");

        List<Object> shopOrderList = shopOrderMapper.selectObjs(orderQueryWrapper);

        // 遍历三个月里的每一天
        LocalDate currentDate = threeMonthsAgo;

        String formattedDate = "";

        while (!currentDate.isAfter(today)) {

            formattedDate = currentDate.format(DateTimeFormatter.ISO_DATE);

            // 检查 shopOrderList 中是否包含当前日期
            boolean dateExists = false;
            for (Object orderDate : shopOrderList) {
                if (orderDate != null && orderDate.toString().contains(formattedDate)) {
                    dateExists = true;
                    break;
                }
            }

            // 如果当前日期不在 shopOrderList 中，停止遍历
            if (!dateExists) {
                System.out.println("日期 " + formattedDate + " 不在订单列表中，停止遍历。");
                break;
            }

            // 继续遍历下一天
            currentDate = currentDate.plusDays(1);
        }

        //时间戳转换
        LocalDate date = LocalDate.parse(formattedDate, DateTimeFormatter.ISO_DATE);

        // 指定时区（例如 UTC 或 Asia/Shanghai）
        ZoneId zone = ZoneId.of("Asia/Shanghai"); // 或

        // 获取当天的开始时间 (00:00:00)
        LocalDateTime startOfDay = date.atStartOfDay();
        long startTimestamp = startOfDay.atZone(zone).toEpochSecond(); // 以秒为单位

        // 获取当天的结束时间 (23:59:59)
        LocalDateTime endOfDay = date.atTime(23, 59, 59);
        long endTimestamp = endOfDay.atZone(zone).toEpochSecond(); // 以秒为单位

        System.out.println("--------开始时间："+startTimestamp+"-------结束时间："+endTimestamp);

        request.setStartConfirmAt(startTimestamp);
        request.setEndConfirmAt(endTimestamp);
        request.setOrderStatus(5);
        if (ObjectUtils.isNotEmpty(orderVO.getPage())){
            request.setPage(orderVO.getPage());
        }
//        request.setPage(page);默认1
//        request.setPageSize(100);默认100
        request.setRefundStatus(5);
        request.setTradeType(0);
        request.setUseHasNext(true);
        PddOrderListGetResponse response = client.syncInvoke(request, orderVO.getAccessToken());
        System.out.println(JsonUtil.transferToJson(response));
        String res = JsonUtil.transferToJson(response);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //字符串转换成对象
        JsonObject obj = gson.fromJson(res, JsonObject.class);

        if (ObjectUtils.isNotEmpty(obj.getAsJsonObject("error_response"))){
            JsonObject error_response = obj.getAsJsonObject("error_response");
            log.error( "数据异常" +error_response.get("error_msg").toString());
            return;
        }

        // 获取根对象
        JsonObject object = obj.getAsJsonObject("order_list_get_response");

        // 获取 has_next 字段
        boolean hasNext = object.get("has_next").getAsBoolean();
        System.out.println("Has next: " + hasNext);

//        int total_count = object.get("total_count").getAsInt();
//        if (total_count == 0){
//            log.info("日期："+formattedDate+"此天无订单");
//            TShopOrder order = new TShopOrder();
//            order.setConfirmTime(formattedDate);
//            shopOrderMapper.insert(order);
//        }

        // 获取 order_list 数组
        JsonArray orderList = object.getAsJsonArray("order_list");

        if (ObjectUtils.isEmpty(orderList)){
            log.info("日期："+formattedDate+"此天无订单");
            if ( !today.toString().equals(formattedDate)){
                TShopOrder order = new TShopOrder();
                order.setConfirmTime(formattedDate);
                shopOrderMapper.insert(order);
            }
        }

        // 遍历订单列表
        for (JsonElement orderElement : orderList) {
            JsonObject order = orderElement.getAsJsonObject();


            // 提取订单字段
            //根据订单编号判断
            String orderSn = order.get("order_sn").getAsString();

            QueryWrapper<TShopOrder> queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_sn", orderSn);

            TShopOrder shopOrder =  shopOrderMapper.selectOne(queryWrapper);
            if (ObjectUtils.isEmpty(shopOrder)){
                shopOrder = new TShopOrder();
                shopOrder.setOrderSn(orderSn);
            }

            //todo地址-加密
            String address = order.get("address").getAsString();
//            shopOrder.setAddress(address);

            //地址
            String addressMask = order.get("address_mask").getAsString();
            shopOrder.setAddressMask(addressMask);

            //售后状态
            int afterSalesStatus = order.get("after_sales_status").getAsInt();
            shopOrder.setAfterSalesStatus(afterSalesStatus);

            //买家留言信息
            String buyerMemo = order.get("buyer_memo").getAsString();
            shopOrder.setBuyerMemo(buyerMemo);

            //成交状态
            int confirmStatus = order.get("confirm_status").getAsInt();
            shopOrder.setConfirmStatus(confirmStatus);

            //成交时间
            String confirmTime = order.get("confirm_time").getAsString();
            shopOrder.setConfirmTime(confirmTime);

            //订单创建时间
            String createdTime = order.get("created_time").getAsString();
            shopOrder.setCreatedTime(createdTime);

            //是否当日发货： 1-是，0-否
            int deliveryOneDay = order.get("delivery_one_day").getAsInt();
            if (deliveryOneDay == 1){
                shopOrder.setDeliveryOneDay("是");
            }
            if (deliveryOneDay == 0){
                shopOrder.setDeliveryOneDay("否");
            }

            //折扣金额
            double discountAmount = order.get("discount_amount").getAsDouble();
            shopOrder.setDiscountAmount(new BigDecimal(discountAmount));

            //多多支付立减金额
            if (ObjectUtils.isNotEmpty(order.get("duo_duo_pay_reduction"))){
                double duoDuoPayReduction = order.get("duo_duo_pay_reduction").getAsDouble();
                shopOrder.setDuoDuoPayReduction(new BigDecimal(duoDuoPayReduction));
            }


            //是否多多批发
            int duoduoWholesale = order.get("duoduo_wholesale").getAsInt();
            shopOrder.setDuoduoWholesale(duoduoWholesale);

            //商品金额
            double goodsAmount = order.get("goods_amount").getAsDouble();
            shopOrder.setGoodsAmount(new BigDecimal(goodsAmount));

            //仓库编码
            if (ObjectUtils.isNotEmpty(order.get("depot_code"))){
                String depotCode = order.get("depot_code").getAsString();
                shopOrder.setDepotCode(depotCode);
            }


            //仓库信息
            if (ObjectUtils.isNotEmpty(order.get("order_depot_info"))){
                Object orderDepotInfo = order.get("order_depot_info");
                shopOrder.setOrderDepotInfo(String.valueOf(orderDepotInfo));
            }

            //仓库id
            if (ObjectUtils.isNotEmpty(order.get("depot_id"))){
                long depotId = order.get("depot_id").getAsLong();
                shopOrder.setDepotId(String.valueOf(depotId));
            }

            //仓库名称
            if (ObjectUtils.isNotEmpty(order.get("depot_name"))){

                String depotName = order.get("depot_name").getAsString();
                shopOrder.setDepotName(depotName);
            }

            //仓库类型
            if (ObjectUtils.isNotEmpty(order.get("depot_type"))){
                int depotType = order.get("depot_type").getAsInt();
                shopOrder.setDepotType(depotType);
            }

            //货品id
            if (ObjectUtils.isNotEmpty(order.get("ware_id"))){
                long wareId = order.get("ware_id").getAsLong();
                shopOrder.setWareId(wareId);
            }


            //货品名称
            if (ObjectUtils.isNotEmpty(order.get("ware_name"))){
                String wareName = order.get("ware_name").getAsString();
                shopOrder.setWareName(wareName);
            }


            //货品编码
            if (ObjectUtils.isNotEmpty(order.get("ware_sn"))){
                String wareSn = order.get("ware_sn").getAsString();
                shopOrder.setWareSn(wareSn);
            }


            //货品类型
            if (ObjectUtils.isNotEmpty(order.get("ware_type"))){
                int wareType = order.get("ware_type").getAsInt();
                shopOrder.setWareType(wareType);
            }


            //订单状态
            int orderStatus = order.get("order_status").getAsInt();
            shopOrder.setOrderStatus(orderStatus);

            //支付金额
            double payAmount = order.get("pay_amount").getAsDouble();
            shopOrder.setPayAmount(new BigDecimal(payAmount));

            //支付单号
            if (ObjectUtils.isNotEmpty(order.get("pay_no"))){
                String payNo = order.get("pay_no").getAsString();
                shopOrder.setPayNo(payNo);
            }

            //支付时间
            String payTime = order.get("pay_time").getAsString();
            shopOrder.setPayTime(payTime);

            //支付方式
            String payType = order.get("pay_type").getAsString();
            shopOrder.setPayType(payType);

            //平台优惠金额
            double platformDiscount = order.get("platform_discount").getAsDouble();
            shopOrder.setPlatformDiscount(new BigDecimal(platformDiscount));

            //邮费
            double postage = order.get("postage").getAsDouble();
            shopOrder.setPostage(new BigDecimal(postage));

            //预售时间
            String preSaleTime = order.get("pre_sale_time").getAsString();
            shopOrder.setPreSaleTime(preSaleTime);

            //承诺送达时间
            if (ObjectUtils.isNotEmpty(order.get("promise_delivery_time"))){
                String promiseDeliveryTime = order.get("promise_delivery_time").getAsString();
                shopOrder.setPromiseDeliveryTime(promiseDeliveryTime);
            }

            //省份
            String province = order.get("province").getAsString();
            shopOrder.setProvince(province);

            //省份编码
            String provinceId = order.get("province_id").getAsString();
            shopOrder.setProvinceId(provinceId);

            //确认收货时间
            if (ObjectUtils.isNotEmpty(order.get("receive_time"))){
                String receiveTime = order.get("receive_time").getAsString();
                shopOrder.setReceiveTime(receiveTime);
            }

            //收件人地址
            String receiverAddress = order.get("receiver_address").getAsString();
            shopOrder.setReceiverAddress(receiverAddress);

            //收件人地址（打码）
            String receiverAddressMask = order.get("receiver_address_mask").getAsString();
            shopOrder.setReceiverAddressMask(receiverAddressMask);

            //收件人姓名
            String receiverName = order.get("receiver_name").getAsString();
            shopOrder.setReceiverName(receiverName);

            //收件人姓名
            String receiverNameMask = order.get("receiver_name_mask").getAsString();
            shopOrder.setReceiverNameMask(receiverNameMask);

            //收件人手机号
            String receiverPhone = order.get("receiver_phone").getAsString();
            shopOrder.setReceiverPhone(receiverPhone);

            //收件人手机号（打码）
            String receiverPhoneMask = order.get("receiver_phone_mask").getAsString();
            shopOrder.setReceiverPhoneMask(receiverPhoneMask);

            //售后状态
            int refundStatus = order.get("refund_status").getAsInt();
            shopOrder.setRefundStatus(refundStatus);

            //订单备注
            String remark = order.get("remark").getAsString();
            shopOrder.setRemark(remark);

            //订单备注标记
            if (ObjectUtils.isNotEmpty(order.get("remark_tag"))){
                String remarkTag = order.get("remark_tag").getAsString();
                String remarkTagColor;
                switch (remarkTag) {
                    case "1":
                        remarkTagColor = "红色";
                        break;
                    case "2":
                        remarkTagColor = "黄色";
                        break;
                    case "3":
                        remarkTagColor = "绿色";
                        break;
                    case "4":
                        remarkTagColor = "蓝色";
                        break;
                    case "5":
                        remarkTagColor = "紫色";
                        break;
                    default:
                        remarkTagColor = "未知颜色";
                        break;
                }
                shopOrder.setRemarkTag(remarkTagColor);
            }


            //订单备注标记名称
            if (ObjectUtils.isNotEmpty(order.get("remark_tag_name"))) {
                String remarkTagName = order.get("remark_tag_name").getAsString();
                shopOrder.setRemarkTagName(remarkTagName);
            }

            //退货包运费
            Integer returnFreightPayer = order.get("return_freight_payer").getAsInt();
            shopOrder.setReturnFreightPayer(returnFreightPayer);

            //订单审核状态
            Integer riskControlStatus = order.get("risk_control_status").getAsInt();
            shopOrder.setRiskControlStatus(riskControlStatus);

            //是否门店自提
            Integer selfContained = order.get("self_contained").getAsInt();
            shopOrder.setSelfContained(selfContained);

            //商家优惠金额
            BigDecimal sellerDiscount = new BigDecimal(order.get("seller_discount").getAsString());
            shopOrder.setSellerDiscount(sellerDiscount);

            //缺货处理状态
            Integer stockOutHandleStatus = order.get("stock_out_handle_status").getAsInt();
            shopOrder.setStockOutHandleStatus(stockOutHandleStatus);

            //全国联保
            Integer supportNationwideWarranty = order.get("support_nationwide_warranty").getAsInt();
            shopOrder.setSupportNationwideWarranty(supportNationwideWarranty);

            //区，乡镇
            String town = order.get("town").getAsString();
            shopOrder.setTown(town);

            //区县编码
            String townId = order.get("town_id").getAsString();
            shopOrder.setTownId(townId);

            //快递单号
            String trackingNumber = order.get("tracking_number").getAsString();
            shopOrder.setTrackingNumber(trackingNumber);

            //以旧换新国家补贴金额
            if (ObjectUtils.isNotEmpty(order.get("trade_in_national_subsidy_amount"))){
                double tradeInNationalSubsidyAmount = order.get("trade_in_national_subsidy_amount").getAsDouble();
                shopOrder.setTradeInNationalSubsidyAmount(new BigDecimal(tradeInNationalSubsidyAmount));
            }

            //订单类型
            int tradeType = order.get("trade_type").getAsInt();
            shopOrder.setTradeType(tradeType);

            //订单的更新时间
            if (ObjectUtils.isNotEmpty(order.get("updated_at"))) {
                String updatedAt = order.get("updated_at").getAsString();
                shopOrder.setUpdatedAt(updatedAt);
            }


            //催发货时间
            if (ObjectUtils.isNotEmpty(order.get("urge_shipping_time"))) {
                String urgeShippingTime = order.get("urge_shipping_time").getAsString();
                shopOrder.setUrgeShippingTime(urgeShippingTime);
            }


            //预约配送日期
            if (ObjectUtils.isNotEmpty(order.get("yyps_date"))) {
                String yypsDate = order.get("yyps_date").getAsString();
                shopOrder.setYypsDate(yypsDate);
            }


            //预约配送时段
            if (ObjectUtils.isNotEmpty(order.get("yyps_time"))) {
                String yypsTime = order.get("yyps_time").getAsString();
                shopOrder.setYypsTime(yypsTime);
            }


            //合单ID2
            if (ObjectUtils.isNotEmpty(order.get("open_address_id2"))){
                String openAddressId2 = order.get("open_address_id2").getAsString();
                shopOrder.setOpenAddressId2(openAddressId2);
            }

            //商品信息列表
            Object itemList = order.get("item_list");
            shopOrder.setItemList(String.valueOf(itemList));


            //店铺名称
            shopOrder.setShopName(orderVO.getShopName());
            //店铺id
            shopOrder.setShopId(String.valueOf(orderVO.getMallId()));

            //todo 租户编码写死
            shopOrder.setTenantId("000000");
//            String city = order.get("city").getAsString();
//            shopOrder.setCity(city);
//
//            int cityId = order.get("city_id").getAsInt();
//            shopOrder.setCityId(cityId);

            //	快递公司编号
//            int logisticsId = order.get("logistics_id").getAsInt();
//            shopOrder.setLogisticsId(logisticsId);

            //是否顺丰包邮，1-是 0-否
//            int freeSf = order.get("free_sf").getAsInt();
//            shopOrder.setFreeSf(freeSf);
            //是否缺货 0-无缺货处理 1： 有缺货处理
//            int isStockOut = order.get("is_stock_out").getAsInt();
//            shopOrder.setIsStockOut(isStockOut);


            if (ObjectUtils.isNotEmpty(shopOrder.getId())){
                shopOrderMapper.updateById(shopOrder);
            }else {
                shopOrderMapper.insert(shopOrder);
            }

            JsonArray orderItemList = order.getAsJsonArray("item_list");

            if (ObjectUtils.isNotEmpty(orderItemList)) {
                //遍历商品详情
                for (JsonElement orderItem : orderItemList) {
                    JsonObject item = orderItem.getAsJsonObject();

                    QueryWrapper<TShopOrderDetail> detailQueryWrapper = new QueryWrapper<>();
                    detailQueryWrapper.eq("order_id", shopOrder.getId());
                    TShopOrderDetail detail = shopOrderDetailMapper.selectOne(detailQueryWrapper);

                    if (ObjectUtils.isEmpty(detail)) {
                        detail = new TShopOrderDetail();
                        detail.setOrderId(shopOrder.getId());
                        detail.setOrderSn(shopOrder.getOrderSn());
                    }

                    int goodsCount = item.get("goods_count").getAsInt();
                    detail.setGoodsCount(goodsCount);

                    String goodsId = item.get("goods_id").getAsString();
                    detail.setGoodsId(goodsId);

                    String goodsImg = item.get("goods_img").getAsString();
                    detail.setGoodsImg(goodsImg);

                    String goodsName = item.get("goods_name").getAsString();
                    detail.setGoodsName(goodsName);

                    double goodsPrice = item.get("goods_price").getAsDouble();
                    detail.setGoodsPrice(new BigDecimal(goodsPrice));

                    String goodsSpec = item.get("goods_spec").getAsString();
                    detail.setGoodsSpec(goodsSpec);

                    String outerGoodsId = item.get("outer_goods_id").getAsString();
                    detail.setOuterGoodsId(outerGoodsId);

                    String outerId = item.get("outer_id").getAsString();
                    detail.setOuterId(outerId);

                    String skuId = item.get("sku_id").getAsString();
                    detail.setSkuId(skuId);

                    //店铺名称
                    detail.setShopName(orderVO.getShopName());
                    //店铺id
                    detail.setShopId(String.valueOf(orderVO.getMallId()));

                    detail.setTenantId("000000");

                    if (ObjectUtils.isEmpty(detail.getId())) {
                        shopOrderDetailMapper.insert(detail);
                    } else {
                        shopOrderDetailMapper.updateById(detail);
                    }
                }
            }

        }

        // 获取 has_next 字段
        boolean next  = object.get("has_next").getAsBoolean();

        if (next){
            orderVO.setPage(orderVO.getPage() + 1);
            getConfirmOrderList(orderVO);
        }
    }

    //订单增量接口(时间跨度为30分钟)
    @Override
    public void getNowOrderList(ShopOrderVO orderVO) throws Exception {


        String clientId = "203c5a7ba8bd4b8488d5e26f93052642";
        String clientSecret = "892ffaa86e12b7a3d8d2942b669d9aa520ad8179";
//        String accessToken = orderVO.getAccessToken();
        PopClient client = new PopHttpClient(clientId, clientSecret);

        //设置时间 end_updated_at - start_updated_at<= 30min
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 指定时区（例如 UTC 或 Asia/Shanghai）
        ZoneId zone = ZoneId.of("Asia/Shanghai");

        // 获取三十分钟之前的时间
        LocalDateTime tenMinutesAgo = now.minusMinutes(20);

        // 将当前时间转换为 UNIX 时间戳（秒）
        long nowTimestamp = now.atZone(zone).toEpochSecond();

        // 将三十分钟之前的时间转换为 UNIX 时间戳（秒）
        long tenMinutesAgoTimestamp = tenMinutesAgo.atZone(zone).toEpochSecond();

        System.out.println("开始时间----------"+nowTimestamp+":"+now);
        System.out.println("结束时间----------"+tenMinutesAgoTimestamp+":"+tenMinutesAgo);

        PddOrderNumberListIncrementGetRequest request = new PddOrderNumberListIncrementGetRequest();

        request.setStartUpdatedAt(tenMinutesAgoTimestamp);//开始时间
        request.setEndUpdatedAt(nowTimestamp);//结束时间

        request.setIsLuckyFlag(0);//订单类型（是否抽奖订单），0-全部，1-非抽奖订单，2-抽奖订单
        request.setOrderStatus(5);//发货状态，1-待发货，2-已发货待签收，3-已签收，5-全部
        request.setRefundStatus(5);//售后状态，1-无售后或售后关闭，2-售后处理中，3-退款中，4-退款成功 5-全部
        request.setUseHasNext(true);

//        request.setTradeType(1);//订单类型： 0-普通订单、1-定金订单 不传为全部
//        request.setPage(1);//默认1
//        request.setPageSize(1);//默认100

        System.out.println(JsonUtil.transferToJson(request));

        PddOrderNumberListIncrementGetResponse response = client.syncInvoke(request, orderVO.getAccessToken());
        System.out.println(JsonUtil.transferToJson(response));



        String res = JsonUtil.transferToJson(response);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //字符串转换成对象
        JsonObject obj = gson.fromJson(res, JsonObject.class);

        if (ObjectUtils.isNotEmpty(obj.getAsJsonObject("error_response"))){
            JsonObject error_response = obj.getAsJsonObject("error_response");
            log.error( "数据异常" +error_response.get("error_msg").toString());
            return;
        }

        // 获取根对象
        JsonObject object = obj.getAsJsonObject("order_sn_increment_get_response");

        // 获取 has_next 字段
        boolean hasNext = object.get("has_next").getAsBoolean();
        System.out.println("Has next: " + hasNext);


        // 获取 order_list 数组
        JsonArray orderList = object.getAsJsonArray("order_sn_list");

        // 遍历订单列表
        for (JsonElement orderElement : orderList) {
            JsonObject order = orderElement.getAsJsonObject();


            // 提取订单字段
            //根据订单编号判断
            String orderSn = order.get("order_sn").getAsString();

            QueryWrapper<TShopOrder> queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_sn", orderSn);

            TShopOrder shopOrder =  shopOrderMapper.selectOne(queryWrapper);
            if (ObjectUtils.isEmpty(shopOrder)){
                shopOrder = new TShopOrder();
                shopOrder.setOrderSn(orderSn);
            }

            //todo地址 加密
            String address = order.get("address").getAsString();
//            shopOrder.setAddress(address);

            //地址
            String addressMask = order.get("address_mask").getAsString();
            shopOrder.setAddressMask(addressMask);

            //售后状态
            int afterSalesStatus = order.get("after_sales_status").getAsInt();
            shopOrder.setAfterSalesStatus(afterSalesStatus);

            //买家留言信息
            String buyerMemo = order.get("buyer_memo").getAsString();
            shopOrder.setBuyerMemo(buyerMemo);

            //成交状态
            int confirmStatus = order.get("confirm_status").getAsInt();
            shopOrder.setConfirmStatus(confirmStatus);

            //成交时间
            String confirmTime = order.get("confirm_time").getAsString();
            shopOrder.setConfirmTime(confirmTime);

            //订单创建时间
            String createdTime = order.get("created_time").getAsString();
            shopOrder.setCreatedTime(createdTime);

            //是否当日发货： 1-是，0-否
            int deliveryOneDay = order.get("delivery_one_day").getAsInt();
            if (deliveryOneDay == 1){
                shopOrder.setDeliveryOneDay("是");
            }
            if (deliveryOneDay == 0){
                shopOrder.setDeliveryOneDay("否");
            }

            //折扣金额
            double discountAmount = order.get("discount_amount").getAsDouble();
            shopOrder.setDiscountAmount(new BigDecimal(discountAmount));

            //多多支付立减金额
            if (ObjectUtils.isNotEmpty(order.get("duo_duo_pay_reduction"))){
                double duoDuoPayReduction = order.get("duo_duo_pay_reduction").getAsDouble();
                shopOrder.setDuoDuoPayReduction(new BigDecimal(duoDuoPayReduction));
            }


            //是否多多批发
            int duoduoWholesale = order.get("duoduo_wholesale").getAsInt();
            shopOrder.setDuoduoWholesale(duoduoWholesale);

            //商品金额
            double goodsAmount = order.get("goods_amount").getAsDouble();
            shopOrder.setGoodsAmount(new BigDecimal(goodsAmount));

            //仓库编码
            if (ObjectUtils.isNotEmpty(order.get("depot_code"))){
                String depotCode = order.get("depot_code").getAsString();
                shopOrder.setDepotCode(depotCode);
            }


            //仓库信息
            if (ObjectUtils.isNotEmpty(order.get("order_depot_info"))){
                Object orderDepotInfo = order.get("order_depot_info");
                shopOrder.setOrderDepotInfo(String.valueOf(orderDepotInfo));
            }

            //仓库id
            if (ObjectUtils.isNotEmpty(order.get("depot_id"))){
                long depotId = order.get("depot_id").getAsLong();
                shopOrder.setDepotId(String.valueOf(depotId));
            }

            //仓库名称
            if (ObjectUtils.isNotEmpty(order.get("depot_name"))){

                String depotName = order.get("depot_name").getAsString();
                shopOrder.setDepotName(depotName);
            }

            //仓库类型
            if (ObjectUtils.isNotEmpty(order.get("depot_type"))){
                int depotType = order.get("depot_type").getAsInt();
                shopOrder.setDepotType(depotType);
            }

            //货品id
            if (ObjectUtils.isNotEmpty(order.get("ware_id"))){
                long wareId = order.get("ware_id").getAsLong();
                shopOrder.setWareId(wareId);
            }


            //货品名称
            if (ObjectUtils.isNotEmpty(order.get("ware_name"))){
                String wareName = order.get("ware_name").getAsString();
                shopOrder.setWareName(wareName);
            }


            //货品编码
            if (ObjectUtils.isNotEmpty(order.get("ware_sn"))){
                String wareSn = order.get("ware_sn").getAsString();
                shopOrder.setWareSn(wareSn);
            }


            //货品类型
            if (ObjectUtils.isNotEmpty(order.get("ware_type"))){
                int wareType = order.get("ware_type").getAsInt();
                shopOrder.setWareType(wareType);
            }


            //订单状态
            int orderStatus = order.get("order_status").getAsInt();
            shopOrder.setOrderStatus(orderStatus);

            //支付金额
            double payAmount = order.get("pay_amount").getAsDouble();
            shopOrder.setPayAmount(new BigDecimal(payAmount));

            //支付单号
            if (ObjectUtils.isNotEmpty(order.get("pay_no"))){
                String payNo = order.get("pay_no").getAsString();
                shopOrder.setPayNo(payNo);
            }

            //支付时间
            String payTime = order.get("pay_time").getAsString();
            shopOrder.setPayTime(payTime);

            //支付方式
            String payType = order.get("pay_type").getAsString();
            shopOrder.setPayType(payType);

            //平台优惠金额
            double platformDiscount = order.get("platform_discount").getAsDouble();
            shopOrder.setPlatformDiscount(new BigDecimal(platformDiscount));

            //邮费
            double postage = order.get("postage").getAsDouble();
            shopOrder.setPostage(new BigDecimal(postage));

            //预售时间
            String preSaleTime = order.get("pre_sale_time").getAsString();
            shopOrder.setPreSaleTime(preSaleTime);

            //承诺送达时间
            if (ObjectUtils.isNotEmpty(order.get("promise_delivery_time"))){
                String promiseDeliveryTime = order.get("promise_delivery_time").getAsString();
                shopOrder.setPromiseDeliveryTime(promiseDeliveryTime);
            }

            //省份
            String province = order.get("province").getAsString();
            shopOrder.setProvince(province);

            //省份编码
            String provinceId = order.get("province_id").getAsString();
            shopOrder.setProvinceId(provinceId);

            //确认收货时间
            if (ObjectUtils.isNotEmpty(order.get("receive_time"))){
                String receiveTime = order.get("receive_time").getAsString();
                shopOrder.setReceiveTime(receiveTime);
            }

            //收件人地址
            String receiverAddress = order.get("receiver_address").getAsString();
            shopOrder.setReceiverAddress(receiverAddress);

            //收件人地址（打码）
            String receiverAddressMask = order.get("receiver_address_mask").getAsString();
            shopOrder.setReceiverAddressMask(receiverAddressMask);

            //收件人姓名
            String receiverName = order.get("receiver_name").getAsString();
            shopOrder.setReceiverName(receiverName);

            //收件人姓名
            String receiverNameMask = order.get("receiver_name_mask").getAsString();
            shopOrder.setReceiverNameMask(receiverNameMask);

            //收件人手机号
            String receiverPhone = order.get("receiver_phone").getAsString();
            shopOrder.setReceiverPhone(receiverPhone);

            //收件人手机号（打码）
            String receiverPhoneMask = order.get("receiver_phone_mask").getAsString();
            shopOrder.setReceiverPhoneMask(receiverPhoneMask);

            //售后状态
            int refundStatus = order.get("refund_status").getAsInt();
            shopOrder.setRefundStatus(refundStatus);

            //订单备注
            String remark = order.get("remark").getAsString();
            shopOrder.setRemark(remark);

            //订单备注标记
            if (ObjectUtils.isNotEmpty(order.get("remark_tag"))){
                String remarkTag = order.get("remark_tag").getAsString();
                String remarkTagColor;
                switch (remarkTag) {
                    case "1":
                        remarkTagColor = "红色";
                        break;
                    case "2":
                        remarkTagColor = "黄色";
                        break;
                    case "3":
                        remarkTagColor = "绿色";
                        break;
                    case "4":
                        remarkTagColor = "蓝色";
                        break;
                    case "5":
                        remarkTagColor = "紫色";
                        break;
                    default:
                        remarkTagColor = "未知颜色";
                        break;
                }
                shopOrder.setRemarkTag(remarkTagColor);
            }


            //订单备注标记名称
            if (ObjectUtils.isNotEmpty(order.get("remark_tag_name"))) {
                String remarkTagName = order.get("remark_tag_name").getAsString();
                shopOrder.setRemarkTagName(remarkTagName);
            }

            //退货包运费
            Integer returnFreightPayer = order.get("return_freight_payer").getAsInt();
            shopOrder.setReturnFreightPayer(returnFreightPayer);

            //订单审核状态
            Integer riskControlStatus = order.get("risk_control_status").getAsInt();
            shopOrder.setRiskControlStatus(riskControlStatus);

            //是否门店自提
            Integer selfContained = order.get("self_contained").getAsInt();
            shopOrder.setSelfContained(selfContained);

            //商家优惠金额
            BigDecimal sellerDiscount = new BigDecimal(order.get("seller_discount").getAsString());
            shopOrder.setSellerDiscount(sellerDiscount);

            //缺货处理状态
            Integer stockOutHandleStatus = order.get("stock_out_handle_status").getAsInt();
            shopOrder.setStockOutHandleStatus(stockOutHandleStatus);

            //全国联保
            Integer supportNationwideWarranty = order.get("support_nationwide_warranty").getAsInt();
            shopOrder.setSupportNationwideWarranty(supportNationwideWarranty);

            //区，乡镇
            String town = order.get("town").getAsString();
            shopOrder.setTown(town);

            //区县编码
            String townId = order.get("town_id").getAsString();
            shopOrder.setTownId(townId);

            //快递单号
            String trackingNumber = order.get("tracking_number").getAsString();
            shopOrder.setTrackingNumber(trackingNumber);

            //以旧换新国家补贴金额
            if (ObjectUtils.isNotEmpty(order.get("trade_in_national_subsidy_amount"))){
                double tradeInNationalSubsidyAmount = order.get("trade_in_national_subsidy_amount").getAsDouble();
                shopOrder.setTradeInNationalSubsidyAmount(new BigDecimal(tradeInNationalSubsidyAmount));
            }

            //订单类型
            int tradeType = order.get("trade_type").getAsInt();
            shopOrder.setTradeType(tradeType);

            //订单的更新时间
            if (ObjectUtils.isNotEmpty(order.get("updated_at"))) {
                String updatedAt = order.get("updated_at").getAsString();
                shopOrder.setUpdatedAt(updatedAt);
            }


            //催发货时间
            if (ObjectUtils.isNotEmpty(order.get("urge_shipping_time"))) {
                String urgeShippingTime = order.get("urge_shipping_time").getAsString();
                shopOrder.setUrgeShippingTime(urgeShippingTime);
            }


            //预约配送日期
            if (ObjectUtils.isNotEmpty(order.get("yyps_date"))) {
                String yypsDate = order.get("yyps_date").getAsString();
                shopOrder.setYypsDate(yypsDate);
            }


            //预约配送时段
            if (ObjectUtils.isNotEmpty(order.get("yyps_time"))) {
                String yypsTime = order.get("yyps_time").getAsString();
                shopOrder.setYypsTime(yypsTime);
            }


            //合单ID2
            if (ObjectUtils.isNotEmpty(order.get("open_address_id2"))){
                String openAddressId2 = order.get("open_address_id2").getAsString();
                shopOrder.setOpenAddressId2(openAddressId2);
            }

            //商品信息列表
            Object itemList = order.get("item_list");
            shopOrder.setItemList(String.valueOf(itemList));


            //店铺名称
            shopOrder.setShopName(orderVO.getShopName());
            //店铺id
            shopOrder.setShopId(String.valueOf(orderVO.getMallId()));


            //todo 租户编码写死
            shopOrder.setTenantId("000000");

            if (ObjectUtils.isNotEmpty(shopOrder.getId())){
                shopOrderMapper.updateById(shopOrder);
            }else {
                shopOrderMapper.insert(shopOrder);
            }

            JsonArray orderItemList = order.getAsJsonArray("item_list");

            if (ObjectUtils.isNotEmpty(orderItemList)) {
                //遍历商品详情
                for (JsonElement orderItem : orderItemList) {
                    JsonObject item = orderItem.getAsJsonObject();

                    QueryWrapper<TShopOrderDetail> detailQueryWrapper = new QueryWrapper<>();
                    detailQueryWrapper.eq("order_id", shopOrder.getId());
                    TShopOrderDetail detail = shopOrderDetailMapper.selectOne(detailQueryWrapper);

                    if (ObjectUtils.isEmpty(detail)) {
                        detail = new TShopOrderDetail();
                        detail.setOrderId(shopOrder.getId());
                        detail.setOrderSn(shopOrder.getOrderSn());
                    }

                    int goodsCount = item.get("goods_count").getAsInt();
                    detail.setGoodsCount(goodsCount);

                    String goodsId = item.get("goods_id").getAsString();
                    detail.setGoodsId(goodsId);

                    String goodsImg = item.get("goods_img").getAsString();
                    detail.setGoodsImg(goodsImg);

                    String goodsName = item.get("goods_name").getAsString();
                    detail.setGoodsName(goodsName);

                    double goodsPrice = item.get("goods_price").getAsDouble();
                    detail.setGoodsPrice(new BigDecimal(goodsPrice));

                    String goodsSpec = item.get("goods_spec").getAsString();
                    detail.setGoodsSpec(goodsSpec);

                    String outerGoodsId = item.get("outer_goods_id").getAsString();
                    detail.setOuterGoodsId(outerGoodsId);

                    String outerId = item.get("outer_id").getAsString();
                    detail.setOuterId(outerId);

                    String skuId = item.get("sku_id").getAsString();
                    detail.setSkuId(skuId);

                    //店铺名称
                    detail.setShopName(orderVO.getShopName());
                    //店铺id
                    detail.setShopId(String.valueOf(orderVO.getMallId()));


                    //todo 租户编码写死
                    detail.setTenantId("000000");

                    if (ObjectUtils.isEmpty(detail.getId())) {
                        shopOrderDetailMapper.insert(detail);
                    } else {
                        shopOrderDetailMapper.updateById(detail);
                    }
                }
            }

        }

        // 获取 has_next 字段
        boolean next  = object.get("has_next").getAsBoolean();

        if (next){
            orderVO.setPage(orderVO.getPage() + 1);
            getConfirmOrderList(orderVO);
        }









    }


}
