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;
        String state = data.getStatus();
        if (state == null || "0".equals(state)) {
            return false;
        }
        if (null == data.getState()){
            return false;
        }
        /**
         * 定时读取板链测试量, 与Redis中保存的测试量比较, 若变量发生变化, 则状态为运行
         */
        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 (data.getState().equals(value)){
            equipmentData.setEquipStatus(EquipStatusEnum.ALARM);
            return true;
        }
        equipmentData.setEquipStatus(EquipStatusEnum.RUN);
        testValueOperations.set(key, data.getState());
        return true;
    }

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

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