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.AutomaticSpotWeldingMachine;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 焊装车顶点焊数据采集JOB
 */
@Slf4j
@Component
public class AutomaticSpotWeldingMachineJob extends GatherJob {

    private static final String NAME = "AUTOMATIC_SPOT_WELDING";

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

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

    @Override
    public boolean handleObject(EquipmentData equipmentData) {
        AutomaticSpotWeldingMachine data = (AutomaticSpotWeldingMachine) equipmentData;
        String state = data.getStatus();
        if (state == null || "0".equals(state)) {
            return false;
        }
        if (data.getWeldingSpotA1() == null || data.getWeldingSpotA2() == null || null == data.getPressure()){
            return false;
        }
        if(data.getWeldingSpotA1() ==0 && data.getWeldingSpotA2() == 0){
            return false;
        }
        equipmentData.setEquipStatus(EquipStatusEnum.RUN);
        return true;
    }

    @Override
    public Object handleValue(String fieldName, Object value) {
        if (null == value){
            return null;
        }
        if (fieldName.startsWith("weldingSpotA")){
            int intValue = Float.valueOf(Integer.valueOf(value.toString()) / 65535f * 5 * 4000).intValue();
            if (intValue < 1000){
                return 0;
            }
            return intValue;
        }
        if ("pressure".equals(fieldName)){
            return Integer.valueOf(value.toString()) / 1000f;
        }
        return value;
    }

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