package cn.iocoder.yudao.module.pms.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectPlanDO;
import cn.iocoder.yudao.module.pms.dal.mysql.inspect.IotInspectPlanMapper;
import cn.iocoder.yudao.module.pms.service.inspect.IotInspectOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class InspectCreateOrderJob implements JobHandler {
    @Resource
    private IotInspectPlanMapper iotInspectPlanMapper;
    @Resource
    private IotInspectOrderService iotInspectOrderService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    @DataPermission(enable = false)
    @TenantIgnore
    public String execute(String param) throws Exception {
//        try {
            TenantUtils.execute(1L, () -> {
                List<IotInspectPlanDO> plans = iotInspectPlanMapper.selectList();
                plans.stream().filter(e -> e.getStatus()==0).forEach(plan -> {
                    if (plan.getLastCreateTime()==null&& Objects.nonNull(plan.getBeginCreateTime())) {
                        //当首次执行时间大于当前时间
                        if (plan.getBeginCreateTime().isBefore(LocalDateTime.now())) {
                            Date date = Date.from(
                                    plan.getBeginCreateTime().atZone(ZoneId.systemDefault()) // 使用系统默认时区
                                            .toInstant()                    // 转为 Instant（时间戳）
                            );
                            deal(plan, date);
                        }
                    } else {
                        Date lastdate = Date.from(
                                plan.getLastCreateTime().atZone(ZoneId.systemDefault()) // 使用系统默认时区
                                        .toInstant()                    // 转为 Instant（时间戳）
                        );
                        deal(plan, lastdate);
                    }
                });
            });
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }
        return "创建成功";
    }

    private void deal(IotInspectPlanDO plan, Date date) {
        Date date1 = new Date();
        if ("hour".equals(plan.getPlanUnit())){
            DateTime dateTime = DateUtil.offsetHour(date, Integer.parseInt(StringUtils.substringBeforeLast(String.valueOf(plan.getPlanCycle()),".")));
            if (date1.compareTo(dateTime) > 0){
                iotInspectOrderService.createPlan(plan);
            }
        } else if ("day".equals(plan.getPlanUnit())){
            DateTime dateTime = DateUtil.offsetDay(date, Integer.parseInt(StringUtils.substringBeforeLast(String.valueOf(plan.getPlanCycle()),".")));
            if (date1.compareTo(dateTime) > 0){
                iotInspectOrderService.createPlan(plan);
            }
        } else if ("month".equals(plan.getPlanUnit())){
            DateTime dateTime = DateUtil.offsetMonth(date, Integer.parseInt(StringUtils.substringBeforeLast(String.valueOf(plan.getPlanCycle()),".")));
            if (date1.compareTo(dateTime) > 0){
                iotInspectOrderService.createPlan(plan);
            }
        }
    }
}
