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

import com.lightinit.hsdatagateway.common.exceptions.ChargeInformationException;
import com.lightinit.hsdatagateway.common.exceptions.NoRestValueException;
import com.lightinit.hsdatagateway.common.exceptions.OverTimeException;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import com.lightinit.hsdatagateway.modules.gateway.entity.Charge;
import com.lightinit.hsdatagateway.modules.gateway.service.ChargeService;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @Author: yangrui
 * @Date: 2019/3/5 12:28
 */
@Component
public class PayVerifyService {
    private RequestDto requestDto;
    private ChargeService chargeService;

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

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

    public RequestDto call() {
        Charge charge = chargeService.getByAppAndRouteAndUserId(requestDto.getAppId(), requestDto.getRouteId(), requestDto.getUserId());
        if (Objects.isNull(charge)) {
            throw new ChargeInformationException("没有查询到该接口计费信息");
        }
        if (StringUtils.isNotBlank(charge.getChargeMethod()) && (!StringUtils.equals("free", charge.getChargeMethod()))){
            if (charge.getChargeMethod().equals("hours")) {
                if (!isEffectiveDate(charge.getEffectiveTime(), charge.getExpiredTime())) {
                    throw new OverTimeException("不在有效时间范围内");
                }
                requestDto.setEffectiveTime(charge.getExpiredTime());
            }  else if (charge.getChargeMethod().equals("times")){
                if (charge.getRestValue() != null && charge.getRestValue() <= 0) {
                    throw new NoRestValueException("没有剩余量");
                }
                requestDto.setRestValue(charge.getRestValue());
            }
        }else {
            requestDto.setFree(true);
        }

        return requestDto;
    }


    public static boolean isEffectiveDate(Date startTime, Date endTime) {
        Date date = new Date();
        if (startTime.getTime() <= date.getTime() && endTime.getTime() >= date.getTime()) {
            return true;
        } else {
            return false;
        }
    }


}
