package com.ruoyi.ext.api.validate;

import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.ext.api.RemoteDictDataService;
import com.ruoyi.ext.api.domain.SysDictData;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 自定义字典校验注解实现
 *
 * @author ruoyi
 */
public class DictValidator implements ConstraintValidator<DictV, String> {
    private String dictType;

    @Autowired
    private RemoteDictDataService remoteDictDataService;
    private boolean muti;
    private String message;
    private String name;


    @Override
    public void initialize(DictV constraintAnnotation) {
        dictType = constraintAnnotation.type();
        muti = constraintAnnotation.isMuti();
        message = constraintAnnotation.message();
        name = constraintAnnotation.name();

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(value)) {
            return true;
        }
        if (!StringUtils.isBlank(name)){
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate(name + "参数不符合规范");
        }
        AjaxResult result = remoteDictDataService.getDictDataByDictType(dictType, SecurityConstants.INNER);
        List<SysDictData> data = null;
//        result.getData(new TypeReference<List<SysDictData>>() {
//        });
        Map<Object, Integer> map =
                data.stream().collect(Collectors.toMap(SysDictData::getDictValue, item -> 0));

        if (data.size() == 0) {
            return false;
        } else {
            return muti ? Arrays.stream(value.split(",")).allMatch(map::containsKey) :
                    map.containsKey(value);
        }
    }


}
