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

import cn.hanghui.outapi.platform.alipay.entity.enums.AlipayCertTypeEnum;
import cn.hanghui.outapi.platform.alipay.entity.param.AlipayUserInfo;
import cn.hanghui.outapi.platform.alipay.entity.po.IotvspUserInfo;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayAmpeSignOpenApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayGroupIdOpenApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayOpenIotvspUserwithimageCreateResponseBody;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayOpenIotvspUserwithimageRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayOpenIotvspUserwithimageResponse;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayOperateRecordCreateWithVidOpenApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayOperateRecordInfoWithVidApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayOrgUserInfoOpenMqRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayUserCreateOpenMqRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayUserDeleteBatchOpenApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayUserDeleteOpenApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayUserDeleteOpenMqRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayUserStateOpenApiRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.request.ZolozCustomerSmileliveInitializeRequest;
import cn.hanghui.outapi.platform.alipay.entity.rest.response.AlipayAmpeSignOpenApiResponse;
import cn.hanghui.outapi.platform.alipay.entity.rest.response.AlipayOperateRecordCreateWithVidOpenApiResponse;
import cn.hanghui.outapi.platform.alipay.mapper.IotDeviceConfigDao;
import cn.hanghui.outapi.platform.alipay.mapper.IotvspUserInfoDao;
import cn.hanghui.outapi.platform.alipay.service.AlipayOpenApiService;
import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.entity.rest.RestResponse;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.exception.CommonException;
import cn.hanghui.outapi.platform.common.service.BaseService;
import cn.hanghui.outapi.platform.common.utils.AppUtils;
import cn.hanghui.outapi.platform.common.utils.ListUtils;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.dto.IotDeviceAppletConfigDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.IotDeviceAppletConfigVo;
import cn.hanghui.outapi.platform.tenant.entity.po.IotDeviceConfig;
import cn.hanghui.outapi.platform.tenant.service.IotDeviceConfigService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenIotvspGroupidQueryRequest;
import com.alipay.api.request.AlipayOpenIotvspUserDeleteRequest;
import com.alipay.api.request.AlipayOpenIotvspUserstateQueryRequest;
import com.alipay.api.request.AlipayOpenIotvspUserwithimageCreateRequest;
import com.alipay.api.request.AlipayOpenIotvspUserwithvidCreateRequest;
import com.alipay.api.request.ZolozAuthenticationCustomerSmileliveInitializeRequest;
import com.alipay.api.response.AlipayOpenIotvspGroupidQueryResponse;
import com.alipay.api.response.AlipayOpenIotvspUserDeleteResponse;
import com.alipay.api.response.AlipayOpenIotvspUserstateQueryResponse;
import com.alipay.api.response.AlipayOpenIotvspUserwithimageCreateResponse;
import com.alipay.api.response.AlipayOpenIotvspUserwithvidCreateResponse;
import com.alipay.api.response.ZolozAuthenticationCustomerSmileliveInitializeResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author shisl
 * @package com.yx.face.service.impl
 * @class AlipayOpenApiServiceImpl
 * @date 2023/5/22 上午11:01
 * @description
 */
@Slf4j
@Service
public class AlipayOpenApiServiceImpl extends BaseService implements AlipayOpenApiService {

    @Resource
    private IotvspUserInfoDao iotvspUserInfoDao;

    @Resource
    private IotDeviceConfigDao iotDeviceConfigDao;
    @Resource
    private IotDeviceConfigService iotDeviceConfigService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public String queryOrgGroupId(AlipayGroupIdOpenApiRequest openApiRequest) {
        log.info("--->查询封闭场景的机构用户库id传递参数：{}", JSONObject.toJSONString(openApiRequest));
        String groupId = null;
        AlipayOpenIotvspGroupidQueryRequest request = new AlipayOpenIotvspGroupidQueryRequest();
        request.setBizContent(JSON.toJSONString(openApiRequest));
        try {
            AlipayClient alipayOpenApiClient = getAlipayClient(openApiRequest.getAppId());
            AlipayOpenIotvspGroupidQueryResponse response = alipayOpenApiClient.execute(request);
            log.info("--->查询封闭场景的机构用户库id响应参数：{}", JSONObject.toJSONString(response));
            if (Objects.nonNull(response) && response.isSuccess() && StringUtils.isNotBlank(response.getGroupId())) {
                groupId = response.getGroupId();
            }
        } catch (Exception e) {
            log.error("查询封闭场景的机构平台异常.", e);
        }
        return groupId;
    }


