package com.yonge.cooleshow.portal.service.impl;

import com.alibaba.fastjson.JSON;
import com.yonge.cooleshow.mall.common.courier.domain.CourierInfo;
import com.yonge.cooleshow.mall.common.courier.enums.CompanyEnum;
import com.yonge.cooleshow.mall.common.courier.service.CourierService;
import com.yonge.cooleshow.mall.common.enums.OrderCacheEnum;
import com.yonge.cooleshow.mbg.mapper.OmsOrderCourierMapper;
import com.yonge.cooleshow.mbg.model.OmsOrderCourier;
import com.yonge.cooleshow.portal.service.OmsOrderCourierService;
import com.yonge.toolset.base.exception.BizException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Description
 *
 * @author liujunchi
 * @date 2022-10-31
 */
@Service
public class OmsOrderCourierServiceImpl implements OmsOrderCourierService {

    @Autowired
    private OmsOrderCourierMapper omsOrderCourierMapper;
    @Autowired
    private CourierService courierService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void updateCourierInfo(CourierInfo courierInfos) {
        String courierNo = courierInfos.getCourierNo();
        String logistics = JSON.toJSONString(courierInfos.getLogisticsList());
        omsOrderCourierMapper.updateByCourierNo(courierNo,logistics);
    }

    @Override
    public OmsOrderCourier getCourierInfo(String deliverySn) {
        OmsOrderCourier omsOrderCourier = omsOrderCourierMapper.queryByCourierNo(deliverySn);
        if (omsOrderCourier == null) {
            throw new BizException("未找到物流信息");
        }
        return omsOrderCourier;
    }

    @Override
    public OmsOrderCourier refreshCourier(String deliverySn) throws InterruptedException {
        RLock lock = redissonClient.getLock(OrderCacheEnum.COURIER_LOCK.getCode() + deliverySn);
        boolean b = lock.tryLock(0,1, TimeUnit.HOURS);

        OmsOrderCourier omsOrderCourier = omsOrderCourierMapper.queryByCourierNo(deliverySn);
        if (b) {
            if (omsOrderCourier == null) {
                throw new BizException("未找到物流信息");
            }
            CourierInfo courierInfo = courierService.queryTrack(CompanyEnum.descOf(omsOrderCourier.getCompany()),
                                                                omsOrderCourier.getCourierNo());
            updateCourierInfo(courierInfo);
        }
        return omsOrderCourierMapper.queryByCourierNo(deliverySn);
    }
}
