package cn.wisenergy.web.config.auto;

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

import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.mapper.WorkSubmitAdoptMapper;
import cn.wisenergy.mapper.WorkTimeOrderMapper;
import cn.wisenergy.model.app.WorkSubmitAdopt;
import cn.wisenergy.model.app.WorkTimeOrder;
import cn.wisenergy.service.WorkCollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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;
import java.util.List;

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

    @Autowired
    private WorkTimeOrderMapper workTimeOrderMapper;

    @Autowired
    private WorkCollectService workCollectService;

    @Autowired
    private WorkSubmitAdoptMapper workSubmitAdoptMapper;

    // 每天凌晨自动审核
    @Scheduled(cron = "0 0 0 * * ?")
    public void autoExamine() {
        log.info("admin[]config[]auto[]Examine[]autoExamine");
        // 获取系统默认值
        WorkSubmitAdopt workSubmitAdopt = workSubmitAdoptMapper.selectById(1);
        Integer autoAdopt = workSubmitAdopt.getAutoAdopt();

        //  更新work_time_order表
        Date yesterdayDate = getAutoExamineDay(autoAdopt);
        Date now = DateUtil.getToday();
        QueryWrapper<WorkTimeOrder> wrapper = new QueryWrapper<>();
        wrapper.in("status", 1,4);
        wrapper.le("work_day", yesterdayDate);
        List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectList(wrapper);
        UpdateWrapper<WorkTimeOrder> wtoWrapper = new UpdateWrapper<>();
        wtoWrapper.in("status", 1,4);
        wtoWrapper.le("work_day", yesterdayDate);
        WorkTimeOrder workTimeOrder1 = new WorkTimeOrder();
        workTimeOrder1.setStatus(5);
        workTimeOrder1.setModifyTime(now);
        int wtoRow = workTimeOrderMapper.update(workTimeOrder1, wtoWrapper);
        System.out.println("一共审核：" + wtoRow + "条工单");

        // 更新work_collect表

        workCollectService.updateByWorkTimeOrder(workTimeOrders);


    }


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


}