    @Override
    public AlipayOperateRecordCreateWithVidOpenApiResponse createOperateRecordWithVidV2(AlipayOperateRecordCreateWithVidOpenApiRequest openApiRequest) {
        AlipayOperateRecordCreateWithVidOpenApiResponse resp = new AlipayOperateRecordCreateWithVidOpenApiResponse();
        log.info("--->自定义vid录入机构用户信息获取操作流水id传递参数：{}", JSONObject.toJSONString(openApiRequest));
        //查询用户是否在库
        List<AlipayOperateRecordInfoWithVidApiRequest> userInfoList = openApiRequest.getUserInfoList();
        if (userInfoList == null && userInfoList.size() == 0) {
            log.error("--->自定义vid录入机构用户信息参数错误");
            return resp;
        }
        String vid = userInfoList.get(0).getVid() == null ? DigestUtil.md5Hex(AlipayCertTypeEnum.IDENTITY_CARD.getCode() + openApiRequest.getOrgOutId() + userInfoList.get(0).getCertNo()) : userInfoList.get(0).getVid();
        AlipayUserStateOpenApiRequest userStateRequest = new AlipayUserStateOpenApiRequest();
        userStateRequest.setIsvPid(openApiRequest.getIsvPid());
        userStateRequest.setOrgOutId(openApiRequest.getOrgOutId());
        userStateRequest.setVid(vid);
        userStateRequest.setAppId(openApiRequest.getAppId());
        Boolean existed = queryUserState(userStateRequest);
        if (existed != null && existed) {
            log.error("--->用户{}信息已入库vid:{}", userInfoList.get(0).getCertName(), vid);
            return resp;
        }

        String uniqueId = null;
        AlipayOpenIotvspUserwithvidCreateRequest request = new AlipayOpenIotvspUserwithvidCreateRequest();
        AlipayOperateRecordInfoWithVidApiRequest info = openApiRequest.getUserInfoList().get(0);
        info.setVid(vid);
        openApiRequest.setUserInfoList(Arrays.asList(info));
        request.setBizContent(JSON.toJSONString(openApiRequest));
        try {
            AlipayClient alipayOpenApiClient = getAlipayClient(openApiRequest.getAppId());
            AlipayOpenIotvspUserwithvidCreateResponse response = alipayOpenApiClient.execute(request);
            log.info("--->自定义vid录入机构用户信息获取操作流水id响应参数：{}", JSONObject.toJSONString(response));
            if (Objects.nonNull(response) && response.isSuccess() && StringUtils.isNotBlank(response.getUniqueId())) {
                uniqueId = response.getUniqueId();
                //用户信息执行入库
                handleIotvspUserInfo(openApiRequest, uniqueId);
            } else {
                log.error("--->自定义vid录入机构用户信息入库失败");
            }
        } catch (Exception e) {
            log.error("--->自定义vid录入机构用户信息机构平台异常.", e);
        }
        resp.setUniqueId(uniqueId);
        return resp;
    }

