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

import java.util.Date;

/**
 * 焊装板链数据采集JOB
 */
@Slf4j
@Component
public class PlateChainMachineJob extends GatherJob {

    private static final String NAME = "PLATE_CHAIN";

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

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

    @Override
    public boolean handleObject(EquipmentData equipmentData) {
        WeldingPlateChainMachine data = (WeldingPlateChainMachine) equipmentData;
        String state = data.getStatus();
        if (state == null){
            return false;
        }
        if (state != null && "0".equals(state)) {
            return false;
        }
        if (data.getState() == 0 && data.getErrorState() == 0){
            equipmentData.setEquipStatus(EquipStatusEnum.DISCONNECT);
        }
        if (data.getState() == 1){
            equipmentData.setEquipStatus(EquipStatusEnum.RUN);
        }
        if (data.getErrorState() == 1){
            //TODO: 设备报警
            equipmentData.setEquipStatus(EquipStatusEnum.ALARM);
        }
        return true;
    }

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

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