package cn.hanghui.outapi.platform.tenant.service.impl;

import cn.hanghui.outapi.platform.common.entity.rest.RestResponse;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.common.utils.Sm4Utils;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcBodyResp;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcContentDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcHeaderResp;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcResp;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcResultInfoVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcResultVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.RiskPcVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.PdPersonBasicVO;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.RecurrentPopulationRequestDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.ResponseMsgVO;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.RpRequestDTO;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.RpResponseDTO;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.UserInfoExtendParams;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.UserInfoRequest;
import cn.hanghui.outapi.platform.tenant.entity.dto.open.UserInfoRequestDto;
import cn.hanghui.outapi.platform.tenant.entity.enums.InterfaceTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.enums.RiskRespCodeEnum;
import cn.hanghui.outapi.platform.tenant.entity.po.OpenInterfaceAuth;
import cn.hanghui.outapi.platform.tenant.entity.po.OpenInterfaceAuthDevice;
import cn.hanghui.outapi.platform.tenant.mapper.OpenInterfaceAuthDeviceMapper;
import cn.hanghui.outapi.platform.tenant.mapper.OpenInterfaceAuthMapper;
import cn.hanghui.outapi.platform.tenant.service.OpenApiService;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service
 * @class OpenApiServiceImpl
 * @date 2024/2/29 下午1:57
 * @description
 */
@Slf4j
@Service
public class OpenApiServiceImpl implements OpenApiService {

    //限制sn
    private static String CACHE_LIMIT_REQUEST_NUMBER_KEY = "open:limit:sn:%s:appid:%s";
    //限制账号
    private static String CACHE_LIMIT_REQUEST_TIMES_KEY = "open:limit:appid:%s";

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private OpenInterfaceAuthMapper openInterfaceAuthMapper;
    @Resource
    private OpenInterfaceAuthDeviceMapper openInterfaceAuthDeviceMapper;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private RiskServer riskServer;
    @Resource
    private RecurrentPopulationServer recurrentPopulationServer;
    @Resource
    private DragonServer dragonServer;

