package com.cusc.nirvana.user.rnr.fp.handler.impl;

import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrSmsInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.UnbindReceiceSMSDTO;
import com.cusc.nirvana.user.rnr.fp.handler.MessageCallbackHandler;
import com.cusc.nirvana.user.rnr.fp.service.IFpSurplusCardBindService;
import com.cusc.nirvana.user.rnr.mg.constants.MessageCallbackStatusEnum;
import com.cusc.nirvana.user.rnr.mg.dto.SurplusConfirmDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author yubo
 * @since 2022-05-04 16:27
 */
@Service
@Slf4j
public class SurplusMessageCallBackHandler implements MessageCallbackHandler {

    @Value("${message.callback.timeout:120}")
    private int timeOut;

    @Autowired
    IFpSurplusCardBindService cardBindService;

    @Override
    public Response callBack(FpRnrSmsInfoDTO rnrSmsInfoDTOResponseData, UnbindReceiceSMSDTO bean,long receiveTIme) {
        SurplusConfirmDto surplusConfirmDto = new SurplusConfirmDto();

        long startTime = rnrSmsInfoDTOResponseData.getCreateTime().getTime();
        log.info("当前时间: {},短信发送时间: {}", receiveTIme, toString());
        boolean isTimeOut = receiveTIme - timeOut * 1000 > startTime;

        if (isTimeOut) {
            surplusConfirmDto.setCallbackStatusEnum(MessageCallbackStatusEnum.TIMEOUT.getCode());
        } else {
            surplusConfirmDto.setCallbackStatusEnum(
                    StringUtils.equalsIgnoreCase(bean.getReplyContent(), "y") ?
                            MessageCallbackStatusEnum.Y.getCode() : MessageCallbackStatusEnum.N.getCode());
        }

        surplusConfirmDto.setOrderId(rnrSmsInfoDTOResponseData.getOrderId());
        return Response.createSuccess(cardBindService.confirm(surplusConfirmDto));
    }
}
