package cn.pluss.platform.job;

import cn.pluss.platform.device.MercOrderDetailService;
import cn.pluss.platform.device.MercOrderExpressService;
import cn.pluss.platform.entity.MercOrderDetail;
import cn.pluss.platform.entity.MercOrderExpress;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * TODO
 * 设备商城订单自动确认收货定时任务
 * @author crystal
 * @date 2022/4/27 16:57
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class DeviceShopOrderAutoReceiptJob {

    @Resource
    private MercOrderDetailService mercOrderDetailService;

    @Resource
    private MercOrderExpressService mercOrderExpressService;
    /**
     * 设备订单物流自动确认收货状态
     * 有物流信息后 15天自动确认收货
     * 每天执行一次
     */
    @Scheduled(fixedDelay = 60 * 60 * 1000 * 24)
    public void checkDeviceOrderStatusTask() {
        log.info("~设备订单物流自动确认收货状态定时任务开始~");
        String date = DateUtils.toString(DateUtils.add(Calendar.DAY_OF_MONTH,DateUtils.currentDate(),-15),"yyyy-MM-dd");
        QueryWrapper<MercOrderDetail> queryWrapper = new QueryWrapper<MercOrderDetail>()
                .eq("status",MercOrderDetail.STATUS_UN_RECEIVED)
                .isNotNull("logistNo").isNotNull("expressNo").last(" and DATE_FORMAT(createTime,'%Y-%m-%d') = '"+date+"'");
        List<MercOrderDetail> list = mercOrderDetailService.list(queryWrapper);
        if(!list.isEmpty()){
            for (MercOrderDetail d:list) {
                MercOrderExpress express = mercOrderExpressService.getByLogistNo(d.getLogistNo());
                //没有物流信息
                if(express == null){
                    continue;
                }
                d.setStatus(MercOrderDetail.STATUS_COMPLETE);
                mercOrderDetailService.updateById(d);
            }
        }
        log.info("~设备订单物流自动确认收货状态定时任务结束~");
    }
}
