package com.fs.express.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fs.common.utils.PhoneUtils;
import com.fs.express.FsStoreDeliversService;
import com.fs.express.IExpressService;
import com.fs.express.dto.DeliveryDTO;
import com.fs.store.domain.FsStoreDelivers;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.dto.ExpressInfoDTO;
import com.fs.store.enums.ShipperCodeEnum;
import com.fs.store.mapper.FsStoreDeliversMapper;
import com.fs.store.service.IFsExpressService;
import com.fs.store.service.IFsStoreOrderService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 物流信息查询类
 * @author xdd
 */
@Service
public class FsStoreDeliversServiceImpl implements FsStoreDeliversService {
    private static final Logger logger = LoggerFactory.getLogger(FsStoreDeliversServiceImpl.class);

    @Autowired
    private FsStoreDeliversMapper fsStoreDeliversMapper;

    @Autowired
    private IFsStoreOrderService orderService;

    @Autowired
    private IFsExpressService expressService;

    @Override
    public FsStoreDelivers findById(Integer id) {
        return fsStoreDeliversMapper.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FsStoreDelivers save(FsStoreDelivers fsStoreDelivers) {
        if (fsStoreDelivers.getId() == null) {
            fsStoreDelivers.setCreateTime(LocalDateTime.now());
            fsStoreDeliversMapper.insert(fsStoreDelivers);

        }
        return fsStoreDelivers;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(FsStoreDelivers fsStoreDelivers)
    {
        fsStoreDelivers.setUpdateTime(LocalDateTime.now());
       return fsStoreDeliversMapper.update(fsStoreDelivers) > 0;

    }

    @Override
    public List<FsStoreDelivers> findByOrderId(Long orderId) {
        return fsStoreDeliversMapper.findByOrderId(orderId);
    }

    @Override
    public void finishOrder(Long orderId) {
        List<FsStoreDelivers> byOrderId = fsStoreDeliversMapper.findByOrderId(orderId);
        Set<Integer> orderStatusSet = byOrderId.stream().map(FsStoreDelivers::getStatus)
                .collect(Collectors.toSet());


        Set<Integer> orderStateExSet = byOrderId.stream().map(FsStoreDelivers::getStateEx)
                .collect(Collectors.toSet());

        // 如果订单都是已经签收
        Set<Integer> finishStatusExSet = new HashSet<>();
        finishStatusExSet.add(301);
        finishStatusExSet.add(302);
        finishStatusExSet.add(304);
        finishStatusExSet.add(311);

        // orderStatusSet 必须都为3
        if (orderStatusSet.size() == 1 && orderStatusSet.contains(3) && finishStatusExSet.containsAll(orderStateExSet)) {
            // 订单完成
            orderService.finishOrder(orderId);
        }
    }

    @Override
    public void syncDeliverInfo(Long orderId) {
        logger.info("开始同步订单发货信息, 订单ID: {}", orderId);
        FsStoreOrder order = orderService.selectFsStoreOrderById(orderId);

        if (order == null) {
            logger.warn("订单不存在，订单ID: {}", orderId);
            return;
        }
        logger.info("查询到订单信息, 订单号: {}", order.getOrderCode());
        List<FsStoreDelivers> byOrderId = fsStoreDeliversMapper.findByOrderId(orderId);
        if (byOrderId.isEmpty()) {
            logger.info("订单没有发货信息, 订单ID: {}", orderId);
            return;
        }
        for (FsStoreDelivers fsStoreDelivers : byOrderId) {
            if (ObjectUtil.isNotEmpty(fsStoreDelivers.getDeliverId())) {
                logger.info("开始处理发货单, 发货单ID: {}, 快递单号: {}", fsStoreDelivers.getDeliverId(), fsStoreDelivers.getDeliverSn());
                String lastFourNumber = "";
                if (StringUtils.equals(fsStoreDelivers.getDeliverSn(), ShipperCodeEnum.SF.getValue())) {
                    lastFourNumber = PhoneUtils.getLastFourNum(order.getUserPhone());
                    logger.info("顺丰快递，获取手机号后四位: {}", lastFourNumber);
                }
                ExpressInfoDTO dto = null;
                try {
                    // 记录HTTP请求前的信息
                    logger.info("开始调用快递查询接口, 订单号: {}, 快递公司编码: {}, 快递单号: {}, 手机号后四位: {}",
                            order.getOrderCode(), fsStoreDelivers.getDeliverId(), fsStoreDelivers.getDeliverSn(), lastFourNumber);
                    dto = expressService.getExpressInfo(order.getOrderCode(),
                            fsStoreDelivers.getDeliverSn(), fsStoreDelivers.getDeliverId(), lastFourNumber);
                    // 假设expressService.getExpressInfo内部进行了HTTP请求，你需要在expressService内部打印更详细的日志
                    // 这里只记录返回结果
                    if (ObjectUtil.isNotNull(dto)) {
                        logger.info("快递查询接口调用成功, 订单号: {}, 快递状态: {}, 扩展状态: {}",
                                order.getOrderCode(), dto.getState(), dto.getStateEx());
                        fsStoreDelivers.setStatus(Integer.valueOf(dto.getState()));
                        fsStoreDelivers.setStateEx(Integer.valueOf(dto.getStateEx()));
                    } else {
                        logger.warn("快递查询接口调用成功，但返回结果为空, 订单号: {}", order.getOrderCode());
                    }
                } catch (Exception e) {
                    logger.error("快递查询接口调用失败, 订单号: {}, 快递单号: {}, 错误信息: {}", order.getOrderCode(), fsStoreDelivers.getDeliverSn(), e.getMessage(), e);
                }
            } else {
                logger.info("发货单信息中快递ID为空, 跳过处理, 发货单ID: {}", fsStoreDelivers.getId());
            }
        }

        fsStoreDeliversMapper.updateBatch(byOrderId);
        logger.info("同步订单发货信息完成, 订单ID: {}", orderId);
    }

    @Override
    public FsStoreDelivers findByOrderCodeAndDeliverId(String deliverId) {
        return fsStoreDeliversMapper.findByDeliverId(deliverId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void editDeliveryId(FsStoreDelivers deliveryDTO) {
        if(ObjectUtil.isNull(deliveryDTO.getId())){
            deliveryDTO.setStatus(0);
            deliveryDTO.setStateEx(0);
            FsStoreOrder fsStoreOrder = orderService.selectFsStoreOrderById(deliveryDTO.getOrderId());
            if(ObjectUtil.isNotNull(fsStoreOrder)){
                deliveryDTO.setOrderCode(fsStoreOrder.getOrderCode());
            }

            fsStoreDeliversMapper.insert(deliveryDTO);

            //新增的要订阅快递鸟监控
            String lastFourNum = PhoneUtils.getLastFourNum(fsStoreOrder.getUserPhone());
            expressService.subscribeEspress(deliveryDTO.getOrderCode(),
                    deliveryDTO.getDeliverSn(),
                    deliveryDTO.getDeliverId(),lastFourNum);
        } else {
            fsStoreDeliversMapper.update(deliveryDTO);
        }
    }

    @Override
    public FsStoreDelivers findByOrderCode(String orderCode) {
        return fsStoreDeliversMapper.findByOrderCode(orderCode);
    }
}
