package com.m2pool.pool.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.github.pagehelper.PageHelper;
import com.m2pool.common.core.constant.CacheConstants;
import com.m2pool.common.core.text.Convert;
import com.m2pool.common.core.utils.ServletUtils;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.common.core.utils.ip.IpUtils;
import com.m2pool.common.core.utils.uuid.IdUtils;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.redis.service.RedisService;
import com.m2pool.common.security.auth.ApiUtil;
import com.m2pool.common.security.service.OpenApiService;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.pool.dto.*;
import com.m2pool.pool.entity.*;
import com.m2pool.pool.enums.PoolAmount;
import com.m2pool.pool.enums.Pools;
import com.m2pool.pool.mapper.GoogleAuthMapper;
import com.m2pool.pool.mapper.UserAccountMapper;
import com.m2pool.pool.service.UserMinserService;
import com.m2pool.pool.utils.EnumUtils;
import com.m2pool.common.core.utils.GoogleAuthenticator;
import com.m2pool.pool.utils.NodeRpc;
import com.m2pool.pool.vo.*;
import com.m2pool.system.api.model.OpenApiKeyInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Date 2024/6/14 14:29
 * @Author dy
 */
@Service
public class UserMinerServiceImpl implements UserMinserService {

    @Autowired
    private UserAccountMapper uaMapper;

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private RedisService redisService;


    @Autowired
    private GoogleAuthMapper googleAuthMapper;


    @Value("${myenv.domain}")
    private String domain;

    @Value("${myenv.img}")
    private String image;


    @Override
    @DSTransactional()
    public AjaxResult addMinerAccount(MinerAccountAddVo vo) {
        //com.m2pool.chat.vo sql字段去脚本
        vo.setCoin(StringUtils.clean(vo.getCoin()));
        vo.setMa(StringUtils.clean(vo.getMa()));
        vo.setBalance(StringUtils.clean(vo.getBalance()));
        vo.setRemarks(StringUtils.clean(vo.getRemarks()));

        if(StringUtils.isBlank(vo.getBalance())){
            return AjaxResult.error("请先输入需要绑定的钱包地址");
        }

        //校验coin是否在规定范围之内
        Pools pool = (Pools) EnumUtils.get(Pools.class, vo.getCoin());
        if(StringUtils.isNull(pool)){
            return AjaxResult.error("矿池参数错误,找不到对应矿池");
        }


        try {
            if("alph".equals(pool.getCoin())){
                /* alph只校验长度(45)和开头(值为1) */
                if(StringUtils.isBlank(vo.getBalance())){
                    return  AjaxResult.error("钱包地址不能为空");
                }
                if(vo.getBalance().startsWith("1") && vo.getBalance().length()==45){
                    //校验通过放行
                }else {
                    return AjaxResult.error("您输入的地址无效，地址格式错误");
                }
            }else if("enx".equals(pool.getCoin())){
                /* enx只校验长度(45)和开头(值为1) */
            }else {
                boolean result = NodeRpc.checkAddress(vo.getCoin(), vo.getBalance());
                if (!result){
                    return AjaxResult.error("您输入的地址无效，请输入可以正常使用的地址");
                }
            }
        }catch (RuntimeException e){
            return  AjaxResult.error("您输入的地址无效，请输入可以正常使用的地址");
        }

        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("用户邮箱获取失败");
        }


        /** 判断是否绑定超过5个 */
        int count = uaMapper.getAccountNumberByUserAccountAndCoin(username, vo.getCoin());
        if(count >= 5){
            return AjaxResult.error("该币种下挖矿账户已达上限！不能再添加挖矿账户");
        }
        /** 判断挖矿账户是否存在 */
        if(uaMapper.checkAccountIfExist(vo.getMa(),vo.getCoin())){
            return AjaxResult.error("该挖矿账户已被他人使用，请修改后重新添加，重复添加失败");
        }
        UserMinerAccount account = new UserMinerAccount();
        account.setUser(username);
        BeanUtils.copyProperties(vo,account);

