package com.lightinit.hsdatagateway.modules.foreign.service;

import com.lightinit.hsdatagateway.common.exceptions.BaseException;
import com.lightinit.hsdatagateway.common.exceptions.InterfaceRequestException;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import com.lightinit.hsdatagateway.modules.gateway.service.ChargeService;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author: yangrui
 * @Date: 2019/3/5 12:31
 */
@Component
public class PayConfirmService {
    private final int retryFrequency = 3;
    private RequestDto requestDto;
    private ChargeService chargeService;

    public PayConfirmService(ChargeService chargeService) {
        this.chargeService = chargeService;
    }

    public PayConfirmService setRequestDto(RequestDto requestDto) {
        this.requestDto = requestDto;
        return this;
    }


    public RequestDto call() {

        if (Objects.isNull(requestDto)) {
            throw new BaseException("请求对象丢失", "500");
        }

        if (!requestDto.isFree()) {
            if (Objects.nonNull(requestDto.getEffectiveTime())) {
                if ((System.currentTimeMillis() >= requestDto.getEffectiveTime().getTime())) {
                    throw new InterfaceRequestException("接口时间已到期");
                }
            } else {
                boolean value = chargeService.updateByRouteIdAndRestValue(requestDto.getRouteId(), requestDto.getRestValue());
                if (!value) {
                    boolean mv = chargeService.updateByRouteId(requestDto.getRouteId());
                    if (!mv) {
                        throw new InterfaceRequestException("接口使用次数不足");
                    }
//                int i = 0;
//                while (true) {
//                    Charge charge = chargeService.getByAppAndRouteAndUserId(requestDto.getAppId(), requestDto.getRouteId(), requestDto.getUserId());
//                    if (charge.getRestValue() > 0) {
//                        boolean retryValue = chargeService.updateByRouteIdAndRestValue(requestDto.getRouteId(), charge.getRestValue());
//                        if (retryValue) {
//                            break;
//                        }
//                        if (i++ < retryFrequency) {
//                            continue;
//                        }
//                    }
//                    throw new InterfaceRequestException("接口使用次数不足");
//                }
                }
            }
        }


        return requestDto;
    }
}
