package org.dromara.job.snailjob;

import cn.hutool.core.date.DateUtil;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.core.util.JsonUtil;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.dromara.biz.domain.StatDept;
import org.dromara.biz.mapper.StatDeptMapper;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author opensnail
 * @date 2024-05-17
 */
@Component
@JobExecutor(name = "statTaskOneDayJobExecutor")
public class StatTaskOneDayJobExecutor {

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private StatDeptMapper statDeptMapper;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        SnailJobLog.LOCAL.info("testJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
        SnailJobLog.REMOTE.info("testJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));

        Date now = new Date();
        Date today = DateUtils.dateTime(DateUtils.YYYY_MM_DD, DateUtils.getDate());
        Date yesterday = DateUtil.offsetDay(today, -1);

        List<SysDept> depts = sysDeptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getStatus, UserConstants.DEPT_NORMAL));

        for (SysDept dept : depts) {
            Long deptId = dept.getDeptId();
            // 每天0点10分前， 重新统计下昨天的数据
//            if (now.getHours() == 0 && now.getMinutes() < 10)
            {
                StatDept statDept = statDeptMapper.statYesterdayByDeptId(deptId);
                statDept.setDeptId(deptId);
                statDept.setDeptName(dept.getDeptName());
                statDept.setTjrq(yesterday);
                statDeptMapper.deleteYesterdayData(deptId);
                statDeptMapper.insert(statDept);
            }

            // 统计今天的数据
            StatDept statDept = statDeptMapper.statByDeptId(deptId);
            statDept.setDeptId(deptId);
            statDept.setDeptName(dept.getDeptName());
            statDept.setTjrq(today);
            statDeptMapper.deleteTodayData(deptId);
            statDeptMapper.insert(statDept);
        }

        return ExecuteResult.success("测试成功");
    }

}
