package com.huashe.park.collect.schedule;

import java.util.List;

import com.huashe.park.common.ByteArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.huashe.park.common.consts.enums.MachineStatus;
import com.huashe.park.common.job.schedule.TriggerTaskSupport;
import com.huashe.park.core.service.IPileHoleIndexRealtimeService;
import com.huashe.park.core.service.IPileMachineInfoService;
import com.huashe.park.domain.entity.PileMachineInfo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "huashe.job.sync-machine-status", name = "enabled", havingValue = "true")
public class SyncMachineStatJob extends TriggerTaskSupport {

    @Value("${huashe.job.sync-machine-status.desc}")
    private String jobDesc;

    @Override
    @Value("${huashe.job.sync-machine-status.cron}")
    public CronTrigger setTrigger(String cron) {
        super.trigger = new CronTrigger(cron);
        return super.trigger;
    }

    @Autowired
    private IPileMachineInfoService machineInfoService;

    @Autowired
    private IPileHoleIndexRealtimeService pileHoleIndexRealtimeService;

    @Override
    public String jobName() {
        return jobDesc;
    }

    @Override
    public void scheduledJob() {
        List<PileMachineInfo> pileMachineInfos = machineInfoService.selectPileMachineInfoList(new PileMachineInfo() {
            {
                setStatus(MachineStatus.MACHINE_STATUS_00.getCode());
            }
        });
        for (PileMachineInfo pileMachineInfo : pileMachineInfos) {
            try {
                int constructingPileHoleCnt = pileHoleIndexRealtimeService
                    .cntMachineConstructingPileHole(pileMachineInfo.getId());
                if (constructingPileHoleCnt < 1) {
                    pileMachineInfo.setStatus(MachineStatus.MACHINE_STATUS_01.getCode());
                    machineInfoService.updatePileMachineInfo(pileMachineInfo);
                }
            }
            catch (Exception e) {
                log.error("同步状态失败", e);
            }
        }
    }
}
