package net.vtstar.zhongtong.avi.gateway.painting.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.painting.domain.DryingRoomTempMachine;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

/**
 * 烘干室温度数据采集JOB
 */
@Slf4j
@Component
public class DryingRoomTempMachineJob extends GatherJob {

    private static final String NAME = "DRYING_ROOM_TEMP";

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

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

    @Override
    public boolean handleObject(EquipmentData equipmentData) {
        DryingRoomTempMachine data = (DryingRoomTempMachine) equipmentData;
        String state = data.getStatus();
        if (state == null || "0".equals(state)) {
            return false;
        }
        Integer state1 = data.getCombustionMachineState1();
        Integer state2 = data.getCombustionMachineState2();
        Integer state3 = data.getCombustionMachineState3();
        if (null == state1 && null == state2 && null == state3){
            return false;
        }
        if (null == data.getTemperature()){
            return false;
        }
        if (state1 != null && state1 == 1){
            equipmentData.setEquipStatus(EquipStatusEnum.RUN);
            return true;
        }
        if (state1 != null && state1 == 0){
            equipmentData.setEquipStatus(EquipStatusEnum.IDLE);
            return true;
        }
        if (state2 != null && state2 == 1){
            equipmentData.setEquipStatus(EquipStatusEnum.RUN);
            return true;
        }
        if (state2 != null && state2 == 0){
            equipmentData.setEquipStatus(EquipStatusEnum.IDLE);
            return true;
        }
        if (state3 != null && state3 == 1){
            equipmentData.setEquipStatus(EquipStatusEnum.RUN);
            return true;
        }
        if (state3 != null && state3 == 0){
            equipmentData.setEquipStatus(EquipStatusEnum.IDLE);
            return true;
        }
        return false;
    }

    @Override
    public Object handleValue(String fieldName, Object value) {
        if (null == value){
            return null;
        }
        if (fieldName.startsWith("combustionMachineState")){
            Integer valueInt = Integer.valueOf(value.toString());
            return valueInt & 0x01;
        }
        return value;
    }

    @Override
    protected void postHandle(EquipmentData equipmentData) {

    }
}
