package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.base.bu;

import cn.estsh.i3plus.ext.mes.pcn.api.base.bu.IMesBusiConfigService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesBusiConfig;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesBusiConfigRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-bu
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2023-01-03 13:59
 */
@Service
public class MesBusiConfigService implements IMesBusiConfigService {

    @Autowired
    private MesBusiConfigRepository busiConfigRepository;

    @Override
    public MesBusiConfig queryBusiConfigeByCfgCode(String cfgCode, String organizeCode) {
        return busiConfigRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.IS_DELETED,
                        MesPcnExtConstWords.CFG_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), cfgCode});
    }

    @Override
    public Map<String, String> getConfigMap(String organizeCode, String cfgCode) {
        List<MesBusiConfig> busiConfigList = busiConfigRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.CFG_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), cfgCode});
        busiConfigList = CollectionUtils.isEmpty(busiConfigList) ? null :
                busiConfigList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getCfgValue()) && !StringUtils.isEmpty(o.getCfgValueSeq()))).collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MesBusiConfig::getCfgValueSeq))), ArrayList::new)
                );
        return CollectionUtils.isEmpty(busiConfigList) ? null :
                busiConfigList.stream().filter(o -> null != o).collect(Collectors.toMap(MesBusiConfig::getCfgValueSeq, MesBusiConfig::getCfgValue));
    }
}
