package com.kiisoo.ic.job.count;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.system.entity.SysTaskDO;
import com.kiisoo.ic.system.mapper.SysTaskDOMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import static com.kiisoo.ic.system.constant.SysTaskConstant.*;

@Component
@Slf4j
public class SyncCountJobService {
    @Autowired
    private CustomerCountJob customerDataJob;

    @Autowired
    private SysTaskDOMapper sysTaskDOMapper;

    @Scheduled(cron = "0 0/15 9/1 * * ??")
    public void syncStoreCount(){
        try {
            int random = new Random().nextInt(100);
            Thread.sleep(random*100);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
            QueryWrapper<SysTaskDO> qw = new QueryWrapper<>();
            qw.eq("type",TASK_TYPE_STORE_COUNT).eq("create_time",sdf.format(new Date())).last("limit 1");
            SysTaskDO sysTaskDO = sysTaskDOMapper.selectOne(qw);
            if (sysTaskDO == null){
                sysTaskDO = new SysTaskDO(TASK_NAME_STORE_COUNT,TASK_STATUS_RUNNING,TASK_TYPE_STORE_COUNT,new Date());
                sysTaskDOMapper.insert(sysTaskDO);
                customerDataJob.handle(false,sysTaskDO);
            }
        }catch (Exception e){
            log.error("",e);
        }
    }

    @Scheduled(cron = "0 0 2 * * ?")
    public void syncAllCount(){
        try {
            int random = new Random().nextInt(100);
            Thread.sleep(random*100);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            QueryWrapper<SysTaskDO> qw = new QueryWrapper<>();
            qw.eq("type",TASK_TYPE_ALL_COUNT).eq("create_time",sdf.format(new Date())).last("limit 1");
            SysTaskDO sysTaskDO = sysTaskDOMapper.selectOne(qw);
            if (sysTaskDO == null){
                sysTaskDO = new SysTaskDO(TASK_NAME_ALL_COUNT,TASK_STATUS_RUNNING,TASK_TYPE_ALL_COUNT,new Date());
                sysTaskDOMapper.insert(sysTaskDO);
                customerDataJob.handle(true,sysTaskDO);
            }
        }catch (Exception e){
            log.error("",e);
        }
    }
}
