package com.fs.express.impl;

import com.alibaba.fastjson.JSON;
import com.fs.express.IExpressService;
import com.fs.express.dto.ExpressPushRespDTO;
import com.fs.express.enums.TaskStatusEnum;
import com.fs.express.http.KdniaoSubscribeHttp;
import com.fs.express.http.dto.LogisticsInfoDTO;
import com.fs.store.domain.FsOrderExpressPush;
import com.fs.store.mapper.FsOrderExpressPushMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.List;

/**
 * 物流相关处理
 */
@Service
@Slf4j
public class ExpressServiceImpl implements IExpressService {
    @Autowired
    private FsOrderExpressPushMapper fsOrderExpressPushMapper;

    @Autowired
    private KdniaoSubscribeHttp kdniaoSubscribeHttp;

    /**
     * 推送物流信息到快递鸟
     */
    @Override
    public void subscribeExpress() {
        log.info("开始处理待订阅的物流信息");

        List<FsOrderExpressPush> fsOrderExpressPushes = fsOrderExpressPushMapper.queryPendingData();
        log.info("查询到待处理的物流信息数量: {}", fsOrderExpressPushes.size());

        for (FsOrderExpressPush fsOrderExpressPush : fsOrderExpressPushes) {
            log.info("处理物流单号: {}", fsOrderExpressPush.getOrderId());
            String params = fsOrderExpressPush.getParams();
            ExpressPushRespDTO expressPushRespDTO = null;
            try {
                params = URLDecoder.decode(params, "UTF-8");
                LogisticsInfoDTO payload = JSON.parseObject(params, LogisticsInfoDTO.class);
                expressPushRespDTO = kdniaoSubscribeHttp.subscribeLogistic(payload);
            } catch (Throwable e) {
                log.error("物流订阅发生异常 - 单号: {}, 错误信息: {}", fsOrderExpressPush.getOrderId(), JSON.toJSONString(e));
                expressPushRespDTO = new ExpressPushRespDTO();
                expressPushRespDTO.setSuccess(false);
                expressPushRespDTO.setReason(JSON.toJSONString(e));
            }

            fsOrderExpressPush.setResult(JSON.toJSONString(expressPushRespDTO));
            if(expressPushRespDTO.getSuccess()) {
                fsOrderExpressPush.setTaskStatus(TaskStatusEnum.SUCCESS.getCode());
                log.info("物流订阅成功 - 单号: {}", fsOrderExpressPush.getOrderId());
            } else {
                fsOrderExpressPush.setTaskStatus(TaskStatusEnum.FAILED.getCode());
                fsOrderExpressPush.setRetryCount(fsOrderExpressPush.getRetryCount()+1);
                log.warn("物流订阅失败 - 单号: {}, 重试次数: {}", fsOrderExpressPush.getOrderId(), fsOrderExpressPush.getRetryCount());

            }
            fsOrderExpressPushMapper.update(fsOrderExpressPush);
            log.info("更新物流信息 - 单号: {}, 处理结果: {}", fsOrderExpressPush.getOrderId(), JSON.toJSONString(expressPushRespDTO));
        }

        log.info("物流订阅处理完成");
    }
}
