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.RemoteDictTypeService;
import com.ruoyi.ext.api.db.DBResult;
import com.ruoyi.ext.api.domain.SysDictData;
import com.ruoyi.ext.api.domain.SysObjDictType;
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.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 对象字典校验注解实现
 *
 * @author ruoyi
 */
public class ObjDictValidator implements ConstraintValidator<DictV, String> {
    private String dictType;

    @Autowired
    private RemoteDictTypeService remoteDictTypeService;
    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 + "参数不符合规范");
        }
        SysObjDictType sysObjDictType = new SysObjDictType();
        sysObjDictType.setDictType(dictType);
        AjaxResult result = remoteDictTypeService.objdict(sysObjDictType, SecurityConstants.INNER);
        List<DBResult> data = result.getData(new TypeReference<List<DBResult>>() {
        });
        Map<Object, Integer> map =
                data.stream().collect(Collectors.toMap(new Function<DBResult, Object>() {
                    @Override
                    public Object apply(DBResult dbResult) {
                        return dbResult.getInt(0,0);
                    }
                }, dbResult -> 1));

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


}
