package com.jwipc.job.handler;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwipc.job.dto.*;
import com.jwipc.shopping.entity.ShoppingCart;
import com.jwipc.shopping.entity.ShoppingCartInfo;
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.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: swq
 * @Date: 2024/4/26 14:35
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class ShoppingOrderStatusJob 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("订单/物流单收货单状态定时同步任务开始");
        //获取ZKH商城token
        String token = onlineMallService.findTokenByCart("ZKH");
        //调用推送消息接口拉取数据
        Integer type = 5;//代表妥投/拒收消息（订单/发货单
        GetMessageDto gmDto = new GetMessageDto();
        gmDto.setType(type);
        gmDto.setToken(token);
        String plDtoJson = JSON.toJSONString(gmDto);
        log.info("订单/物流单收货单状态定时同步的接口调用参数: {}", plDtoJson);
        //调用发货单明细接口
        try {
            String result = middleWareService.requestMiddleGetMessage(plDtoJson);
            log.info("订单/物流单收货单状态定时同步的接口调用返回结果: {}", result);
            if (StringUtils.isNotEmpty(result)) {
                final GetMessageResponse orderResponse = JSON.parseObject(result, GetMessageResponse.class);
                if (orderResponse.getSuccess()) {
                    List<GetResultDto> grDtoList = orderResponse.getResult();
                    if (CollectionUtils.isNotEmpty(grDtoList)) {
                        List<ShoppingCart> shoppingCartList = new ArrayList<>();
                        List<ShoppingCartInfo> shoppingCartInfoList = new ArrayList<>();
                        grDtoList.forEach(t -> {
                            ResultTypeDto resultTypeDto = t.getResult();
                            Integer orderType = resultTypeDto.getOrderType() == null ? 1 : resultTypeDto.getOrderType();//1：订单 2：发货单； 默认是订单
                            String orderId = resultTypeDto.getOrderId(); //orderType=1 返回订单号orderType=2 返回发货单号
                            Integer state = resultTypeDto.getState();//1-妥投，2-拒收，3-部分妥投(该状态有orderType=1才有，请查看下面说明)订单包含三种状态：妥投、拒收、部分妥投；发货单包含两种状态：妥投、拒收
                            if (orderType.equals(2)) {//发货单
                                List<ShoppingCartInfo> cartInfoList = shoppingCartInfoService.list(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getPackageId, orderId));
                                if (CollectionUtils.isNotEmpty(cartInfoList)) {
                                    cartInfoList.forEach(carInfo -> {
                                        if (state == 1) {
                                            carInfo.setDeliveryStatus(2);//签收
                                        } else {
                                            carInfo.setDeliveryStatus(3);//拒收
                                        }
                                        carInfo.setPurchaseDate(LocalDateTime.now());//设置购买时间
                                        shoppingCartInfoList.add(carInfo);

                                    });
                                }

                            } else {//订单
                                ShoppingCart shoppingCart = shoppingCartService.getOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getOrderId, orderId));
                                if (!Objects.isNull(shoppingCart)) {
                                    if (state == 1) {
                                        shoppingCart.setReceiptStatus(1);//签收
                                    } else if (state == 2) {
                                        shoppingCart.setReceiptStatus(0);//拒收=未收货
                                    } else {
                                        shoppingCart.setReceiptStatus(2);//部分收货
                                    }
                                    shoppingCartList.add(shoppingCart);
                                }
                            }

                            //调用删除接口
                            String id = t.getId();
                            DelMessageDto delMessageDto = new DelMessageDto();
                            delMessageDto.setId(id);
                            delMessageDto.setToken(token);
                            String delJson = JSON.toJSONString(delMessageDto);
                            log.info("商城删除消息接口调用参数: {}", delJson);
                            try {
                                String delResult = middleWareService.requestMiddleDelMessage(delJson);
                                log.info("商城删除消息接口调用返回结果: {}", delResult);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        });
                        if (CollectionUtils.isNotEmpty(shoppingCartList)) {
                            shoppingCartService.updateBatchById(shoppingCartList);//更新订单信息
                        }
                        if (CollectionUtils.isNotEmpty(shoppingCartInfoList)) {
                            shoppingCartInfoService.updateBatchById(shoppingCartInfoList);//更新订单明细信息
                        }
                    }
                }
            }

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


    }
}