    @Override
    public RestResult createOperateRecordWithoutImage(AlipayOpenIotvspUserwithimageRequest openApiRequest) {
        log.info("--->自定义vid自动直接入库录入机构用户信息入参：{}", JSONObject.toJSONString(openApiRequest));
        //查询用户是否在库
        if (openApiRequest == null || openApiRequest.getCertNo() == null) {
            log.error("--->自定义vid自动录入机构用户信息参数错误");
            return RestResponse.error("参数错误");
        }
        String vid = openApiRequest.getVid() == null ? DigestUtil.md5Hex(AlipayCertTypeEnum.IDENTITY_CARD.getCode() + openApiRequest.getOrgOutId() + openApiRequest.getCertNo()) : openApiRequest.getVid();
        AlipayUserStateOpenApiRequest userStateRequest = new AlipayUserStateOpenApiRequest();
        userStateRequest.setIsvPid(openApiRequest.getIsvPid());
        userStateRequest.setOrgOutId(openApiRequest.getOrgOutId());
        userStateRequest.setAppId(openApiRequest.getAppId());
        userStateRequest.setVid(vid);
        Boolean existed = queryUserState(userStateRequest);
        openApiRequest.setIsvPid(Preconditions.isNotBlank(openApiRequest.getIsvPid()) ? openApiRequest.getIsvPid() : userStateRequest.getAppId());
        openApiRequest.setOrgOutId(Preconditions.isNotBlank(openApiRequest.getOrgOutId()) ? openApiRequest.getOrgOutId() : userStateRequest.getOrgOutId());
        openApiRequest.setComponentOutId(Preconditions.isNotBlank(openApiRequest.getComponentOutId()) ? openApiRequest.getComponentOutId() : getComponentOutId("common"));
        openApiRequest.setAppId(Preconditions.isNotBlank(openApiRequest.getAppId()) ? openApiRequest.getAppId() : userStateRequest.getAppId());
        AlipayOpenIotvspUserwithimageResponse userwithimageResponse = new AlipayOpenIotvspUserwithimageResponse();
        if (existed != null && existed) {
            log.error("--->用户{}信息已入库vid:{}", openApiRequest.getCertName(), vid);
            updateIotvspUserInfoWithimage(openApiRequest);
            userwithimageResponse.setVid(vid);
            return RestResponse.build(RestCode.FAIL.getCode(), "用户信息已入库", userwithimageResponse);
        }
        AlipayOpenIotvspUserwithimageCreateRequest request = new AlipayOpenIotvspUserwithimageCreateRequest();
        openApiRequest.setVid(vid);
        request.setBizContent(JSONObject.toJSONString(openApiRequest));
        try {
            AlipayClient alipayOpenApiClient = getAlipayClient(openApiRequest.getAppId());
            AlipayOpenIotvspUserwithimageCreateResponse response = alipayOpenApiClient.execute(request);
            log.info("--->自定义vid自动录入机构用户信息获取操作流水id响应参数：{}", JSONObject.toJSONString(response));
            if (Objects.nonNull(response) && response.isSuccess()) {
                //用户信息执行入库
                handleIotvspUserInfoWithimage(openApiRequest);
                userwithimageResponse.setVid(response.getVid());
                return RestResponse.ok(userwithimageResponse);
            }

            if (Objects.nonNull(response) && !response.isSuccess()
                    && Objects.nonNull(response.getSubCode())
                    && response.getSubCode().equals("SIMILAR_FACE_EXIST")) {
                //SIMILAR_FACE_EXIST
                AlipayOpenIotvspUserwithimageCreateResponseBody body = JSONObject.parseObject(JSON.toJSONString(JSON.parseObject(response.getBody()).get("alipay_open_iotvsp_userwithimage_create_response")), AlipayOpenIotvspUserwithimageCreateResponseBody.class);
                userwithimageResponse.setVid(response.getVid());
                userwithimageResponse.setSimilarVidList(body.getSimilarVidList());
                return RestResponse.build(RestCode.FAIL.getCode(), response.getSubMsg() != null ? response.getSubMsg() : "用户信息直接入库失败", userwithimageResponse);
            }
            userwithimageResponse.setVid(response.getVid());
            return RestResponse.build(RestCode.FAIL.getCode(), response.getSubMsg() != null ? response.getSubMsg() : "用户信息直接入库失败", userwithimageResponse);
        } catch (Exception e) {
            log.error("--->自定义vid自动录入机构用户信息平台异常.", e);
        }
        return RestResponse.error("用户信息直接入库失败");
    }

    /**
     * 设备端实名入库
     *
     * @param openApiRequest
     * @return
     */
    @Override
    public RestResult createOperateRecordWithverified(AlipayOpenIotvspUserwithimageRequest openApiRequest) {
        log.info("--->自定义vid设备端实名入库入参：{}", JSONObject.toJSONString(openApiRequest));
        //查询用户是否在库
        if (openApiRequest == null || openApiRequest.getCertNo() == null) {
            log.error("--->自定义vid设备端实名入库参数错误");
            return RestResponse.error("参数错误");
        }
        openApiRequest.setCertType(AlipayCertTypeEnum.IDENTITY_CARD.getCode());
        IsvInfo isvInfo = getIsvInfo(openApiRequest.getAppId());
        openApiRequest.setComponentOutId(Preconditions.isNotBlank(openApiRequest.getComponentOutId()) ? openApiRequest.getComponentOutId() : getComponentOutId("verified"));
        openApiRequest.setIsvPid(Preconditions.isNotBlank(openApiRequest.getIsvPid()) ? openApiRequest.getIsvPid() : isvInfo.getIsvPid());
        openApiRequest.setOrgOutId(Preconditions.isNotBlank(openApiRequest.getOrgOutId()) ? openApiRequest.getOrgOutId() : isvInfo.getOrgOutId());
        openApiRequest.setAppId(Preconditions.isNotBlank(openApiRequest.getAppId()) ? openApiRequest.getAppId() : isvInfo.getAppId());
        return createOperateRecordWithoutImage(openApiRequest);
    }

    @Override
    public RestResult createOperateRecordWithanonymous(AlipayOpenIotvspUserwithimageRequest openApiRequest) {
        log.info("--->自定义vid匿名入库入参：{}", JSONObject.toJSONString(openApiRequest));
        //查询用户是否在库
        if (openApiRequest == null || (openApiRequest.getImage() == null && openApiRequest.getFtoken() == null) || openApiRequest.getAppId() == null || openApiRequest.getCertNo() == null) {
            log.error("--->自定义vid匿名入库参数错误");
            return RestResponse.error("参数错误");
        }
        openApiRequest.setCertType(AlipayCertTypeEnum.OTHERS.getCode());
        IsvInfo isvInfo = getIsvInfo(openApiRequest.getAppId());
        openApiRequest.setComponentOutId(Preconditions.isNotBlank(openApiRequest.getComponentOutId()) ? openApiRequest.getComponentOutId() : getComponentOutId("anonymous"));
        openApiRequest.setIsvPid(Preconditions.isNotBlank(openApiRequest.getIsvPid()) ? openApiRequest.getIsvPid() : isvInfo.getIsvPid());
        openApiRequest.setOrgOutId(Preconditions.isNotBlank(openApiRequest.getOrgOutId()) ? openApiRequest.getOrgOutId() : isvInfo.getOrgOutId());
        openApiRequest.setCertNo(openApiRequest.getCertNo());
        openApiRequest.setCertName(openApiRequest.getCertName() == null ? openApiRequest.getCertNo() : openApiRequest.getCertName());
        return createOperateRecordWithoutImage(openApiRequest);
    }

