package com.jwipc.job.handler;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwipc.job.dto.DeliveryEntityDto;
import com.jwipc.job.dto.DeliveryEntityItemDto;
import com.jwipc.job.dto.PackageListDto;
import com.jwipc.job.dto.PackageListResponse;
import com.jwipc.shopping.entity.ShoppingCart;
import com.jwipc.shopping.entity.ShoppingCartInfo;
import com.jwipc.shopping.model.vo.CartPurchaseDTO;
import com.jwipc.shopping.service.IMiddleWareService;
import com.jwipc.shopping.service.IOnlineMallService;
import com.jwipc.shopping.service.IShoppingCartInfoService;
import com.jwipc.shopping.service.IShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: swq
 * @Date: 2024/4/16 11:19
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class ShippingQueryJob extends QuartzJobBean implements InterruptableJob {
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IShoppingCartInfoService shoppingCartInfoService;
    @Autowired
    IMiddleWareService middleWareService;
    @Autowired
    IOnlineMallService onlineMallService;

    @Override
    public void interrupt() throws UnableToInterruptJobException {

    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("查询所有发货单明细信息任务开始");
        List<ShoppingCartInfo> cartInfoList = new ArrayList<>();
        //查询所有除已收货的订单信息(收货状态不等于1)
        List<ShoppingCart> carList = shoppingCartService.list(new LambdaQueryWrapper<ShoppingCart>().ne(ShoppingCart::getReceiptStatus, 1).isNotNull(ShoppingCart::getOrderId));
        if (CollectionUtils.isNotEmpty(carList)) {
            carList.forEach(item -> {
                //商城订单号
//                String orderId = "2024112118211300001A";
                String orderId = item.getOrderId();
                    ShoppingCart shoppingCart = shoppingCartService.getOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getOrderId, orderId));
                    //获取ZKH商城token
                    String token = onlineMallService.findTokenByCart("ZKH");
                    PackageListDto plDto = new PackageListDto();
//                    plDto.setOrderId(orderId);
                    plDto.setOrderId(orderId);
                    plDto.setToken(token);
                    String plDtoJson = JSON.toJSONString(plDto);
                    log.info("根据震坤行订单号，查询所有发货单明细信息的接口调用参数: {}", plDtoJson);

                    //调用发货单明细接口
                    try {
                        String result = middleWareService.requestMiddlePackageList(plDtoJson);
                        log.info("根据震坤行订单号，查询所有发货单明细信息的接口调用返回结果: {}", result);

                        if (StringUtils.isNotEmpty(result)) {
                            final PackageListResponse orderResponse = JSON.parseObject(result, PackageListResponse.class);
                            if (orderResponse.getSuccess()) {
                                List<DeliveryEntityDto> deliveryList = orderResponse.getResult();
                                if (CollectionUtils.isNotEmpty(deliveryList)) {
                                    deliveryList.forEach(t -> {
                                        List<DeliveryEntityItemDto> deliveryItems = t.getDeliveryItems();
//                                        Boolean f = false;
//                                        boolean shouldBreak = false;
//                                        BooleanWrapper f = new BooleanWrapper();
                                        Boolean f = false;
//                                        BooleanWrapper shouldBreak = new BooleanWrapper();
                                        if (CollectionUtils.isNotEmpty(deliveryItems)) {
                                            deliveryItems.forEach(ditem -> {
                                                ShoppingCartInfo shoppingCartInfo = shoppingCartInfoService.getOne(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, shoppingCart.getId()).eq(ShoppingCartInfo::getSkuCode, ditem.getSkuId()));
                                                shoppingCartInfo.setPackageId(t.getPackageId());
                                                shoppingCartInfo.setDeliveryTime(t.getDeliveryTime());
                                                shoppingCartInfo.setDeliveryStatus(t.getDeliveryStatus());
                                                shoppingCartInfo.setPurchaseDate(LocalDateTime.now());
                                                // 0未发货 1 已发货 2 部分发货
//                                                if (shoppingCartInfo.getDeliveryStatus() == 0) {
//                                                    f.setValue(true);
//                                                    shouldBreak.setValue(true);

//                                                }
                                                cartInfoList.add(shoppingCartInfo);
//                                                if (shouldBreak.getValue()) {
//                                                    throw new BreakLoopException();
//                                                }
                                            });
//                                            for (DeliveryEntityItemDto deliveryItem : deliveryItems) {
//                                                ShoppingCartInfo shoppingCartInfo = shoppingCartInfoService.getOne(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, shoppingCart.getId()).eq(ShoppingCartInfo::getSkuCode, deliveryItem.getSkuId()));
////                                                shoppingCartInfo.setDeliveryStatus(t.getDeliveryStatus());
//                                                // 0未发货 1 已发货 2 部分发货
//                                                if (shoppingCartInfo.getDeliveryStatus() == 0) {
//                                                    f = true;
//                                                    break;
//                                                }
//
//                                            }
                                        }
                                        //部分发货
//                                        if (f) {
//                                            shoppingCart.setReceiptStatus(2);
//                                        } else {
//                                            shoppingCart.setReceiptStatus(1);
//                                        }
//                                        shoppingCartService.updateById(shoppingCart);
                                    });
                                }
                            }
                        }
                        if (CollectionUtils.isNotEmpty(cartInfoList)) {
                            //批量更新
                            shoppingCartInfoService.updateBatchById(cartInfoList);
                        }
                        log.info("查询所有发货单明细信息任务结束:{}", JSON.toJSONString(cartInfoList));
                        Boolean f = false;




                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            });

            //20241209更新
            List<ShoppingCart> shoppingCarts = shoppingCartService.list();
            for (ShoppingCart shoppingCart1 : shoppingCarts) {
//                            ShoppingCartInfo shoppingCartInfo = shoppingCartInfoService.getOne(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, shoppingCart1.getId()).eq(ShoppingCartInfo::getSkuCode, deliveryItem.getSkuId()));
                boolean allZeros = true;
                boolean hasNonZero = false;
                List<CartPurchaseDTO> shoppingCartInfos = shoppingCartInfoService.getByCartId(shoppingCart1.getId());
                for (CartPurchaseDTO cartPurchaseDTO : shoppingCartInfos) {

                    if (cartPurchaseDTO.getDeliveryStatus() == 0) {
                        hasNonZero = true;
                    } else {
                        allZeros = false;
                    }
                    // 0未发货 1 已发货 2 部分发货
//                                if (cartPurchaseDTO.getDeliveryStatus() == 0) {
//                                    f = true;
//                                    break;
//                                }
                }
                //未发货
                if (allZeros) {
                    shoppingCart1.setDeliveryStatus(0);
                }
                //部分发货
                else if (hasNonZero) {
                    shoppingCart1.setDeliveryStatus(2);
                }
                //已发货
                else {
                    shoppingCart1.setDeliveryStatus(1);
                }
                shoppingCartService.updateById(shoppingCart1);
            }

        }


    }
    class BooleanWrapper {
        private boolean value;

        public boolean getValue() {
            return value;
        }

        public void setValue(boolean value) {
            this.value = value;
        }
    }
    class BreakLoopException extends RuntimeException {
    }
}
