package com.shkj.wms.validator;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.shkj.common.core.domain.entity.SysDictData;
import com.shkj.common.utils.spring.SpringUtils;
import com.shkj.system.service.impl.SysDictDataServiceImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Dict注解校验实现类
 *
 * @Author lch
 */
public class DictInValidator implements ConstraintValidator<DictIn, Object> {

    private String type = "";

    @Override
    public void initialize(DictIn constraintAnnotation) {
        type = constraintAnnotation.type();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(type) || ObjectUtil.isNull(value)) {
            return false;
        }
        SysDictData dictData = new SysDictData();
        dictData.setDictType(type);
        List<SysDictData> dictList = SpringUtils.getBean(SysDictDataServiceImpl.class).selectDictDataList(dictData);
        if (CollectionUtil.isEmpty(dictList)) {
            return false;
        }

        List<String> result = new ArrayList<>();
        List<String> valueList = dictList.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
        if(value instanceof ArrayList<?>){
            for(Object o : (List<?>) value){
                result.add(String.class.cast(o));
            }
        }
        return valueList.containsAll(result);
    }

}
