package cn.wisenergy.web.config.auto;

/**
 * @Authotr:陈奇
 * @QQ1799796883
 */

import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.mapper.WorkCollectMapper;
import cn.wisenergy.mapper.WorkSubmitAdoptMapper;
import cn.wisenergy.mapper.WorkTimeOrderMapper;
import cn.wisenergy.model.app.WorkCollect;
import cn.wisenergy.model.app.WorkSubmitAdopt;
import cn.wisenergy.model.app.WorkTimeOrder;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

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

/**
 * 自动审批定时器
 */
@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class Examin {

    @Autowired
    private WorkTimeOrderMapper workTimeOrderMapper;

    @Autowired
    private WorkCollectMapper workCollectMapper;

    @Autowired
    private WorkSubmitAdoptMapper workSbumitAdoptMapper;

    @Scheduled(cron = "0 0 0 * * ?")
    public void autoExamin() {
        log.info("admin[]config[]auto[]Examin[]autoExamin");
        WorkSubmitAdopt workSbumitAdopt = workSbumitAdoptMapper.selectById(1);
        Integer autoAdopt = workSbumitAdopt.getAutoAdopt();
        Date yesterdayDate = getAutoExaminDay(autoAdopt);
        Date now = DateUtil.getToday();
        UpdateWrapper<WorkTimeOrder> WTOwrapper = new UpdateWrapper<>();
        WTOwrapper.eq("status", 1);
        WTOwrapper.le("work_day", yesterdayDate);
        WorkTimeOrder workTimeOrder = new WorkTimeOrder();
        workTimeOrder.setStatus(5);
        workTimeOrder.setModifyTime(now);
        int wtoRow = workTimeOrderMapper.update(workTimeOrder, WTOwrapper);
        System.out.println("一共审核：" + wtoRow + "条工单");
        WorkCollect workCollect = new WorkCollect();
        UpdateWrapper<WorkCollect> wcw = new UpdateWrapper<>();
        wcw.eq("status", 1);
        wcw.le("work_day", yesterdayDate);
        workCollect.setStatus(2);
        workCollect.setModifyTime(now);
        int wcRow = workCollectMapper.update(workCollect, wcw);
        System.out.println("一共审核：" + wcRow + "条工单");
    }


    public static Date getAutoExaminDay(Integer day) {
        day = -(day + 1);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -2);
        Date start = c.getTime();
        String qyt= format.format(start);
        System.out.println(qyt);
        Date date = DateUtil.convertStrToDate(qyt, "yyyy-MM-dd");
        return date;
    }
}
