package cn.axzo.msg.center.message.service.card.job;

import cn.axzo.msg.center.dal.mapper.CardLogMapper;
import cn.axzo.msg.center.utils.DateFormatUtil;
import cn.axzo.msg.center.utils.JSONObjectUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author yanglin
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ExpungeCardLogJob {

    private final CardLogMapper cardLogMapper;

    @XxlJob("expungeCardLogJob")
    public ReturnT<String> execute(String paramStr) throws Exception {
        log.info("start - run job with param={}", paramStr);
        try {
            Param param = StringUtils.isBlank(paramStr)
                    ? new Param() :
                    JSONObjectUtil.parseObject(paramStr, Param.class);
            expunge(param);
            log.info("end - run job with param={}", param);
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            log.warn("job failed. param={}", paramStr, e);
            return ReturnT.FAIL;
        }
    }

    private void expunge(Param param) {
        Date until = DateTime.now().minusDays(param.daysAgo).toDate();
        log.info("going to delete until={}", DateFormatUtil.toReadableString(until));
        int count = cardLogMapper.expunge(until);
        log.info("deleted count={}", count);
    }

    @Data
    public static class Param {
        private int daysAgo = 3;
    }
}
