package net.vtstar.zhongtong.avi.gateway.assembly.job;

import lombok.extern.slf4j.Slf4j;
import net.vtstar.scada.base.equipmgt.domain.Enum.EquipStatusEnum;
import net.vtstar.scada.base.gather.domain.EquipmentData;
import net.vtstar.scada.base.gather.job.GatherJob;
import net.vtstar.zhongtong.avi.gateway.assembly.domain.PlateChainStateMachine;
import net.vtstar.zhongtong.avi.utils.EquipDataUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

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

/**
 * 总装板链状态设备数据采集JOB
 */
@Slf4j
@Component
public class PlateChainStateMachineJob extends GatherJob {

    private static final String NAME = "ASSEMBLY_PLATE_CHAIN";

    @Resource(name = "redisTemplate")
    protected ValueOperations testValueOperations;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        log.info("JobName: {}", context.getJobDetail().getKey().getName());
        super.gatherByModbus(NAME, PlateChainStateMachine.class);
    }

    @Override
    public boolean handleObject(EquipmentData equipmentData) {
        PlateChainStateMachine data = (PlateChainStateMachine) equipmentData;
        Integer state = data.getState();
        if (state == null) {
            return false;
        }
        String key = EquipDataUtil.getTestValueKey(equipmentData.getEquipCode());
        Object value = testValueOperations.get(key);
        if (value == null || "".equals(value.toString())){
            equipmentData.setEquipStatus(EquipStatusEnum.ALARM);
            testValueOperations.set(key, state);
            return true;
        }
        if (state.equals(value)){
            return false;
        }
        equipmentData.setEquipStatus(EquipStatusEnum.RUN);
        testValueOperations.set(key, state);
        return true;
    }

    @Override
    public Object handleValue(String fieldName, Object value) {
        return value;
    }

    @Override
    protected void postHandle(EquipmentData equipmentData) {
        ((PlateChainStateMachine)equipmentData).setCreateTime(new Date());
    }
}