        //查询是否开启双重验证
        //谷歌验证码校验
        GoogleInfo googleInfo = googleAuthMapper.getGoogleInfoByEmail(username);
        if(StringUtils.isBlank(googleInfo.getSecret())){
            //未绑定定谷歌验证器
            return AjaxResult.error("您的账号未开启双重验证,请先开启验证!");
        }
        if(!GoogleAuthenticator.checkCode(googleInfo.getSecret(), vo.getCode(), System.currentTimeMillis())){
            return AjaxResult.error("谷歌验证码错误");
        }
        //if(StringUtils.isNull(googleInfo)){
        //    return AjaxResult.error("当前账户未绑定谷歌验证器,暂时不能添加账号");
        //}
        //
        //if(googleInfo.getStatus() == 0){
        //    return AjaxResult.error("当前账户未绑定谷歌验证器,暂时不能添加账号");
        //}
        //
        //if(googleInfo.getStatus() == 2){
        //    return AjaxResult.error("当前账户关闭了谷歌验证器,暂时不能添加账号");
        //}

        if(uaMapper.userAddMinerAccount(account) && account.getId()>0){
            System.out.println("id为"+account.getId());
            //todo  获取新写入的挖矿账户id 写入地址表
            AccountBalanceAddVo aVo = new AccountBalanceAddVo();
            aVo.setMa(vo.getMa());
            aVo.setBalance(vo.getBalance());
            aVo.setAmount(PoolAmount.getAmountByCoin(vo.getCoin()));

            uaMapper.accountAddBalance(account.getId(),aVo);
            //todo  日志记录
            return AjaxResult.success("挖矿账户添加成功");
        }else {
            return AjaxResult.error("挖矿账户添加失败请稍后再试");
        }

    }

    @Override
    public AjaxResult checkAccount(MinerAccountAddVo vo) {

        if(!vo.getMa().equals(StringUtils.clean(vo.getMa()))){

        }
        //校验coin是否在规定范围之内
        Pools pool = (Pools) EnumUtils.get(Pools.class, vo.getCoin());
        if(StringUtils.isNull(pool)){
            return AjaxResult.error("矿池参数错误,找不到对应矿池");
        }

        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("未获取到用户信息请稍后再试");
        }

        if(uaMapper.checkAccountIfExist(vo.getMa(),vo.getCoin())){
            return AjaxResult.success(false);
        }
        return AjaxResult.success(true);
    }

    @Override
    public AjaxResult checkBalance(BalanceCheckVo vo) {
        vo.setBalance(StringUtils.clean(vo.getBalance()));
        if(StringUtils.isBlank(vo.getBalance())){
            return AjaxResult.error("请先输入需要绑定的钱包地址");
        }

        //HttpHeaders headers = new HttpHeaders();
        //headers.add("Content-Type","application/json");
        //HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
        //StringBuffer paramsURL = new StringBuffer("http://13.229.139.183:23115/verify_wallet?address="+com.m2pool.chat.vo.getBalance()+"&coin="+com.m2pool.chat.vo.getCoin());
        //URI uri = URI.create(paramsURL.toString());
        //System.out.println(paramsURL.toString());
        try {
            boolean result = NodeRpc.checkAddress(vo.getCoin(), vo.getBalance());
            return AjaxResult.success(result);
        }catch (RuntimeException e){
            return  AjaxResult.error(e.getMessage());
        }


    }

    @Override
    public AjaxResult checkMaAndBalance(MaBalanceCheckVo vo) {

        if(!vo.getMa().equals(StringUtils.clean(vo.getMa()))){

        }
        //校验coin是否在规定范围之内
        Pools pool = (Pools) EnumUtils.get(Pools.class, vo.getCoin());
        if(StringUtils.isNull(pool)){
            return AjaxResult.error("矿池参数错误,未知矿池");
        }

        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("未获取到用户信息请稍后再试");
        }
        System.out.println("挖矿账号"+vo.getMa());
        boolean b = uaMapper.checkAccountIfExist(vo.getMa(), vo.getCoin());
        System.out.println("查询结果:"+b);
        if(b){
            return AjaxResult.error(801,"该挖矿账号名已被使用,不能在使用");
        }

        vo.setBalance(StringUtils.clean(vo.getBalance()));
        if(StringUtils.isBlank(vo.getBalance())){
            return AjaxResult.error("请先输入有效的钱包地址");
        }


        try {
            boolean result = NodeRpc.checkAddress(vo.getCoin(), vo.getBalance());
            return AjaxResult.success(result);
        }catch (RuntimeException e){
            return  AjaxResult.error(802,"该钱包地址不可用,请确认钱包地址是否是当前币种可用的钱包地址");
        }

    }

    @DSTransactional()
    @Override
    public AjaxResult delMinerAccount(MinerAccountDelVo vo) {
        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("用户信息获取失败");
        }

        String[] idStrs = vo.getId().split(",");

        if(idStrs.length > 20){
            return AjaxResult.error("最多同时删除20个账号");
        }
        List<UserAccountDto> list = new ArrayList<>();
        //校验挖矿账户名是否已存在
        /** 判断是否已绑定过该挖矿账号 */
        Map<String,Long> map =new HashMap<>();
        for(String id : idStrs){
            Long maId = Convert.toLong(id,0L);
            UserAccountDto dto = uaMapper.getAccountByUserAccountId(username, maId);
            //删除挖矿账户对应的只读页面

            if(StringUtils.isNull(dto)){
                return AjaxResult.error("挖矿账号异常:未找到id:"+maId+"对应的账户");
            }
            map.put(id,maId);
            list.add(dto);
        }

        //查询是否开启双重验证
        //谷歌验证码校验
        GoogleInfo googleInfo = googleAuthMapper.getGoogleInfoByEmail(username);
        if(StringUtils.isBlank(googleInfo.getSecret())){
            //未绑定定谷歌验证器
            return AjaxResult.error("您的账号未开启双重验证,请先开启验证!");
        }
        if(!GoogleAuthenticator.checkCode(googleInfo.getSecret(), vo.getGCode(), System.currentTimeMillis())){
            return AjaxResult.error("谷歌验证码错误");
        }


        List<Long> idsList = map.values().stream().collect(Collectors.toList());



        //删除用户挖矿账号  逻辑删除
        if(uaMapper.batchDelAccount(idsList)){
            //todo  修改钱包表钱包数据状态、并

            //todo 日志记录
            uaMapper.deleteBatchReadOnlyPage(list);
            return  AjaxResult.success("账号删除成功");
        }else {
            return AjaxResult.error("数据库执行异常");
        }

    }

    @DSTransactional()
    @Override
    public AjaxResult addBalance(AccountBalanceAddVo vo) {
        //包含操作 1绑定钱包地址 2设置起付金 3设置是否自动激活 4更换绑定钱包地址 5 修改起伏金额 6
        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("用户邮箱获取失败");
        }

        UserAccountDto dto = uaMapper.getAccountByUserAccountAndCoin(username, vo.getMa(),vo.getCoin());

        if(StringUtils.isNull(dto)){
            return AjaxResult.error("当前用户下没有该挖矿账号");
        }

        //校验是否已绑定过地址
        MinerAccountBalanceDto balance = uaMapper.getBalanceByMinerAccount(dto.getId());
        Pools pool = (Pools) EnumUtils.get(Pools.class, vo.getCoin());
        if(StringUtils.isNull(pool)){
            return AjaxResult.error("矿池参数错误！");
        }
        double amount = PoolAmount.getAmountByCoin(dto.getCoin());

        GoogleInfo googleInfo = googleAuthMapper.getGoogleInfoByEmail(username);
        if(StringUtils.isBlank(googleInfo.getSecret())){
            //未绑定定谷歌验证器
            return AjaxResult.error("您的账号未开启双重验证,请先开启验证!");
        }
        if(!GoogleAuthenticator.checkCode(googleInfo.getSecret(), vo.getGCode(), System.currentTimeMillis())){
            return AjaxResult.error("谷歌验证码错误");
        }

        if(StringUtils.isNotNull(balance)){
            //todo 判断是否是更新
            if(vo.getBalance().equals(balance.getBalance())){
                //相同 说明是修改其他信息 在远有数据基础上执行修改
                if(vo.getAmount() < PoolAmount.getAmountByCoin(dto.getCoin())){
                    return AjaxResult.error(pool.getName()+"设置起付金额不能小于"+amount);
                }
                System.out.println("com.m2pool.chat.vo:"+vo);

                vo.setRemarks(StringUtils.clean(vo.getRemarks()));
                uaMapper.updateMinerAccountRemark(dto.getId(),vo);

                uaMapper.updateBalance(balance.getId(), vo);
                return AjaxResult.success("修改完成");
            }else {
                //todo 从redis拿
                try {
                    boolean result = NodeRpc.checkAddress(vo.getCoin(), vo.getBalance());
                    //不同 说明是修改地址 先将原有地址数据状态修改为停用（99） 根据地址表id 再新增数据入库
                    if(result){
                        uaMapper.accountStopBalance(balance.getId(), vo);
                        //新增用户地址数据入库 写入挖矿账号id和地址信息
                        uaMapper.accountAddBalance(dto.getId(),vo);
                        return AjaxResult.success("修改成功");
                    }else {
                        return  AjaxResult.error("地址错误");
                    }
                }catch (RuntimeException e){
                    return  AjaxResult.error("当前接口请求用户过多,请稍后再试！");
                }


            }

        }

        //没有绑定
        if(vo.getAmount() == 0){
            vo.setAmount(amount);
        }

        if(vo.getAmount() < PoolAmount.getAmountByCoin(dto.getCoin())){
            return AjaxResult.error(pool.getName()+"设置起付金额不能小于"+amount);
        }

        if(uaMapper.accountAddBalance(dto.getId(),vo)){
            return AjaxResult.success();
        }else {
            return AjaxResult.error("当前用户下没有该挖矿账号");
        }

    }


    @Override
    public AjaxResult getAccountList() {

        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("用户邮箱获取失败");
        }

        List<UserAccountListDto> list = uaMapper.getAccountByUserAndCoin(username);
        list = list.stream().filter(e -> StringUtils.isNull(e.getAddr()) || (StringUtils.isNotNull(e.getAddr()) && (e.getAddrStatus() == 0))).collect(Collectors.toList());

        list.stream().forEach(e ->{
            Pools pool = (Pools) EnumUtils.get(Pools.class, e.getCoin());

            if(StringUtils.isNotNull(pool)){
                e.setPool(pool.getName());
                e.setImg(domain+image+"/"+pool.getImg());
            }

            if(StringUtils.isNotBlank(e.getAddr())){
                e.setAddrStatus(1);
            }else {
                e.setAddrStatus(0);
            }
        });

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getAccountGradeList() {
        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("用户邮箱获取失败");
        }

        List<UserAccountListDto> list = uaMapper.getAccountByUserAndCoin(username);
        list = list.stream().filter(e -> StringUtils.isNull(e.getAddr()) || (StringUtils.isNotNull(e.getAddr()) && (e.getAddrStatus() == 0))).collect(Collectors.toList());
        HashMap<String,List<UserAccountGradeDto>> map = new HashMap<>();

        list.stream().forEach(e ->{
            Pools pool = (Pools) EnumUtils.get(Pools.class, e.getCoin());

            if(StringUtils.isNotNull(pool)){
                UserAccountGradeDto gDto = new UserAccountGradeDto();
                gDto.setId(e.getId());
                gDto.setAccount(e.getMa());
                if(map.containsKey(pool.getCoin())){
                    //已有数据则原list中加入当前对象
                    map.get(pool.getCoin()).add(gDto);
                }else {
                    //没有数据创建list 并把当前对象加入list 再把list加入map中
                    List<UserAccountGradeDto> gList = new ArrayList<>();
                    gList.add(gDto);
                    map.put(pool.getCoin(),gList);
                }
            }
        });

        List<UserAccountGradeListDto> returnList = map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())).map(e ->
        {
            UserAccountGradeListDto lDto = new UserAccountGradeListDto();
            lDto.setTitle(Pools.getNameByCoin(e.getKey()));
            lDto.setCoin(e.getKey());
            lDto.setImg(domain+image+"/"+Pools.getImgByCoin(e.getKey()));
            lDto.setChildren(e.getValue());

            return lDto;
        }).collect(Collectors.toList());


        return AjaxResult.success(returnList);
    }

    @Override
    public AjaxResult getMinerAccountBalance(MinerIdVo vo) {
        String username = SecurityUtils.getUsername();

        if(StringUtils.isBlank(username)){
            return AjaxResult.error("用户邮箱获取失败");
        }
        UserAccountDto uaDto = uaMapper.getAccountByUserAccountId(username, vo.getId());
        System.out.println("uaDto:"+uaDto);
        if(StringUtils.isNull(uaDto)){
            return AjaxResult.error("当前矿池中未找到该挖矿账号");
        }


        MinerAccountBalanceDto dto = uaMapper.getBalanceByMinerAccount(uaDto.getId());

        if(StringUtils.isNotNull(dto)){
            double amount = PoolAmount.getAmountByCoin(uaDto.getCoin());
            if(dto.getAmount() <= amount){
                dto.setAmount(amount);
            }
        }else {
            dto = new MinerAccountBalanceDto();
            dto.setMa(uaDto.getAccount());
            dto.setAmount(PoolAmount.getAmountByCoin(uaDto.getCoin()));
        }

        return AjaxResult.success(dto);
    }

    @Override
    public AjaxResult createApiKey(ApiKeyCreateVo vo) {
        String user = SecurityUtils.getUsername();
        //校验
        if(StringUtils.isBlank(vo.getPerms())){
            return AjaxResult.success("权限不能为空");
        }

        List<String> perms = Arrays.asList(vo.getPerms().split(",").clone());
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }

        List<UserApi> list = uaMapper.getAPIListByUser(user);
        long count = list.stream().filter(e -> {
            OpenApiKeyInfo openApiKeyInfo = openApiService.getOpenApiKeyInfo(e.getKey());
            return openApiKeyInfo != null;
        }).count();
        if(count >= 5){
            return AjaxResult.error("apiKey创建次数已达上限：5");
        }

        //创建apikey
        String apiKey = IdUtils.fastUUID();

        OpenApiKey keyToDB = new OpenApiKey();
        keyToDB.setKey(apiKey);
        keyToDB.setUser(user);
        keyToDB.setPermissions(vo.getPerms());
        OpenApiKeyInfo info = new OpenApiKeyInfo();
        info.setKey(apiKey);
        info.setUser(user);
        if(StringUtils.isNotBlank(vo.getIp())){
            //格式校验 通过则设置api绑定的ip为输入的ip 否则设置为
            Boolean check = vo.getIp().matches("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");

            if(check){
                System.out.println("用户输入的地址："+info.getApiIp());
                info.setApiIp(vo.getIp());
                keyToDB.setApiIp(vo.getIp());
            }else {
                return AjaxResult.error("ip地址格式错误");
                //String ipAddr = IpUtils.getIpAddr(ServletUtils.getRequest());
                //info.setApiIp(ipAddr);
                //keyToDB.setApiIp(ipAddr);
                //System.out.println("iputils获取到的地址："+ipAddr);
            }
        }else {
            String ipAddr = IpUtils.getIpAddr(ServletUtils.getRequest());
            info.setApiIp(ipAddr);
            keyToDB.setApiIp(ipAddr);
            System.out.println("未传入ip,通过iputils获取到的地址："+ipAddr);
        }
        info.setPermissions(permsSet);
        //通过jwt创建api_key
        String key = Convert.toStr(openApiService.createApiKey(info).get("api_key"));
        System.out.println("创建的api_key"+key);
        System.out.println("共"+key.length()+"个字符");
        keyToDB.setKey(key);
        //存入数据库
        boolean result = uaMapper.userCreateApiKey(keyToDB);
        if(result){
            return AjaxResult.success();
        }else {
            return AjaxResult.error("服务器当前apiKey生成请求大多,apiKey生成失败,请稍后再试");
        }
    }

    @Override
    public List<UserApiDto> getApiList(PageVo vo) {
        long t0 = System.currentTimeMillis();
        //获取邮箱 网站用的邮箱做用户名
        String user = SecurityUtils.getUsername();
        if(StringUtils.isNull(user)){
            return null;
        }
        List<UserApi> list = uaMapper.getAPIListByUser(user);
        List<UserApiDto> returnList = list.stream().filter(e -> {
            OpenApiKeyInfo openApiKeyInfo = openApiService.getOpenApiKeyInfo(e.getKey());
            return openApiKeyInfo != null;
        }).map(e -> {
            UserApiDto dto = new UserApiDto();
            BeanUtils.copyProperties(e,dto);
            if(StringUtils.isNull(e.getPerms())){
                //防止字段为null时抛出异常 字段未null时设置字段为""
                dto.setPerms("".split(","));
            }else {
                dto.setPerms(e.getPerms().split(","));
            }
            return dto;
        }).collect(Collectors.toList());
        return returnList;
    }

    @Override
    public AjaxResult getApiInfo(ApiKeyInfoVo vo) {


        String email = SecurityUtils.getUsername();
        if(StringUtils.isNull(email)){
            return null;
        }
        PageHelper.clearPage();
        UserApi info = uaMapper.getAPIInfoByUserAndId(vo.getId(), email);
        if(StringUtils.isNull(info)){
            return AjaxResult.error("未找到对应ApiKey");
        }

        if(!email.equals(info.getUser())){
            return AjaxResult.error("token错误");
        }
        UserApiInfoReturnDto dto = new UserApiInfoReturnDto();
        BeanUtils.copyProperties(info,dto);
        if(StringUtils.isNull(info.getPerms())){
            //防止字段为null时抛出异常 字段未null时设置字段为""
            dto.setPerms("".split(","));
        }else {
            dto.setPerms(info.getPerms().split(","));
        }
        return AjaxResult.success(dto);
    }

    @Override
    public AjaxResult updateApi(ApiKeyUpdateVo vo) {

        System.out.println("入参："+vo);
        String user = SecurityUtils.getUsername();
        if(StringUtils.isNotBlank(vo.getPerms())){
            if(!vo.getPerms().equals(StringUtils.clean(vo.getPerms()))){
                return AjaxResult.error("权限传参错误");
            }
        }else {
            return AjaxResult.error("权限传参不能为空");
        }


        //todo 判断ip
        if(StringUtils.isBlank(vo.getIp())){
            vo.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            System.out.println("用户未传ip,默认使用本机ip："+vo.getIp());
        }

        //ip字段格式校验
        if(!checkIP(vo.getIp())){
            //不是ip报错
            return AjaxResult.error("IP格式错误");
        }

        //todo 判断perms传参
        List<String> perms = Arrays.asList(vo.getPerms().split(",").clone());
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }

        UserApi userApi = uaMapper.getAPIInfoByUserAndId(vo.getId(), user);
        if(StringUtils.isNull(userApi)){
            return AjaxResult.error("id未找到");
        }
        OpenApiKeyInfo info = openApiService.getOpenApiKeyInfo(userApi.getKey());
        System.out.println("info:"+info);
        boolean result = uaMapper.updateApiKey(vo,user);


        if(result){
            info.setApiIp(vo.getIp());
            info.setPermissions(permsSet);
            openApiService.refreshApiKey(info);
            return AjaxResult.success("修改成功");
        }else {
            result = uaMapper.updateApiKey(vo,user);

            if(result){
                info.setApiIp(vo.getIp());
                info.setPermissions(permsSet);
                openApiService.refreshApiKey(info);
                return AjaxResult.success("修改成功");
            }else {
                return AjaxResult.error("当前接口请求过多,请稍后再试");
            }
        }
    }

    @Override
    public AjaxResult deleteApi(ApiKeyDelVo vo) {
        String email = SecurityUtils.getUsername();
        if(StringUtils.isNull(email)){
            return AjaxResult.error("token解析异常");
        }

        List<String> ids = Arrays.asList(StringUtils.clean(vo.getIds()).split(","));

        if(ids.size() < 1){
            return AjaxResult.error("id不能为空");
        }

        List<UserApi> list = uaMapper.getAPIListByUser(email);
        if(list.size() < 0){
            return AjaxResult.error("id不存在");
        }

        List<String> apiIds = list.stream().map(e -> {return  Convert.toStr(e.getId());}).collect(Collectors.toList());

        if(apiIds.containsAll(ids)){
            //执行删除
            try {
                uaMapper.batchDeleteAPIByIdsAndUser(ids, email);
                list.stream().forEach(e ->{
                    if(ids.contains(Convert.toStr(e.getId()))){
                        openApiService.delOpenApiKey(e.getKey());
                    }
                });

                //redis删除api_key相关
                return AjaxResult.success("删除成功");
            }catch (Exception e){
                return AjaxResult.error("网络异常,请稍后再试");
            }

        }else {
            StringBuilder msg = new StringBuilder();
            msg.append("当前用户下不存在对应key:");
            ids.stream().forEach(id -> {
                if(!apiIds.contains(id)){
                    msg.append(id+"\n");
                }
            });
            return AjaxResult.error(msg.toString());
        }
    }


    public boolean checkIP(String ip){
        if(StringUtils.isBlank(ip)){
            return false;
        }
        boolean iPv4Result = IPAddressUtil.isIPv4LiteralAddress(ip);
        boolean iPv6Result = IPAddressUtil.isIPv6LiteralAddress(ip);
        if(iPv4Result || iPv6Result){
            return true;
        }else{
            return false;
        }
    }


}