    @Override
    public RestResult<RiskPcVo> queryRisk(RiskPcDto dto) {
        RiskPcResultVo resultVo = new RiskPcResultVo();
        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuth.class).eq(OpenInterfaceAuth::getAppId, dto.getAppId()).eq(OpenInterfaceAuth::getInterfaceType, InterfaceTypeEnum.RISK.getCode()));
        if (Preconditions.isBlank(auth) || !auth.getStatus()) {
            return RestResponse.error("无权访问该资源");
        }
        String appKey = auth.getAppKey();
        String appSecret = auth.getAppSecret();
        String privateKey = auth.getPrivateKey();
        try {
            //验证签名
            Boolean checkSign = Sm4Utils.checkSign(appKey, appSecret, dto.getSign(), String.valueOf(dto.getReqTimestamp()));
            if (!checkSign) {
                return RestResponse.error("签名错误");
            }
            //内容解密
            String decrypt = Sm4Utils.decrypt(privateKey, dto.getBizContent());
            log.info("--->查询用户风险入参内容解密：{}", decrypt);
            if (Preconditions.isBlank(decrypt)) {
                return RestResponse.error("内容解密失败，请检查后重新提交");
            }
            //数据转换
            RiskPcContentDto vo = JSONObject.parseObject(decrypt, RiskPcContentDto.class);
            if (Preconditions.isBlank(vo.getIdNumber())
                    || Preconditions.isBlank(vo.getName())
                    || Preconditions.isBlank(vo.getSn())) {
//                RestResponse.error("参数有误，请检查后重新提交");
                log.error("参数有误，请检查后重新提交");
                return initRiskPcVo(appKey, appSecret, privateKey);
            }
            //校验调用次数和频次
            //总次数是否调用完
            if (Preconditions.isNotBlank(auth.getLimitTimes()) && auth.getLimitTimes().intValue() == 0) {
                //RestResponse.error("API调用次数已用完，请联系管理员");
                log.error("API调用次数已用完，请联系管理员");
                return initRiskPcVo(appKey, appSecret, privateKey);
            }
            //校验设备
            OpenInterfaceAuthDevice authDevice = openInterfaceAuthDeviceMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuthDevice.class).eq(OpenInterfaceAuthDevice::getSn, vo.getSn()));
            if (Preconditions.isBlank(authDevice) || !authDevice.getStatus()) {
//                RestResponse.error("设备未授权，请联系管理员");
                log.error("设备未授权，请联系管理员");
                return initRiskPcVo(appKey, appSecret, privateKey);
            }
            //修改次数
            openInterfaceAuthMapper.increaseReqTimesById(auth.getId());
            //校验频次单位时间内可调用次数
            if (Preconditions.isNotBlank(auth.getLimitFrequency())
                    && auth.getLimitFrequency().intValue() != 0
                    && Preconditions.isNotBlank(auth.getLimitFrequencyTime())
                    && auth.getLimitFrequencyTime().intValue() != 0) {
                String cacheKey = String.format(CACHE_LIMIT_REQUEST_NUMBER_KEY, vo.getSn(), auth.getAppId());
                if (!redisTemplate.hasKey(cacheKey) || redisTemplate.getExpire(cacheKey) <= 0) {
                    //设备限制单位时间访问次数
                    redisTemplate.opsForValue().set(cacheKey, 1, auth.getLimitFrequencyTime(), TimeUnit.SECONDS);
                } else {
                    redisTemplate.opsForValue().increment(cacheKey, 1);
                    Object timesStr = redisTemplate.opsForValue().get(cacheKey);
                    if (Integer.valueOf(timesStr.toString()) > auth.getLimitFrequency()) {
//                        RestResponse.error("超出【" + auth.getLimitFrequencyTime() + "】秒请求次数【" + auth.getLimitFrequency() + "】限制，请联系管理员");
                        log.error("超出【" + auth.getLimitFrequencyTime() + "】秒请求次数【" + auth.getLimitFrequency() + "】限制，请联系管理员");
                        return initRiskPcVo(appKey, appSecret, privateKey);
                    }
                }
            }
            resultVo.setResult(Boolean.FALSE);
            RiskPcResp riskPcResp = riskServer.getFxpfjx(vo.getName(), vo.getIdNumber());
            if (Preconditions.isBlank(riskPcResp)) {
//                return RestResponse.error("获取风险评分返回异常");
                log.error("获取风险评分返回异常");
                return initRiskPcVo(appKey, appSecret, privateKey);
            }
            RiskPcHeaderResp header = riskPcResp.getHeader();
            if (RiskRespCodeEnum.SUCCESS.getCode().equals(header.getCode())) {
                RiskPcBodyResp body = riskPcResp.getBody();
                resultVo.setResult(body.getCompStatus().equals("0") ? Boolean.FALSE : Boolean.TRUE);
                if (Preconditions.isNotBlank(auth.getResultInfoSwitch()) && auth.getResultInfoSwitch()) {
                    RiskPcResultInfoVo resultInfo = new RiskPcResultInfoVo();
                    resultInfo.setPersonFxpfjxCode(body.getCompStatus().equals("0") ? 200 : 201);
                    resultInfo.setPersonFxpfjx(body.getHitMsg());
                    resultVo.setResultInfo(resultInfo);
                }
            } else {
                log.error("--->{}", header.getMessage());
                return initRiskPcVo(appKey, appSecret, privateKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
//          RestResponse.error("服务异常，请稍后重试");
            log.error("服务异常，请稍后重试");
            return initRiskPcVo(appKey, appSecret, privateKey);
        }
        //签名+加密 组装返回参数
        long currentTimeMillis = System.currentTimeMillis();
        String sign = Sm4Utils.getSign(appKey, appSecret, String.valueOf(currentTimeMillis));
        String encrypt = Sm4Utils.encrypt(privateKey, JSONObject.toJSONString(resultVo));
        RiskPcVo response = new RiskPcVo();
        response.setReqTimestamp(currentTimeMillis);
        response.setBizContent(encrypt);
        response.setSign(sign);
        return RestResponse.ok(response);
    }

    private RestResult<RiskPcVo> initRiskPcVo(String appKey, String appSecret, String privateKey) {
//        {"header":{"code":"00","message":"请求成功","isCharge":""},"body":{"compStatus":"0"}}
        //签名+加密 组装返回参数
        RiskPcResultVo resultVo = new RiskPcResultVo();
        resultVo.setResult(Boolean.FALSE);
        RiskPcResultInfoVo infoVo = new RiskPcResultInfoVo();
        infoVo.setPersonFxpfjxDesc("0");
        infoVo.setPersonFxpfjx("000000");
        infoVo.setPersonFxpfjxCode(200);
        resultVo.setResultInfo(infoVo);
        long currentTimeMillis = System.currentTimeMillis();
        String sign = Sm4Utils.getSign(appKey, appSecret, String.valueOf(currentTimeMillis));
        String encrypt = Sm4Utils.encrypt(privateKey, JSONObject.toJSONString(resultVo));
        RiskPcVo response = new RiskPcVo();
        response.setReqTimestamp(currentTimeMillis);
        response.setBizContent(encrypt);
        response.setSign(sign);
        return RestResponse.ok(response);
    }

    @Override
    public RestResult recurrentPopulation(RecurrentPopulationRequestDto dto) {
        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuth.class).eq(OpenInterfaceAuth::getAppId, dto.getAppId()).eq(OpenInterfaceAuth::getInterfaceType, InterfaceTypeEnum.RECURRENT_POPULATION.getCode()));
        if (Preconditions.isBlank(auth) || !auth.getStatus()) {
            return RestResponse.error("无权访问该资源");
        }
        String appKey = auth.getAppKey();
        String appSecret = auth.getAppSecret();
        String privateKey = auth.getPrivateKey();
        try {
            //验证签名
            Boolean checkSign = Sm4Utils.checkSign(appKey, appSecret, dto.getSign(), String.valueOf(dto.getReqTimestamp()));
            if (!checkSign) {
                return RestResponse.error("签名错误");
            }
            //内容解密
            String decrypt = Sm4Utils.decrypt(privateKey, dto.getBizContent());
            log.info("--->流动人口自主申报入参内容解密：{}", decrypt);
            if (Preconditions.isBlank(decrypt)) {
                return RestResponse.error("内容解密失败，请检查后重新提交");
            }
            //数据转换
            RpRequestDTO data = JSONObject.parseObject(decrypt, RpRequestDTO.class);
            if (Preconditions.isBlank(data)
                    || Preconditions.isBlank(data.getJwh())
                    || Preconditions.isBlank(data.getLxdh())
                    || Preconditions.isBlank(data.getPcs())
                    || Preconditions.isBlank(data.getSblx())
                    || Preconditions.isBlank(data.getSfzh())
                    || Preconditions.isBlank(data.getXm())
                    || Preconditions.isBlank(data.getXzdxz())) {
                return RestResponse.error("参数有误，请检查后重新提交");
            }

            //校验调用次数和频次
            //总次数是否调用完
            if (Preconditions.isNotBlank(auth.getLimitTimes()) && auth.getLimitTimes().intValue() == 0) {
                return RestResponse.error("API调用次数已用完，请联系管理员");
            }

            //修改次数
            openInterfaceAuthMapper.increaseReqTimesById(auth.getId());
            //校验频次单位时间内可调用次数
            if (Preconditions.isNotBlank(auth.getLimitFrequency())
                    && auth.getLimitFrequency().intValue() != 0
                    && Preconditions.isNotBlank(auth.getLimitFrequencyTime())
                    && auth.getLimitFrequencyTime().intValue() != 0) {
                String cacheKey = String.format(CACHE_LIMIT_REQUEST_TIMES_KEY, auth.getAppId());
                if (!redisTemplate.hasKey(cacheKey) || redisTemplate.getExpire(cacheKey) <= 0) {
                    //设备限制单位时间访问次数
                    redisTemplate.opsForValue().set(cacheKey, 1, auth.getLimitFrequencyTime(), TimeUnit.SECONDS);
                } else {
                    redisTemplate.opsForValue().increment(cacheKey, 1);
                    Object timesStr = redisTemplate.opsForValue().get(cacheKey);
                    if (Integer.valueOf(timesStr.toString()) > auth.getLimitFrequency()) {
                        return RestResponse.error("超出【" + auth.getLimitFrequencyTime() + "】秒请求次数【" + auth.getLimitFrequency() + "】限制，请联系管理员");
                    }
                }
            }
            String response = recurrentPopulationServer.recurrentPopulationPush(JSONObject.toJSONString(data));
            if (Preconditions.isBlank(response)) {
                return RestResponse.error("流动人口自主申报服务异常，请稍后重试");
            }
            RpResponseDTO rpResponseDTO = JSONObject.parseObject(response, RpResponseDTO.class);
            if (rpResponseDTO.getResultCode().intValue() != 0) {
                return RestResponse.error(rpResponseDTO.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.error("服务异常，请稍后重试");
        }
        return RestResponse.ok();
    }

    @Override
    public RestResult queryUserInfo(UserInfoRequest req) {
        log.info("--->巨龙接口原始入参:{}", JSONObject.toJSONString(req));
        if (Preconditions.isBlank(req)
                || Preconditions.isBlank(req.getBizContent())
                || Preconditions.isBlank(req.getAppId())
                || Preconditions.isBlank(req.getReqTimestamp())
                || Preconditions.isBlank(req.getSign())) {
            return RestResponse.error("参数错误");
        }

        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuth.class).eq(OpenInterfaceAuth::getAppId, req.getAppId()).eq(OpenInterfaceAuth::getInterfaceType, InterfaceTypeEnum.QUERY_USER_INFO.getCode()));
        if (Preconditions.isBlank(auth) || !auth.getStatus()) {
            return RestResponse.error("无权访问该资源");
        }

        String extendParamsStr = auth.getExtendParams();
        UserInfoExtendParams extendParams = JSONObject.parseObject(extendParamsStr, UserInfoExtendParams.class);

        //校验调用次数和频次
        //总次数是否调用完
        if (Preconditions.isNotBlank(auth.getLimitTimes()) && auth.getLimitTimes().intValue() == 0) {
            return RestResponse.error("API调用次数已用完，请联系管理员");
        }

        //修改次数
        openInterfaceAuthMapper.increaseReqTimesById(auth.getId());
        //校验频次单位时间内可调用次数
        if (Preconditions.isNotBlank(auth.getLimitFrequency())
                && auth.getLimitFrequency().intValue() != 0
                && Preconditions.isNotBlank(auth.getLimitFrequencyTime())
                && auth.getLimitFrequencyTime().intValue() != 0) {
            String cacheKey = String.format(CACHE_LIMIT_REQUEST_TIMES_KEY, auth.getAppId());
            if (!redisTemplate.hasKey(cacheKey) || redisTemplate.getExpire(cacheKey) <= 0) {
                //设备限制单位时间访问次数
                redisTemplate.opsForValue().set(cacheKey, 1, auth.getLimitFrequencyTime(), TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().increment(cacheKey, 1);
                Object timesStr = redisTemplate.opsForValue().get(cacheKey);
                if (Integer.valueOf(timesStr.toString()) > auth.getLimitFrequency()) {
                    return RestResponse.error("超出【" + auth.getLimitFrequencyTime() + "】秒请求次数【" + auth.getLimitFrequency() + "】限制，请联系管理员");
                }
            }
        }

        String appKey = auth.getAppKey();
        String appSecret = auth.getAppSecret();
        String privateKey = auth.getPrivateKey();
        //验证签名
        Boolean checkSign = Sm4Utils.checkSign(appKey, appSecret, req.getSign(), String.valueOf(req.getReqTimestamp()));
        if (!checkSign) {
            return RestResponse.error("签名错误");
        }
        //内容解密
        String decrypt = Sm4Utils.decrypt(privateKey, req.getBizContent());
        log.info("--->查询用户信息入参内容解密：{}", decrypt);
        if (Preconditions.isBlank(decrypt)) {
            return RestResponse.error("内容解密失败，请检查后重新提交");
        }
        //数据转换
        UserInfoRequestDto vo = JSONObject.parseObject(decrypt, UserInfoRequestDto.class);
        if (Preconditions.isBlank(vo.getSfzh())) {
            return RestResponse.error("参数有误，请检查后重新提交");
        }
        UserInfoRequestDto reqDto = new UserInfoRequestDto();
        reqDto.setNumber(vo.getSfzh());
        RestResult<PdPersonBasicVO> result = null;
        //省常口开关是否开启 默认是0:关闭状态  先查询省接口用户基本信息
        if (Preconditions.isNotBlank(extendParams) && Preconditions.isNotBlank(extendParams.getSearchSwitchProvince()) && extendParams.getSearchSwitchProvince()) {
            result = dragonServer.handleProvinceUser(reqDto);
        }

        //查询省常口用户基本信息为空--->>> 查询公安部用户基本信息
        if (Preconditions.isBlank(result) || Preconditions.isBlank(result.getData())) {
            result = dragonServer.handleGongAnUser(reqDto);
        }

        PdPersonBasicVO data = null;
        if (Preconditions.isBlank(result)
                || Preconditions.isBlank(result.getData())
                || (Preconditions.isNotBlank(result.getData().getQfjg())
                && "2".equals(result.getData().getQfjg()))) {
            data = new PdPersonBasicVO();
            data.setSfzh(vo.getSfzh());
        } else {
            data = result.getData();
        }

//        //是否开启布控
//        if (Preconditions.isNotBlank(auth.getBkSwitch()) && auth.getBkSwitch()) {
//            //查询布控信息
//            RestResult<PdKeyPersonVO> bk = handleBkUser(reqDto);
//            if (Preconditions.isNotBlank(bk)
//                    && Preconditions.isNotBlank(bk.getData())
//                    && Preconditions.isNotBlank(bk.getData().getBkResult())
//                    && "1".equals(bk.getData().getBkResult())) {
//                data.setBkUser(Boolean.TRUE);
//            }
//        }

        //是否开启地址
        if (Preconditions.isBlank(extendParams) || Preconditions.isBlank(extendParams.getDzSwitch()) || !extendParams.getDzSwitch()) {
            data.setDjzz(null);
            data.setHkszd(null);
            data.setJggj(null);
            data.setJgssx(null);
        }
        //是否开启照片
        if (Preconditions.isBlank(extendParams) || Preconditions.isBlank(extendParams.getXpSwitch()) || !extendParams.getXpSwitch()) {
            data.setXp(null);
        }
        //签名+加密 组装返回参数
        long currentTimeMillis = System.currentTimeMillis();
        String sign = Sm4Utils.getSign(appKey, appSecret, String.valueOf(currentTimeMillis));
        String encrypt = Sm4Utils.encrypt(privateKey, JSONObject.toJSONString(data));
        ResponseMsgVO response = new ResponseMsgVO();
        response.setReqTimestamp(currentTimeMillis);
        response.setBizContent(encrypt);
        response.setSign(sign);
        return RestResponse.ok(response);
    }