    @Override
    public RestResult createOperateRecordWithverifiedcommon(AlipayOpenIotvspUserwithimageRequest openApiRequest) {
        log.info("--->自定义vid接口实名入库入参：{}", JSONObject.toJSONString(openApiRequest));
        //查询用户是否在库
        if (openApiRequest == null || openApiRequest.getCertNo() == null) {
            log.error("--->自定义vid接口实名入库参数错误");
            return RestResponse.error("参数错误");
        }
        openApiRequest.setCertType(AlipayCertTypeEnum.IDENTITY_CARD.getCode());
        IsvInfo isvInfo = getIsvInfo(openApiRequest.getAppId());
        openApiRequest.setComponentOutId(Preconditions.isNotBlank(openApiRequest.getComponentOutId()) ? openApiRequest.getComponentOutId() : getComponentOutId("common"));
        openApiRequest.setIsvPid(Preconditions.isNotBlank(openApiRequest.getIsvPid()) ? openApiRequest.getIsvPid() : isvInfo.getIsvPid());
        openApiRequest.setOrgOutId(Preconditions.isNotBlank(openApiRequest.getOrgOutId()) ? openApiRequest.getOrgOutId() : isvInfo.getOrgOutId());
        openApiRequest.setAppId(Preconditions.isNotBlank(openApiRequest.getAppId()) ? openApiRequest.getAppId() : isvInfo.getAppId());
        return createOperateRecordWithoutImage(openApiRequest);
    }

    @Override
    public void deleteUserBatch(AlipayUserDeleteBatchOpenApiRequest req) {
        log.error("--->出库参数:{}", JSONObject.toJSONString(req));
        if (req == null || req.getAppId() == null || req.getOrgOutId() == null) {
            return;
        }
        Integer holdDays = req.getHoldDays();
        Date dateTime = DateUtil.offsetDay(new Date(), holdDays != null ? holdDays : 7);
        List<IotvspUserInfo> userInfos = iotvspUserInfoDao.selectList(Wrappers.lambdaQuery(IotvspUserInfo.class)
                .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                .eq(IotvspUserInfo::getOrgOutId, req.getOrgOutId())
                .lt(IotvspUserInfo::getUpdateTime, dateTime));
        if (userInfos == null || userInfos.size() == 0) {
            log.error("--->完成用户库{}出库,出库用户不存在", req.getOrgOutId());
            return;
        }
        log.info("--->用户库{}查询到批量出库用户数:{}个", req.getOrgOutId(), userInfos.size());
        AlipayUserDeleteOpenApiRequest openApiRequest = new AlipayUserDeleteOpenApiRequest();
        openApiRequest.setAppId(req.getAppId());
        openApiRequest.setIsvPid(req.getIsvPid());
        openApiRequest.setOrgOutId(req.getOrgOutId());
        int threadCount = req.getThreadCount() != null ? req.getThreadCount() : 1;
        List<List<IotvspUserInfo>> splits = ListUtils.averageAssign(userInfos, threadCount);
        Integer count = 0;
        for (List<IotvspUserInfo> items : splits) {
            count = count + 1;
            Integer finalCount = count;
            threadPoolExecutor.execute(() -> {
                log.info("--->用户库批量出库线程-{}", finalCount);
                for (IotvspUserInfo userInfo : items) {
                    AlipayOpenIotvspUserDeleteRequest request = new AlipayOpenIotvspUserDeleteRequest();
                    openApiRequest.setVidList(Arrays.asList(userInfo.getVid()));
                    request.setBizContent(JSON.toJSONString(openApiRequest));
                    try {
                        AlipayClient alipayOpenApiClient = getAlipayClient(openApiRequest.getAppId());
                        AlipayOpenIotvspUserDeleteResponse response = alipayOpenApiClient.execute(request);
                        log.info("--->机构用户批量出库响应参数：{}", JSONObject.toJSONString(response));
                        if ("40004".equals(response.getCode()) && "ORG_USER_NOT_EXIST".equals(response.getSubCode())) {
                            //TODO 。。。补偿 人员数据不存在直接删除
                            delIotvspUserInfo(userInfo.getVid(), openApiRequest.getOrgOutId());
                        }
                    } catch (Exception e) {
                        log.error("机构用户批量出库（自定义vid）机构平台异常.", e);
                    }
                }
                log.info("--->完成用户库批量出库线程-{}, 出库用户数:{}个", finalCount, items.size());
            });
        }
    }

