package com.xhkjedu.suser.utils;

import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author ywx
 * @className suserUtil
 * @description
 * @date 2022/2/21 15:27
 **/
@Slf4j
public class UserUtil {
    /**
     * 发送form-data请求返回json结果
     *
     * @return java.lang.String
     * @Param [apiUrl, param]
     * @Author ywx
     * @Date 2021/5/14 17:41
     **/
    public static String sendFormData(String apiUrl, MultiValueMap<String, String> param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            List<MediaType> acceptableMediaTypes = new ArrayList<>();
            acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
            acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
            HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(param, headers);
            ResponseEntity<String> response = new RestTemplate().postForEntity(apiUrl, requestParams, String.class);
            String result = response.getBody();
            return result;
        } catch (RestClientException e) {
            log.error("发送form-data请求失败", e.getMessage());
            return null;
        }
    }

    /**
     * 功能描述  校验密码，包含字母和数字，长度6-16
     *
     * @param * @param loginpwd
     * @return ResultVo
     * @author WN
     * @date 2022/3/15
     */
    public static ResultVo checkhLoginPwd(String loginpwd) {
        ResultVo resultVo = new ResultVo(1, "密码必须是6-16位的英文字母、数字组合");
        String passRegex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        if (loginpwd.matches(passRegex)) {
            resultVo = new ResultVo(0, "密码符合规范");
        }
        return resultVo;
    }

    //线程是否执行完
    public static void isAllDone(List<Future> futureList) {
        while (true) {
            if (N_Utils.isListNotEmpty(futureList)) {
                boolean isAllDone = true;
                for (Future future : futureList) {
                    if (null == future || !future.isDone()) {
                        isAllDone = false;
                    }
                }
                if (isAllDone) {
                    break;
                }
            }
        }
    }
}