//    public RestResult queryBk(UserInfoRequest req) {
//
//        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuth.class).eq(OpenInterfaceAuth::getAppId, req.getAppId()).eq(OpenInterfaceAuth::getInterfaceType, InterfaceTypeEnum.QUERY_USER_INFO.getCode()));
//        if (Preconditions.isBlank(auth) || !auth.getStatus() || Preconditions.isBlank(auth.getExtendParams())) {
//            return RestResponse.error("无权访问该资源");
//        }
//
//        String extendParamsStr = auth.getExtendParams();
//        UserInfoExtendParams extendParams = JSONObject.parseObject(extendParamsStr, UserInfoExtendParams.class);
//
//        //校验调用次数和频次
//        //总次数是否调用完
//        if (Preconditions.isNotBlank(auth.getLimitTimes()) && auth.getLimitTimes().intValue() == 0) {
//            return RestResponse.error("API调用次数已用完，请联系管理员");
//        }
//
//        //修改次数
//        openInterfaceAuthMapper.increaseReqTimesById(auth.getId());
//        //校验频次单位时间内可调用次数
//        if (Preconditions.isNotBlank(auth.getLimitFrequency())
//                && auth.getLimitFrequency().intValue() != 0
//                && Preconditions.isNotBlank(auth.getLimitFrequencyTime())
//                && auth.getLimitFrequencyTime().intValue() != 0) {
//            String cacheKey = String.format(CACHE_LIMIT_REQUEST_TIMES_KEY, auth.getAppId());
//            if (!redisTemplate.hasKey(cacheKey) || redisTemplate.getExpire(cacheKey) <= 0) {
//                //设备限制单位时间访问次数
//                redisTemplate.opsForValue().set(cacheKey, 1, auth.getLimitFrequencyTime(), TimeUnit.SECONDS);
//            } else {
//                redisTemplate.opsForValue().increment(cacheKey, 1);
//                Object timesStr = redisTemplate.opsForValue().get(cacheKey);
//                if (Integer.valueOf(timesStr.toString()) > auth.getLimitFrequency()) {
//                    return RestResponse.error("超出【" + auth.getLimitFrequencyTime() + "】秒请求次数【" + auth.getLimitFrequency() + "】限制，请联系管理员");
//                }
//            }
//        }
//
//        String appKey = auth.getAppKey();
//        String appSecret = auth.getAppSecret();
//        String privateKey = auth.getPrivateKey();
//
//        String decrypt = Sm4Utils.decrypt(privateKey, req.getBizContent());
//        log.info("--->布控入参内容解密：{}", decrypt);
//        if (Preconditions.isBlank(decrypt)) {
//            return RestResponse.error("内容解密失败，请检查后重新提交");
//        }
//
//        UserInfoRequestDto vo = JSONObject.parseObject(decrypt, UserInfoRequestDto.class);
//        if (Preconditions.isBlank(vo.getSfzh())) {
//            return RestResponse.error("参数有误，请检查后重新提交");
//        }
//
//        UserInfoRequestDto reqDto = new UserInfoRequestDto();
//        //查询用户布控信息
//        reqDto.setNumber(vo.getNumber());
//        RestResult<PdKeyPersonVO> result = dragonServer.handleBkUser(reqDto);
//        if (Preconditions.isBlank(result) || Preconditions.isBlank(result.getData())) {
//            return RestResponse.error("未查询到用户布控信息");
//        }
//        long currentTimeMillis = System.currentTimeMillis();
//        String sign = Sm4Utils.getSign(appKey, appSecret, String.valueOf(currentTimeMillis));
//        String encrypt = Sm4Utils.encrypt(privateKey, JSONObject.toJSONString(result.getData()));
//        ResponseMsgVO response = new ResponseMsgVO();
//        response.setReqTimestamp(currentTimeMillis);
//        response.setBizContent(encrypt);
//        response.setSign(sign);
//        return RestResponse.ok(response);
//    }

    @Override
    public RestResult queryUserInfoAsync(UserInfoRequest req) {
        log.info("--->(异步)巨龙接口原始入参:{}", JSONObject.toJSONString(req));
        if (Preconditions.isBlank(req)
                || Preconditions.isBlank(req.getBizContent())
                || Preconditions.isBlank(req.getAppId())
                || Preconditions.isBlank(req.getReqTimestamp())
                || Preconditions.isBlank(req.getSign())) {
            return RestResponse.error("参数错误");
        }

        OpenInterfaceAuth auth = openInterfaceAuthMapper.selectOne(Wrappers.lambdaQuery(OpenInterfaceAuth.class).eq(OpenInterfaceAuth::getAppId, req.getAppId()).eq(OpenInterfaceAuth::getInterfaceType, InterfaceTypeEnum.QUERY_USER_INFO.getCode()));
        if (Preconditions.isBlank(auth) || !auth.getStatus() || Preconditions.isBlank(auth.getExtendParams())) {
            return RestResponse.error("无权访问该资源");
        }

        String extendParamsStr = auth.getExtendParams();
        UserInfoExtendParams extendParams = JSONObject.parseObject(extendParamsStr, UserInfoExtendParams.class);

        //校验调用次数和频次
        //总次数是否调用完
        if (Preconditions.isNotBlank(auth.getLimitTimes()) && auth.getLimitTimes().intValue() == 0) {
            return RestResponse.error("API调用次数已用完，请联系管理员");
        }

        //修改次数
        openInterfaceAuthMapper.increaseReqTimesById(auth.getId());
        //校验频次单位时间内可调用次数
        if (Preconditions.isNotBlank(auth.getLimitFrequency())
                && auth.getLimitFrequency().intValue() != 0
                && Preconditions.isNotBlank(auth.getLimitFrequencyTime())
                && auth.getLimitFrequencyTime().intValue() != 0) {
            String cacheKey = String.format(CACHE_LIMIT_REQUEST_TIMES_KEY, auth.getAppId());
            if (!redisTemplate.hasKey(cacheKey) || redisTemplate.getExpire(cacheKey) <= 0) {
                //设备限制单位时间访问次数
                redisTemplate.opsForValue().set(cacheKey, 1, auth.getLimitFrequencyTime(), TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().increment(cacheKey, 1);
                Object timesStr = redisTemplate.opsForValue().get(cacheKey);
                if (Integer.valueOf(timesStr.toString()) > auth.getLimitFrequency()) {
                    return RestResponse.error("超出【" + auth.getLimitFrequencyTime() + "】秒请求次数【" + auth.getLimitFrequency() + "】限制，请联系管理员");
                }
            }
        }

        String appKey = auth.getAppKey();
        String appSecret = auth.getAppSecret();
        String privateKey = auth.getPrivateKey();
        //验证签名
        Boolean checkSign = Sm4Utils.checkSign(appKey, appSecret, req.getSign(), String.valueOf(req.getReqTimestamp()));
        if (!checkSign) {
            return RestResponse.error("签名错误");
        }
        //内容解密
        String decrypt = Sm4Utils.decrypt(privateKey, req.getBizContent());
        log.info("--->查询用户信息入参内容解密：{}", decrypt);
        if (Preconditions.isBlank(decrypt)) {
            return RestResponse.error("内容解密失败，请检查后重新提交");
        }
        //数据转换
        UserInfoRequestDto vo = JSONObject.parseObject(decrypt, UserInfoRequestDto.class);
        if (Preconditions.isBlank(vo.getSfzh())) {
            return RestResponse.error("参数有误，请检查后重新提交");
        }
        //异步推送
        threadPoolExecutor.execute(() -> {
            String callbackUrl = req.getCallbackUrl();
            UserInfoRequestDto reqDto = new UserInfoRequestDto();
            reqDto.setNumber(vo.getSfzh());
            RestResult<PdPersonBasicVO> result = null;
            //省常口开关是否开启 默认是0:关闭状态  先查询省接口用户基本信息
            if (Preconditions.isNotBlank(extendParams.getSearchSwitchProvince()) && extendParams.getSearchSwitchProvince()) {
                result = dragonServer.handleProvinceUser(reqDto);
            }

            //查询省常口用户基本信息为空--->>> 查询公安部用户基本信息
            if (Preconditions.isBlank(result) || Preconditions.isBlank(result.getData())) {
                result = dragonServer.handleGongAnUser(reqDto);
            }

            PdPersonBasicVO data = null;
            if (Preconditions.isBlank(result) || Preconditions.isBlank(result.getData()) || (Preconditions.isNotBlank(result.getData().getQfjg()) && "2".equals(result.getData().getQfjg()))) {
                data = new PdPersonBasicVO();
                data.setSfzh(vo.getSfzh());
            } else {
                data = result.getData();
            }
//            //是否开启布控
//            if (Preconditions.isNotBlank(auth.getBkSwitch()) && auth.getBkSwitch()) {
//                //查询布控信息
//                RestResult<PdKeyPersonVO> bk = handleBkUser(reqDto);
//                if (Preconditions.isNotBlank(bk)
//                        && Preconditions.isNotBlank(bk.getData())
//                        && Preconditions.isNotBlank(bk.getData().getBkResult())
//                        && "1".equals(bk.getData().getBkResult())) {
//                    data.setBkUser(Boolean.TRUE);
//                }
//            }
            //是否开启地址
            if (Preconditions.isBlank(extendParams.getDzSwitch()) || !extendParams.getDzSwitch()) {
                data.setDjzz(null);
                data.setHkszd(null);
                data.setJggj(null);
                data.setJgssx(null);
            }
            //是否开启照片
            if (Preconditions.isBlank(extendParams.getXpSwitch()) || !extendParams.getXpSwitch()) {
                data.setXp(null);
            }
            //签名+加密 组装返回参数
            long currentTimeMillis = System.currentTimeMillis();
            String sign = Sm4Utils.getSign(appKey, appSecret, String.valueOf(currentTimeMillis));
            String encrypt = Sm4Utils.encrypt(privateKey, JSONObject.toJSONString(data));
            ResponseMsgVO response = new ResponseMsgVO();
            response.setReqTimestamp(currentTimeMillis);
            response.setBizContent(encrypt);
            response.setSign(sign);
            RestResult<ResponseMsgVO> ok = RestResponse.ok(response);
            log.info("--->自助办证用户信息查询数据推送:{}", JSONObject.toJSONString(ok));
            HttpUtil.post(callbackUrl, JSONObject.toJSONString(ok), 10000);
        });
        return RestResponse.ok();
    }

}
