package org.dromara.job.snailjob;

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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.work.domain.TpClient;
import org.dromara.work.domain.TpOrder;
import org.dromara.work.service.ITpClientService;
import org.dromara.work.service.ITpOrderService;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

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

    private final ITpOrderService tpOrderService;

    private final ITpClientService tpClientService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        String dateMinus180Days = getCurrentDateMinus180Days(180L);
        String dateMinus365Days = getCurrentDateMinus180Days(365L);
        List<TpClient> list = tpClientService.queryAllList();
        List<TpClient> newList = new ArrayList<>();

        for (TpClient tpClient : list){
            boolean exist = tpOrderService.exists(new LambdaQueryWrapper<TpOrder>().eq(TpOrder::getKid, tpClient.getId()).eq(TpOrder::getIsDel, 1).ge(TpOrder::getAddTime, dateMinus180Days));
            if (exist){
                if(tpClient.getHealth() != 1){
                    tpClient.setHealth(1);
                    newList.add(tpClient);
                }
                continue;
            }
            boolean exist2 = tpOrderService.exists(new LambdaQueryWrapper<TpOrder>().eq(TpOrder::getKid, tpClient.getId()).eq(TpOrder::getIsDel, 1).ge(TpOrder::getAddTime, dateMinus365Days));
            if (exist2){
                if(tpClient.getHealth() != 2){
                    tpClient.setHealth(2);
                    newList.add(tpClient);
                }
                continue;
            }else {
                if(tpClient.getHealth() != 3){
                    tpClient.setHealth(3);
                    newList.add(tpClient);
                }
            }
        }
        tpClientService.updateBatchById(newList);
        return ExecuteResult.success("执行成功");
    }


    public static String getCurrentDateMinus180Days(Long days) {
        try {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 计算当前日期减去180天的日期
            LocalDate dateMinus180Days = currentDate.minusDays(days);
            // 格式化日期为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            return dateMinus180Days.format(formatter);
        } catch (Exception e) {
            // 处理异常情况
            e.printStackTrace();
            return null;
        }
    }
}
