package com.kym.miniapp.jobs;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kym.common.utils.CommUtil;
import com.kym.entity.common.RedisKeys;
import com.kym.entity.miniapp.ChargeOrder;
import com.kym.service.miniapp.ChargeOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author skyline
 * 设备充电状态信息（订单信息）更新定时任务
 * 2024-08-12
 */
@Component
@Slf4j
public class EquipmentChargeStatusJob {

    private final StringRedisTemplate redisTemplate;
    private final ChargeOrderService chargeOrderService;

    public EquipmentChargeStatusJob(StringRedisTemplate redisTemplate, ChargeOrderService chargeOrderService) {
        this.redisTemplate = redisTemplate;
        this.chargeOrderService = chargeOrderService;
    }

    // 每5分钟执行一次
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void executeMpUserRelationJob() {
        log.info("设备充电状态信息（订单信息）更新定时任务启动...");
        var orders = redisTemplate.opsForHash().values(RedisKeys.CHARGE_ORDER_EQUIP_CHARGE_STATUS);
        if (CommUtil.isNotEmptyAndNull(orders)) {
            var orderList = new ArrayList<ChargeOrder>();
            orders.forEach(order -> {
                var chargeOrder = JSONObject.parseObject(order.toString(), ChargeOrder.class);
                orderList.add(chargeOrder);
                if (chargeOrder.getChargeStatus().equals(ChargeOrder.CHARGE_STATUS_停止中) || chargeOrder.getChargeStatus().equals(ChargeOrder.CHARGE_STATUS_已结束)) {
                    redisTemplate.opsForHash().delete(RedisKeys.CHARGE_ORDER_EQUIP_CHARGE_STATUS, chargeOrder.getStartChargeSeq());
                }
            });
            chargeOrderService.updateBatchByQueryWrapper(orderList, order ->
                    new QueryWrapper<ChargeOrder>().eq("start_charge_seq", order.getStartChargeSeq()));
        }
        log.info("设备充电状态信息（订单信息）更新定时任务结束...");
    }

}
