package com.cftech.order.job;

import com.cftech.accounts.model.SysJob;
import com.cftech.accounts.service.JobService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.Constants;
import com.cftech.core.util.SpringContextHolder;
import com.cftech.core.util.SystemConfig;
import com.cftech.order.model.Order;
import com.cftech.order.service.OrderService;
import com.cftech.orderdetail.service.OrderDetailsService;
import com.cftech.orderdetail.service.impl.OrderDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

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

/**
 * 待付款订单，半小时未付款自动取消
 * Created by 16444 on 2020/11/24.
 */
@Slf4j
public class OrderExpiredRemindJob implements Job {

    /**
     * @param context 通过JobExecutionContext对象访问到Quartz运行时候的环境以及Job本身的数据明细
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        boolean isCluster = Boolean.valueOf(SystemConfig.p.getProperty("quartz.isCluster"));
        if (!isCluster) {
            return;
        }

        Conds orderConds = new Conds();
        orderConds.equal("o.del_flag", Constants.DEL_FLAG_0);
        orderConds.equal("o.status", "1");//待付款订单
        OrderService orderService = SpringContextHolder.getBean(OrderService.class);
        List<Order> orders = orderService.fetchSearchByPage(orderConds, null, 0, 0);
        for (Order ord: orders) {
            Date orderTime = ord.getOrderTime();//确认时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(orderTime);
            calendar.add(Calendar.MINUTE, 30);
            orderTime = calendar.getTime();
            //超过半小时
            if (orderTime.compareTo(new Date()) < 0 ) {
                ord.setStatus("5");
                ord.setCancelTime(new Date());
                ord.setOrderCancel("订单超时取消");
                orderService.update(ord);
            }
        }

        //获得明细数据
        JobDataMap jobInfo = context.getJobDetail().getJobDataMap();
        String id = jobInfo.get("uid") == null ? "" : jobInfo.getString("uid");//这个也是ID主键
        log.info("任务ID：" + id);

        //执行更新操作
        if (context.getNextFireTime() != null) {
            log.info("订单半小时未付款过期任务：下次执行时间=====" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(context.getNextFireTime()) + "==============");
        } else {
            JobService jobService = SpringContextHolder.getBean(JobService.class);
            SysJob sysJob = new SysJob();
            sysJob.setJobuid(id);
            sysJob.setStatus("0");
            jobService.updateStatus(sysJob);
            log.info("订单半小时未付款过期任务，已执行完成");
        }
    }
}
