package org.ta.pddserver.serviceutil;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.ta.pdd.entity.WaybillSeaEntity;
import org.ta.pddserver.service.impl.CollectReceiverDetailImpl;
import org.ta.pddserver.service.impl.WaybillSeaImpl;

@Slf4j
@Component
public class WaybillOperator {

    @Resource
    WaybillSeaImpl waybillSeaImpl;

    WaybillSeaEntity currentWaybillSea;

    @Resource
    CollectReceiverDetailImpl collectReceiverDetailImpl;

    @Value("${pdd.lotto}")
    private Integer lotto;

    @PostConstruct
    public void init() {
        log.info("初始化 WaybillOperator，获取当前面单池状态");
        WaybillSeaEntity waybillSeaEntity = waybillSeaImpl.getFirstUsable();
        if (waybillSeaImpl != null) {
            currentWaybillSea = waybillSeaEntity;
            log.info("面单池更新完成，快递公司编码{}，当前单号{}，剩余单号数量{}", waybillSeaEntity.getExpressCode(), waybillSeaEntity.getCurrentNo(), (waybillSeaEntity.getEndNo() - waybillSeaEntity.getCurrentNo()));
        }
    }

    public WaybillInfo generateWaybillInfo() {
        WaybillInfo waybillInfo = new WaybillInfo();
        Long currentNo = currentWaybillSea.getCurrentNo() + 1;
        long verifyByte = 0;
        if (currentWaybillSea.getVerifyType() == 1) {
            verifyByte = currentNo % currentWaybillSea.getVerifyVal();
        }
        waybillInfo.setExpressCode(currentWaybillSea.getExpressCode());
        waybillInfo.setMailNo("" + currentNo + verifyByte);
        currentWaybillSea.setCurrentNo(currentNo);
        if (this.lotto > 0) {
            // 测试不更新
            waybillSeaImpl.updateById(currentWaybillSea);
        }
        return waybillInfo;
    }

    @Data
    public static class WaybillInfo {
        private String expressCode;
        private String mailNo;
    }
}
