package com.cusc.nirvana.user.rnr.fp.scheduled;

import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.rnr.fp.common.constant.FpRedisConstant;
import com.cusc.nirvana.user.rnr.fp.service.IRnrService;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderStatusEnum;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Calendar;

@Service
@Slf4j
@EnableScheduling
public class OrderScheduledService {

    @Autowired
    private IRnrService rnrService;

    @Resource
    private RnrOrderClient orderClient;

    @Resource
    private CacheFactory cacheFactory;

    /**
     * 定时任务，从数据库中获取已提交并，每隔5分钟执行一次
     */
    //@Scheduled(fixedRateString = "${rnr.order.invalid:60000}")
    public void execInvalidOrder() {
        try {
            cacheFactory.getLockService()
                    .lock(FpRedisConstant.ORDER_SCHEDULED_LOCK, FpRedisConstant.ORDER_SCHEDULED_LOCK_EXPIRE);
            RnrOrderDTO orderDTO = new RnrOrderDTO();
            orderDTO.setPageSize(1000);
            orderDTO.setCurrPage(1);
            orderDTO.setOrderStatus(RnrOrderStatusEnum.COMMIT.getCode());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR_OF_DAY, -1);
            orderDTO.setCreateTime(calendar.getTime());
            Response<PageResult<RnrOrderDTO>> orderPageResp = orderClient.queryByPage(orderDTO);
            if (orderPageResp.isSuccess() && orderPageResp.getData() != null && !CollectionUtils.isEmpty(orderPageResp.getData().getList())) {
                for(RnrOrderDTO order : orderPageResp.getData().getList()){
                    rnrService.updateRnrInValid(order);
                }
            }
        } catch (CacheException e) {
            log.error("OrderScheduledService execInvalidOrder lock ", e);
        } finally {
            try {
                cacheFactory.getLockService().unLock(FpRedisConstant.ORDER_SCHEDULED_LOCK);
            } catch (CacheException e) {
                log.error("OrderScheduledService execInvalidOrder unlock ", e);
            }
        }
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, -1);
        System.out.println(calendar.getTime());
    }
}