    @Override
    public RestResult customerSmileliveInitialize(ZolozCustomerSmileliveInitializeRequest req) {

        //创建API对应的request类
        ZolozAuthenticationCustomerSmileliveInitializeRequest request = new ZolozAuthenticationCustomerSmileliveInitializeRequest();
        // zolozGetMetaInfo接口返回的metainfo对象中加入业务参数
        try {
            //设置业务参数
            JSONObject biz = new JSONObject();
            biz.put("zimmetainfo", URLEncoder.encode(JSONObject.toJSONString(req.getZimMetaInfo()), "utf-8"));
            request.setBizContent(biz.toJSONString());
            //通过alipayClient调用API，获得对应的response类
            AlipayClient alipayOpenApiClient = getAlipayClient(appId5736);
            ZolozAuthenticationCustomerSmileliveInitializeResponse response = alipayOpenApiClient.execute(request);
            log.info("--->刷脸核身Windows-BPaaSFaceSmileLifeVerify响应参数:{}", JSONObject.toJSONString(response));
            if (Objects.nonNull(response) && response.isSuccess()) {
                return RestResponse.ok(JSON.parseObject(response.getResult()));
            } else {
                return RestResponse.error(response.getSubMsg() != null ? response.getSubMsg() : "刷脸核身Windows-BPaaSFaceSmileLifeVerify失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.error("刷脸核身Windows-BPaaSFaceSmileLifeVerify服务异常");
        }
    }

    //用户已入库修改更新时间 防止被删除
    private void updateIotvspUserInfoWithimage(AlipayOpenIotvspUserwithimageRequest openApiRequest) {
        try {
            IotvspUserInfo userInfo = iotvspUserInfoDao.selectOne(Wrappers.lambdaQuery(IotvspUserInfo.class)
                    .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                    .eq(IotvspUserInfo::getOrgOutId, openApiRequest.getOrgOutId())
                    .eq(IotvspUserInfo::getVid, openApiRequest.getVid()));
            if (userInfo == null) {//添加
                return;
            }
            //修改
            userInfo.setVid(openApiRequest.getVid());
            userInfo.setUpdateTime(new Date());
            userInfo.setAvatar(openApiRequest.getImage());
            userInfo.setCertName(openApiRequest.getCertName());
            userInfo.setCertNo(openApiRequest.getCertNo());
            userInfo.setPhone(openApiRequest.getPhone());
            iotvspUserInfoDao.updateById(userInfo);
        } catch (Exception e) {
            log.error("--->本地修改失败");
            throw new CommonException("用户信息本地修改失败");
        }
    }

    // 用户信息自动入库失败
    private void handleIotvspUserInfoWithimage(AlipayOpenIotvspUserwithimageRequest openApiRequest) {
        try {
            IotvspUserInfo userInfo = iotvspUserInfoDao.selectOne(Wrappers.lambdaQuery(IotvspUserInfo.class)
                    .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                    .eq(IotvspUserInfo::getOrgOutId, openApiRequest.getOrgOutId())
                    .eq(IotvspUserInfo::getVid, openApiRequest.getVid()));

            if (userInfo == null) {//添加
                userInfo = new IotvspUserInfo();
                userInfo.setOrgOutId(openApiRequest.getOrgOutId());
                userInfo.setIsvPid(openApiRequest.getIsvPid());
                userInfo.setCreateTime(new Date());
                userInfo.setUpdateTime(new Date());
                userInfo.setVersion(1);
                userInfo.setIsDeleted(Boolean.FALSE);
                userInfo.setState(1);
                userInfo.setMsg("已入库");
                userInfo.setCertType(AlipayCertTypeEnum.IDENTITY_CARD.getCode());
                userInfo.setVid(openApiRequest.getVid());
                userInfo.setAvatar(openApiRequest.getImage());
                userInfo.setCertName(openApiRequest.getCertName());
                userInfo.setCertNo(openApiRequest.getCertNo());
                userInfo.setPhone(openApiRequest.getPhone());
                iotvspUserInfoDao.insert(userInfo);
                return;
            }

            //修改
            userInfo.setIsDeleted(Boolean.FALSE);
            userInfo.setState(1);
            userInfo.setMsg("已入库");
            userInfo.setCertType(AlipayCertTypeEnum.IDENTITY_CARD.getCode());
            userInfo.setUpdateTime(new Date());
            userInfo.setVid(openApiRequest.getVid());
            userInfo.setAvatar(openApiRequest.getImage());
            userInfo.setCertName(openApiRequest.getCertName());
            userInfo.setCertNo(openApiRequest.getCertNo());
            userInfo.setPhone(openApiRequest.getPhone());
            iotvspUserInfoDao.updateById(userInfo);
        } catch (Exception e) {
            log.error("--->本地入库失败");
            throw new CommonException("用户信息本地入库失败");
        }
    }

    @Override
    public AlipayUserInfo getUserInfo(String vid) {
        AlipayUserInfo userInfo = new AlipayUserInfo();
        IotvspUserInfo dbUserInfo = iotvspUserInfoDao.selectOne(Wrappers.lambdaQuery(IotvspUserInfo.class)
                .eq(IotvspUserInfo::getState, 1)
                .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                .eq(IotvspUserInfo::getVid, vid));
        if (dbUserInfo != null) {
            userInfo.setAvatar(dbUserInfo.getAvatar());
            userInfo.setCertNo(dbUserInfo.getCertNo());
            userInfo.setMobile(dbUserInfo.getPhone());
            userInfo.setUserName(dbUserInfo.getCertName());
        }
        return userInfo;
    }

    @Override
    public AlipayUserInfo getUserInfo(String vid, String orgOutId) {
        AlipayUserInfo userInfo = new AlipayUserInfo();
        IotvspUserInfo dbUserInfo = iotvspUserInfoDao.selectOne(Wrappers.lambdaQuery(IotvspUserInfo.class)
                .eq(IotvspUserInfo::getOrgOutId, orgOutId)
                .eq(IotvspUserInfo::getState, 1)
                .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                .eq(IotvspUserInfo::getVid, vid));
        if (dbUserInfo != null) {
            userInfo.setAvatar(dbUserInfo.getAvatar());
            userInfo.setCertNo(dbUserInfo.getCertNo());
            userInfo.setMobile(dbUserInfo.getPhone());
            userInfo.setUserName(dbUserInfo.getCertName());
        }
        return userInfo;
    }

    @Override
    public AlipayAmpeSignOpenApiResponse ampeSign(AlipayAmpeSignOpenApiRequest req) {
        if (req == null || req.getDeviceId() == null) {
            return null;
        }

        IotDeviceConfig device = iotDeviceConfigDao.selectOne(Wrappers.lambdaQuery(IotDeviceConfig.class)
                .eq(IotDeviceConfig::getIsDeleted, Boolean.FALSE)
                .eq(IotDeviceConfig::getSn, req.getDeviceId()));
        if (device == null) {
            return null;
        }
        IotDeviceAppletConfigDto dto = new IotDeviceAppletConfigDto();
        dto.setSn(req.getDeviceId());
        IotDeviceAppletConfigVo configVo = iotDeviceConfigService.snConfig(dto);
        AlipayAmpeSignOpenApiResponse response = new AlipayAmpeSignOpenApiResponse();
        // 其它业务逻辑
        response.setAppId(configVo.getMiniProgramAppid());
        response.setDeviceId(configVo.getSn());
        response.setHostAppId(configVo.getAmpeAppid());
        response.setProductId(configVo.getProductId());
        response.setSignature(configVo.getSignature());
        response.setAppName(configVo.getAppName());
        response.setStartPageUrl(configVo.getStartPageUrl());
        response.setHomePageUrl(configVo.getHomePageUrl());



/*        Long productId = Long.valueOf(config.getProductId()); // 门户设备产品注册得到的productId
        String deviceId = req.getDeviceId(); // 一个产品下的唯一设备识别号,厂商自定义,建议使用SN等设备标识
        String encodeContent = productId + "_" + deviceId;
        try {
            // 获取签名
            String signature = AlipaySignature.rsa256Sign(encodeContent, getKey8PrivateKey(config.getHostAppId()), "UTF-8");
            // 其它业务逻辑
            response.setAppId(config.getAppId());
            response.setDeviceId(deviceId);
            response.setHostAppId(config.getHostAppId());
            response.setProductId(config.getProductId());
            response.setSignature(signature);
            response.setAppName(config.getAppName());


            response.setStartPageUrl(config.getStartPageUrl());
            response.setHomePageUrl(config.getHomePageUrl());
            return response;
        } catch (AlipayApiException e) {
            //
        }*/
        return response;
    }

    private void handleIotvspUserInfo(AlipayOperateRecordCreateWithVidOpenApiRequest openApiRequest, String uniqueId) {
        try {
            AlipayOperateRecordInfoWithVidApiRequest userInfoReq = openApiRequest.getUserInfoList().get(0);
            IotvspUserInfo userInfo = iotvspUserInfoDao.selectOne(Wrappers.lambdaQuery(IotvspUserInfo.class)
                    .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                    .eq(IotvspUserInfo::getOrgOutId, openApiRequest.getOrgOutId())
                    .eq(IotvspUserInfo::getVid, userInfoReq.getVid()));

            if (userInfo == null) {//添加
                userInfo = new IotvspUserInfo();
                userInfo.setOrgOutId(openApiRequest.getOrgOutId());
                userInfo.setIsvPid(openApiRequest.getIsvPid());
                userInfo.setUniqueId(uniqueId);
                userInfo.setCreateTime(new Date());
                userInfo.setUpdateTime(new Date());
                userInfo.setVersion(1);
                userInfo.setIsDeleted(Boolean.FALSE);
                userInfo.setState(0);
                userInfo.setMsg("入库中");
                userInfo.setCertType(AlipayCertTypeEnum.IDENTITY_CARD.getCode());
                userInfo.setVid(userInfoReq.getVid());
                userInfo.setAvatar(userInfoReq.getAvatar());
                userInfo.setCertName(userInfoReq.getCertName());
                userInfo.setCertNo(userInfoReq.getCertNo());
                userInfo.setPhone(userInfoReq.getPhone());
                iotvspUserInfoDao.insert(userInfo);
                return;
            }

            //修改
            userInfo.setIsDeleted(Boolean.FALSE);
            userInfo.setState(0);
            userInfo.setMsg("入库中");
            userInfo.setCertType(AlipayCertTypeEnum.IDENTITY_CARD.getCode());
            userInfo.setUniqueId(uniqueId);
            userInfo.setUpdateTime(new Date());
            userInfo.setVid(userInfoReq.getVid());
            userInfo.setAvatar(userInfoReq.getAvatar());
            userInfo.setCertName(userInfoReq.getCertName());
            userInfo.setCertNo(userInfoReq.getCertNo());
            userInfo.setPhone(userInfoReq.getPhone());
            iotvspUserInfoDao.updateById(userInfo);
        } catch (Exception e) {
            log.error("--->本地入库失败");
        }
    }

    @Override
    public void deleteUser(AlipayUserDeleteOpenApiRequest openApiRequest) {
        log.info("--->机构用户出库请求参数：{}", JSONObject.toJSONString(openApiRequest));
        if (openApiRequest.getVidList() == null || openApiRequest.getVidList().size() == 0) {
            return;
        }

        IsvInfo isvInfo = getIsvInfo(openApiRequest.getAppId());
        openApiRequest.setIsvPid(Preconditions.isNotBlank(openApiRequest.getIsvPid()) ? openApiRequest.getIsvPid() : isvInfo.getIsvPid());
        openApiRequest.setOrgOutId(Preconditions.isNotBlank(openApiRequest.getOrgOutId()) ? openApiRequest.getOrgOutId() : isvInfo.getOrgOutId());
        openApiRequest.setAppId(Preconditions.isNotBlank(openApiRequest.getAppId()) ? openApiRequest.getAppId() : isvInfo.getAppId());
        List<String> vids = openApiRequest.getVidList().stream().distinct().collect(Collectors.toList());
        for (String vid : vids) {
            AlipayOpenIotvspUserDeleteRequest request = new AlipayOpenIotvspUserDeleteRequest();
            openApiRequest.setVidList(Arrays.asList(vid));
            request.setBizContent(JSON.toJSONString(openApiRequest));
            try {
                AlipayClient alipayOpenApiClient = getAlipayClient(openApiRequest.getAppId());
                AlipayOpenIotvspUserDeleteResponse response = alipayOpenApiClient.execute(request);
                log.info("--->机构用户出库响应参数：{}", JSONObject.toJSONString(response));
                if ("40004".equals(response.getCode()) && "ORG_USER_NOT_EXIST".equals(response.getSubCode())) {
                    //TODO 。。。 人员数据不存在直接删除
                    delIotvspUserInfo(vid, openApiRequest.getOrgOutId());
                }
            } catch (Exception e) {
                log.error("机构用户出库（自定义vid）机构平台异常.", e);
            }
        }

    }

    private void delIotvspUserInfo(String vid, String orgOutId) {
        if (vid == null || orgOutId == null) {
            return;
        }
        IotvspUserInfo userInfo = iotvspUserInfoDao.selectOne(Wrappers.lambdaQuery(IotvspUserInfo.class)
                .eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                .eq(IotvspUserInfo::getOrgOutId, orgOutId)
                .eq(IotvspUserInfo::getVid, vid));
        if (userInfo == null) {
            return;
        }
        iotvspUserInfoDao.deleteById(userInfo);
    }

    @Override
    public Boolean queryUserState(AlipayUserStateOpenApiRequest openApiRequest) {
        IsvInfo isvInfo = getIsvInfo(openApiRequest.getAppId());
        openApiRequest.setIsvPid(isvInfo.getIsvPid());
        openApiRequest.setOrgOutId(isvInfo.getOrgOutId());
        openApiRequest.setAppId(isvInfo.getAppId());
        AlipayOpenIotvspUserstateQueryRequest request = new AlipayOpenIotvspUserstateQueryRequest();
        request.setBizContent(JSON.toJSONString(openApiRequest));
        try {
            AlipayClient alipayOpenApiClient = getAlipayClient(openApiRequest.getAppId());
            AlipayOpenIotvspUserstateQueryResponse response = alipayOpenApiClient.execute(request);
            log.info("--->查询机构用户在库结果响应参数：{}", JSONObject.toJSONString(response));
            if (Objects.nonNull(response) && response.isSuccess()) {
                if ("1".equals(response.getState())) {
                    return Boolean.TRUE;
                }
            }
        } catch (Exception e) {
            log.error("查询机构用户在库结果机构平台异常.", e);
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean notifyCreateUserState(AlipayUserCreateOpenMqRequest req) {
        if (req.getUserInfoList() == null || req.getUserInfoList().size() == 0) {
            return Boolean.FALSE;
        }
        log.info("--->notifyCreateUserState执行入库成功或失败处理参数:{}", JSONObject.toJSONString(req));
        String uniqueId = req.getUniqueId();
        String orgOutId = req.getOrgOutId();
        List<AlipayOrgUserInfoOpenMqRequest> userInfoList = req.getUserInfoList();
        List<String> vids = userInfoList.stream().map(AlipayOrgUserInfoOpenMqRequest::getVid).collect(Collectors.toList());
        Map<String, AlipayOrgUserInfoOpenMqRequest> userInfoOpenMqRequestMap = userInfoList.stream().collect(Collectors.toMap(AlipayOrgUserInfoOpenMqRequest::getVid, v -> v, (v1, v2) -> v1));
        List<IotvspUserInfo> dbUserInfos = iotvspUserInfoDao.selectList(Wrappers.lambdaQuery(IotvspUserInfo.class).eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                .eq(IotvspUserInfo::getOrgOutId, orgOutId)
                .eq(IotvspUserInfo::getUniqueId, uniqueId)
                .in(IotvspUserInfo::getVid, vids));
        if (dbUserInfos != null && dbUserInfos.size() > 0) {
            dbUserInfos.stream().forEach(item -> {
                AlipayOrgUserInfoOpenMqRequest userInfoOpenMqRequest = userInfoOpenMqRequestMap.get(item.getVid());
                if (userInfoOpenMqRequest != null) {
                    item.setState(userInfoOpenMqRequest.getState());
                    item.setMsg((userInfoOpenMqRequest.getState() != null && userInfoOpenMqRequest.getState().intValue() == 1) ? "入库成功" : ((userInfoOpenMqRequest.getState() != null && userInfoOpenMqRequest.getState().intValue() == 2) ? "入库失败" : "入库中"));
                    iotvspUserInfoDao.updateById(item);
                }
            });
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean notifyDelUserState(AlipayUserDeleteOpenMqRequest req) {
        if (req.getUserInfoList() == null || req.getUserInfoList().size() == 0) {
            return Boolean.FALSE;
        }
        log.info("--->notifyDelUserState执行出库成功或失败处理参数:{}", JSONObject.toJSONString(req));
        String orgOutId = req.getOrgOutId();
        List<AlipayOrgUserInfoOpenMqRequest> userInfoList = req.getUserInfoList();
        List<String> vids = userInfoList.stream().map(AlipayOrgUserInfoOpenMqRequest::getVid).collect(Collectors.toList());
        Map<String, AlipayOrgUserInfoOpenMqRequest> userInfoOpenMqRequestMap = userInfoList.stream().collect(Collectors.toMap(AlipayOrgUserInfoOpenMqRequest::getVid, v -> v, (v1, v2) -> v1));
        List<IotvspUserInfo> dbUserInfos = iotvspUserInfoDao.selectList(Wrappers.lambdaQuery(IotvspUserInfo.class).eq(IotvspUserInfo::getIsDeleted, Boolean.FALSE)
                .eq(IotvspUserInfo::getOrgOutId, orgOutId)
                .in(IotvspUserInfo::getVid, vids));
        if (dbUserInfos != null && dbUserInfos.size() > 0) {
            dbUserInfos.stream().forEach(item -> {
                AlipayOrgUserInfoOpenMqRequest userInfoOpenMqRequest = userInfoOpenMqRequestMap.get(item.getVid());
                if (userInfoOpenMqRequest != null && userInfoOpenMqRequest.getState() == 1) {
                    iotvspUserInfoDao.deleteById(item);
                }
            });
        }
        return Boolean.TRUE;
    }

    public static void main(String[] args) {
        System.out.println(DigestUtil.md5Hex(AlipayCertTypeEnum.IDENTITY_CARD.getCode() + "xinchengshidaiguangchang" + "430621200304210084"));
    }

}
