package com.heyu.api.data.service.impl.vv;
/**
 * <p>
 * 包裹表 服务类
 * </p>
 *
 * @author quyixiao
 * @since 2025-08-23
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.dao.vv.VvPackageDao;
import com.heyu.api.data.dao.vv.VvReverseOrderDao;
import com.heyu.api.data.dao.vv.VvReverseOrderLineDao;
import com.heyu.api.data.dao.vv.VvTradeOrderLineDao;
import com.heyu.api.data.dto.PackageDelivedDelayDTO;
import com.heyu.api.data.dto.vv.KuaiDi100DTO;
import com.heyu.api.data.entity.vv.VvPackageEntity;
import com.heyu.api.data.entity.vv.VvReverseOrderEntity;
import com.heyu.api.data.entity.vv.VvReverseOrderLineEntity;
import com.heyu.api.data.entity.vv.VvTradeOrderLineEntity;
import com.heyu.api.data.enums.*;
import com.heyu.api.data.kuaidi100.KuaiDi100Utils;
import com.heyu.api.data.kuaidi100.LogisticsMapUtils;
import com.heyu.api.data.service.vv.VvPackageService;
import com.heyu.api.data.service.vv.VvTradeOrderConvertService;
import com.heyu.api.data.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class VvPackageServiceImpl extends ServiceImpl<VvPackageDao, VvPackageEntity> implements VvPackageService {


    @Autowired
    private VvPackageDao vvPackageDao;


    @Value("${eb.config.rabbitQueue.delayQueue}")
    private String delayQueue;


    @Value("${eb.config.rabbitQueue.delayExchangeName}")
    private String delayExchangeName;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private VvTradeOrderLineDao tradeOrderLineDao;

    @Autowired
    private VvReverseOrderDao vvReverseOrderDao;

    @Autowired
    private VvReverseOrderLineDao vvReverseOrderLineDao;

    @Autowired
    private VvTradeOrderConvertService vvTradeOrderConvertService;


    @Override
    public VvPackageEntity selectVvPackageById(Long id) {
        return vvPackageDao.selectVvPackageById(id);
    }


    @Override
    public Long insertVvPackage(VvPackageEntity vvPackage) {
        return vvPackageDao.insertVvPackage(vvPackage);
    }


    @Override
    public Long insertOrUpdateVvPackage(VvPackageEntity vvPackage) {
        return vvPackageDao.insertOrUpdateVvPackage(vvPackage);
    }


    @Override
    public int updateVvPackageById(VvPackageEntity vvPackage) {
        return vvPackageDao.updateVvPackageById(vvPackage);
    }


    @Override
    public int updateCoverVvPackageById(VvPackageEntity vvPackage) {
        return vvPackageDao.updateCoverVvPackageById(vvPackage);
    }


    @Override
    public int deleteVvPackageById(Long id) {
        return vvPackageDao.deleteVvPackageById(id);
    }


    @Override
    public KuaiDi100DTO selectVvKuaidiAndUpdateData(String trackNumber, String role, boolean checkExpireTime) {
        if (StringUtils.isBlank(trackNumber)) {
            return new KuaiDi100DTO();
        }

        VvPackageEntity vvPackageEntity = vvPackageDao.selectVvPackageByTrackNumber(trackNumber);
        Long kuaidiQueryExpireTimeDB = NumberUtil.objToLongDefault(vvPackageEntity.getKuaidiQueryExpireTime(), 0L);
        Date kuaidiQueryExpireTime = DateUtils.addMinutes(new Date(), 40);

        if (checkExpireTime && System.currentTimeMillis() < kuaidiQueryExpireTimeDB) {
            return JSONObject.parseObject(vvPackageEntity.getPackageLogisticsInfo(), KuaiDi100DTO.class);
        }
        log.info("selectVvKuaidiAndUpdateData select packageLogisticsInfo trackNumber:{},role:{}", trackNumber, role);
        KuaiDi100DTO kuaiDi100DTO = null;
        // 如果是已经签收状态
        if (KuaiDi100StateEnums.sign_receipt.getState().equals(vvPackageEntity.getState())) {
            kuaiDi100DTO = JSONObject.parseObject(vvPackageEntity.getPackageLogisticsInfo(), KuaiDi100DTO.class);
        } else {                    //如果当次查到的是已经签收状态
            kuaiDi100DTO = KuaiDi100Utils.getLogisticsInfo(trackNumber);
            vvPackageEntity.setIscheck(kuaiDi100DTO.getIscheck());
            vvPackageEntity.setCom(kuaiDi100DTO.getCom());
            vvPackageEntity.setStatus(kuaiDi100DTO.getStatus());
            vvPackageEntity.setState(kuaiDi100DTO.getState());
            vvPackageEntity.setPackageLogisticsInfo(JSON.toJSONString(kuaiDi100DTO));
            vvPackageEntity.setKuaidiQueryExpireTime(kuaidiQueryExpireTime.getTime());

            if (StringUtils.isBlank(vvPackageEntity.getLogisticsCompany())
                    && StringUtils.isNotEmpty(kuaiDi100DTO.getCom())) {
                vvPackageEntity.setLogisticsCompany(LogisticsMapUtils.getLogisticsCompanyName(kuaiDi100DTO.getCom()));
            }
            if (kuaiDi100DTO.getRouteInfo() != null
                    && kuaiDi100DTO.getRouteInfo().getFrom() != null) {
                vvPackageEntity.setShippingFrom(kuaiDi100DTO.getRouteInfo().getFrom().getName());
            }
            // 如果查询出来包裹状态已经签收
            if (KuaiDi100StateEnums.sign_receipt.getState().equals(kuaiDi100DTO.getState())) {
                List<KuaiDi100DTO.DataDTO> dataDTOS = kuaiDi100DTO.getData();
                if (dataDTOS != null && dataDTOS.size() > 0) {
                    for (KuaiDi100DTO.DataDTO dataDTO : dataDTOS) {
                        String status = dataDTO.getStatus();
                        if (KuaiDi100StateEnums.sign_receipt.getDesc().equals(status)) {
                            String fTime = dataDTO.getFtime();
                            Date time = DateUtils.parseDate(fTime);
                            Date timeAfter15 = DateUtils.addDays(time, 15);
                            // 设置签收时间
                            vvPackageEntity.setGmtSignReceipt(time);
                            vvPackageEntity.setSignReceiptStatus(ApiConstants.SIGN_RECEIPT);

                            // 如果是正向订单
                            if (ShippingTypeEnums.order.getType().equals(vvPackageEntity.getShippingType())) {
                                PackageDelivedDelayDTO dto = new PackageDelivedDelayDTO();
                                dto.setPackageId(vvPackageEntity.getId());
                                dto.setRole(role);
                                dto.setSendTime(DateUtils.formatDate(new Date(), com.heyu.api.data.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));
                                dto.setDelayTime(DateUtils.formatDate(timeAfter15, com.heyu.api.data.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));
                                dto.setType(DelayTypeEnums.delivered.getType());
                                int second = DateUtils.betweenSecond(time, timeAfter15);
                                log.info("VvPackageServiceImpl delay send :{}", JSON.toJSONString(dto));
                                // 通过广播模式发布延时消息 延时30分钟 持久化消息 消费后销毁 这里无需指定路由，会广播至每个绑定此交换机的队列
                                rabbitTemplate.convertAndSend(delayExchangeName, "", JSON.toJSONString(dto), message -> {
                                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                                    message.getMessageProperties().setDelay((second) * 1000);   // 毫秒为单位，指定此消息的延时时长 ,+ 1 尽量保证机器人跑完了，再发送消息
                                    return message;
                                });
                                // 设置已经发送消息了
                                vvPackageEntity.setIscheck("2");
                                vvPackageEntity.setGmtSendMqDelivered(new Date());

                                List<VvTradeOrderLineEntity> tradeOrderLineEntities = tradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(trackNumber);
                                for (VvTradeOrderLineEntity tradeOrderLineEntity : tradeOrderLineEntities) {
                                    tradeOrderLineEntity.setShippedUser(RoleEnums.system.getRole());
                                    tradeOrderLineEntity.setGmtShipped(new Date());
                                    tradeOrderLineEntity.setStatus(OrderStatusEnums.shipped.getStatus());
                                    tradeOrderLineEntity.setState(kuaiDi100DTO.getState());
                                    tradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
                                    Long roleId = -1L;
                                    if (RoleEnums.user.getRole().equals(role)) {
                                        roleId = tradeOrderLineEntity.getBuyerId();
                                    }
                                    vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                                            OrderStatusEnums.shipped,
                                            roleId,
                                            role,
                                            OrderStatusEnums.shipped.getDesc()
                                    );
                                }

                            } else {
                                VvReverseOrderEntity vvReverseOrderEntity = vvReverseOrderDao.selectVvReverseOrderByTrackNumber(trackNumber);
                                vvReverseOrderEntity.setStatus(ReverseStatusEnums.shipped.getStatus());
                                vvReverseOrderEntity.setGmtShipped(new Date());
                                vvReverseOrderEntity.setShippedUser(RoleEnums.system.getRole());
                                List<VvReverseOrderLineEntity> vvReverseOrderLineEntities = vvReverseOrderLineDao.selectVvReverseOrderLineByReverseOrderId(vvReverseOrderEntity.getId());
                                List<Long> tradeOrderLineIdList = SanUtils.getFieldList(vvReverseOrderLineEntities, VvReverseOrderLineEntity::getTradeOrderLineId);

                                if (CollectionUtils.isNotEmpty(tradeOrderLineIdList)) {
                                    List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = tradeOrderLineDao.selectVvTradeOrderLineByIds(tradeOrderLineIdList);
                                    for (VvTradeOrderLineEntity tradeOrderLineEntity : vvTradeOrderLineEntityList) {
                                        tradeOrderLineEntity.setReverseStatus(ReverseStatusEnums.shipped.getStatus());
                                        tradeOrderLineDao.updateVvTradeOrderLineById(tradeOrderLineEntity);
                                        Long roleId = -1L;
                                        if (RoleEnums.user.getRole().equals(role)) {
                                            roleId = tradeOrderLineEntity.getBuyerId();
                                        }
                                        vvTradeOrderConvertService.addOrderLineStatusLog(tradeOrderLineEntity.getId(),
                                                ReverseStatusEnums.shipped,
                                                roleId,
                                                role,
                                                ReverseStatusEnums.shipped.getDesc()
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
            vvPackageDao.updateVvPackageById(vvPackageEntity);
        }
        return kuaiDi100DTO;
    }


}
