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

import cn.estsh.i3plus.pojo.mes.bean.MesEquipmentChannel;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import com.alibaba.fastjson.JSONObject;
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.*;
import java.util.stream.Collectors;

/**
 * 生产过程上下文对象-工位设备信息
 */
@Data
public class MesCellEquipContext implements Serializable {

    private static final long serialVersionUID = -2603242542443555462L;

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

    @ApiParam("腔数")
    private Integer cavity;

    @ApiParam("每腔装配件个数")
    private Integer bindQty;

    @ApiParam("顺序")
    private Integer seq;

    @ApiParam("设备ID")
    private Integer equipId;

    @ApiParam("设备代码")
    private String equipmentCode;

    @ApiParam("设备名称")
    private String equipmentName;

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

    @ApiParam("是否控制byPass")
    private Integer ctrlByPass;

    @ApiParam("设备质量")
    private Integer quality = MesExtEnumUtil.EQUIP_LOG_QUALITY.QUALITY.getValueInt();

    @ApiParam("kepware标识 Map<channel, kepwareFlag>")
    private String kepwareFlagJson;

    //根据通到获取对应的kepware标识
    public String getKepwareFlag(String channel) {

        if (StringUtils.isEmpty(channel) || StringUtils.isEmpty(this.kepwareFlagJson)) return null;

        Map<String, String> kepwareFlagMap = JSONObject.parseObject(this.kepwareFlagJson, Map.class);

        return !CollectionUtils.isEmpty(kepwareFlagMap) ? kepwareFlagMap.get(channel) : null;

    }

    //赋值kepware标识数据
    public MesCellEquipContext kepwareFlagJson(List<MesEquipmentChannel> equipmentChannelList) {

        equipmentChannelList = CollectionUtils.isEmpty(equipmentChannelList) ? null :
                equipmentChannelList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getChannel()) && !StringUtils.isEmpty(o.getKepwareFlag())))
                        .distinct().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MesEquipmentChannel::getChannel))), ArrayList::new));

        Map<String, String> kepwareFlagMap = CollectionUtils.isEmpty(equipmentChannelList) ? null :
                equipmentChannelList.stream().filter(o -> null != o).collect(Collectors.toMap(MesEquipmentChannel::getChannel, MesEquipmentChannel::getKepwareFlag));

        this.kepwareFlagJson = !CollectionUtils.isEmpty(kepwareFlagMap) ? JSONObject.toJSONString(kepwareFlagMap) : null;

        return this;
    }
}
