package cn.estsh.i3plus.ext.mes.pcn.pojo.context;

import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 生产过程上下文对象-数据变量接口逻辑信息
 */
@Data
public class MesEquipVariableCfgCollectContext implements Serializable {

    private static final long serialVersionUID = 4521711037005858586L;

    @ApiParam("组织代码")
    private String organizeCode;

    @ApiParam("变量配置类型")
    private String variableCfgType;

    @ApiParam("变量类别")
    private String variableCategory;

    @ApiParam("二级变量")
    private String categoryLevelTwo;

    @ApiParam("规则类别")
    private String ruleCategory;

    @ApiParam("参考值")
    private String value;

    @ApiParam("是否常变值")
    private Integer needNewValue;

    @ApiParam("数据变量集合")
    private List<MesEquipVariableCollectContext> equipVariableCollectContextList;

    @ApiParam("设备LOG表ID集合")
    private Map<Long, String> equipmentLogIdMap;

    @ApiParam("是否采集到数据")
    private Boolean isCollectValue = false;

    public MesEquipVariableCfgCollectContext equipVariableCollectContextList(List<MesEquipVariableCollectContext> equipVariableCollectContextList) {
        if (CollectionUtils.isEmpty(equipVariableCollectContextList)) return this;
        for (MesEquipVariableCollectContext equipVariableCollectContext : equipVariableCollectContextList) {
            if (null == equipVariableCollectContext) continue;
            //判断是否常变值, 常变值equipVariableStatus必须状态=0
            if (MesExtEnumUtil.EQUIP_VARIABLE_NEED_NEW_VALUE.TRUE.getValue() == this.needNewValue && (StringUtils.isEmpty(equipVariableCollectContext.getEquipVariableStatus()) ||
                    MesExtEnumUtil.EQUIP_VARIABLE_NEED_NEW_VALUE.TRUE.getEquipVariableStatus() != equipVariableCollectContext.getEquipVariableStatus())) equipVariableCollectContext.setEquipVariableValue(null);
            //已经采集到任何数据情况下isCollectValue标记为true
            if (!StringUtils.isEmpty(equipVariableCollectContext.getEquipVariableValue())) this.isCollectValue = true;
        }
        this.equipVariableCollectContextList = equipVariableCollectContextList;
        this.equipmentLogIdMap = equipVariableCollectContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getEquipmentLogId()))).collect(Collectors.toMap(MesEquipVariableCollectContext::getEquipmentLogId, MesEquipVariableCollectContext::getWriteDatetime));
        return this;
    }

}
