package com.fs.qw.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyConfigService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.OptionVO;
import com.fs.config.cloud.CloudHostProper;
import com.fs.his.config.FsSysConfig;
import com.fs.his.utils.ConfigUtil;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwIpadServerLog;
import com.fs.qw.domain.QwIpadServerUser;
import com.fs.qw.domain.QwUser;
import com.fs.qw.dto.QwUserByToolDTO;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.mapper.QwWorkTaskMapper;
import com.fs.qw.param.*;
import com.fs.qw.result.QwFsServerBindResult;
import com.fs.qw.result.QwFsServerIPResult;
import com.fs.qw.service.*;
import com.fs.qw.utils.RSASignatureUtils;
import com.fs.qw.utils.RSAUtils;
import com.fs.qw.vo.*;
import com.fs.qwApi.Result.QwOpenidResult;
import com.fs.qwApi.Result.QwUploadImgResult;
import com.fs.qwApi.domain.QwUserIdResult;
import com.fs.qwApi.domain.inner.DeptUser;
import com.fs.qwApi.param.QwOpenidByUserParams;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import com.fs.wxwork.dto.*;
import com.fs.wxwork.service.WxWorkService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 企微用户Service业务层处理
 *
 * @author fs
 * @date 2024-06-20
 */
@Service
@EnableAsync
public class QwUserServiceImpl implements IQwUserService
{
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(QwUserServiceImpl.class);
    @Autowired
    QwApiService qwApiService;
    @Autowired
    private QwUserMapper qwUserMapper;
    @Autowired
    ICompanyConfigService companyConfigService;

    @Autowired
    IQwCompanyService iQwCompanyService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    CloudHostProper cloudHostProper;
    @Autowired
    private QwWorkTaskMapper qwWorkTaskMapper;
    @Autowired
    WxWorkService wxWorkService;

//    @Value("${hook.path}")
//    private String hookPath;

    /**
     * 查询企微用户
     *
     * @param id 企微用户主键
     * @return 企微用户
     */
    @Override
    public QwUser selectQwUserById(Long id)
    {
        return qwUserMapper.selectQwUserById(id);
    }

    @Override
    public R authAppKey(QwUser param) {
        String appKey;
        QwUser qwUser;
        // 循环生成 appKey，直到找到一个数据库中不存在的 appKey
        do {
            appKey = IdUtil.getSnowflake(0, 0).nextIdStr();
            qwUser = qwUserMapper.selectQwUserByAppKey(appKey);
        } while (qwUser != null); // 如果 appKey 已存在，则重新生成

        QwUser qwUserAppKey = new QwUser();
        qwUserAppKey.setId(param.getId());
        qwUserAppKey.setAppKey(appKey);
        qwUserAppKey.setQwHookId(appKey);
        qwUserMapper.updateQwUser(qwUserAppKey);

        return R.ok();
    }

    @Override
    public R handleInputAuthAppKey(QwUser param) {

        param.setAppKey(param.getAppKey().replaceAll("[^a-zA-Z0-9]", ""));

        QwUser qwUser = qwUserMapper.selectQwUserByAppKey(param.getAppKey());
        if (qwUser == null) {
            QwUser qwUserAppKey = new QwUser();
            qwUserAppKey.setId(param.getId());
            qwUserAppKey.setAppKey(param.getAppKey().trim());
            qwUserAppKey.setQwHookId(param.getAppKey().trim());
            qwUserMapper.updateQwUser(qwUserAppKey);
            return R.ok();
        }else {
         return R.error("当前授权码已被使用，请检查授权码是否正确");
        }
    }


    /**
     * 登录企业微信(获取登录二维码-发起登录)
     */
    @Override
    public R loginQwCode(QwLoginParam loginParam) {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.post(domainName+"/app/qwSop/qwLogin")
               .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
               .execute().body();
//        HttpRequest.post("http://127.0.0.1:7771/app/qwSop/qwLogin")
//                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
//                .execute().body();

        return R.ok();
    }

    @Override
    public R loginQwAll() {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.get(domainName+"/app/qwSop/qwLoginAll").execute().body();
//        HttpRequest.post("http://127.0.0.1:7771/app/qwSop/qwLogin")
//                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
//                .execute().body();

        return R.ok();
    }

    @Override
    public R qwLoginOutAll() {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.get(domainName+"/app/qwSop/qwLoginOutAll").execute().body();
//        HttpRequest.post("http://127.0.0.1:7771/app/qwSop/qwLogin")
//                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
//                .execute().body();

        return R.ok();
    }

    /**
     * 登录请求-刷新获取二维码
     */
    @Override
    public R loginQwCodeUrl(QwLoginParam loginParam) {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.post(domainName+"/app/qwSop/loginQwCodeUrl")
                 .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
                 .execute().body();
//        HttpRequest.post("http://127.0.0.1:7771/app/qwSop/loginQwCodeUrl")
//                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
//                .execute().body();
        return R.ok();
    }

    /**
     * 取某个appkey登录的二维码
     */
    @Override
    public R getQwCodeUrl(QwLoginParam param) throws InterruptedException {
        int maxRetryCount = 10;  // 最大重试次数
        String base64 = null;  // 用于存储缓存的值
        String cacheKey = "QwLoginCode:" + param.getAppKey();  // Redis 缓存的 Key

        // 从缓存中获取数据
        base64 = redisCache.getCacheObject(cacheKey);

        // 如果缓存值为空，尝试重新获取
        if (StringUtil.strIsNullOrEmpty(base64)) {
            for (int i = 0; i < maxRetryCount; i++) {
                try {
                    Thread.sleep(3000); // 等待 3 秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // 恢复中断状态
                    logger.error("线程被中断"+e.getMessage());
                }

                base64 = redisCache.getCacheObject(cacheKey);
                if (!StringUtil.strIsNullOrEmpty(base64)) {
                    break;  // 如果成功获取到值，退出循环
                }
            }
        }

        // 最终检查结果
        if (StringUtil.strIsNullOrEmpty(base64)) {
            return R.error("未获取到当前人的二维码，请重试或检查是否有key");
        } else {
            return R.ok().put("base64",base64);
        }


    }

    /**
     * 登录企业微信(传输验证信息)
     */
    @Override
    public R loginQwCodeMsg(QwLoginParam loginParam) {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.post(domainName+"/app/qwSop/qwLoginInputCode")
                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
                .execute().body();
//        HttpRequest.post("http://127.0.0.1:7771/app/qwSop/qwLoginInputCode")
//                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
//                .execute().body();
        return R.ok();
    }
    /**
     * 退出企业微信(退出插件)
     */
    @Override
    public R logoutQwLogout(QwLoginParam loginParam) {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.post(domainName+"/app/qwSop/qwLoginOut")
                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
                .execute().body();

//        HttpRequest.post("http://127.0.0.1:7771/app/qwSop/qwLoginOut")
//                .body(JSON.toJSONString(loginParam),"application/json;charset=UTF-8")
//                .execute().body();
        return R.ok();
    }


    /**
     * 企业微信(修改登录状态)
     */
    @Override
    public R modifyLoginQwStatus(QwLoginParam loginParam) {

        QwUser qwUser=new QwUser();
        qwUser.setAppKey(loginParam.getAppKey());
        qwUser.setLoginStatus(loginParam.getLoginStatus());

        int i = qwUserMapper.updateQwUser(qwUser);
        if (i>0){
         return R.ok("修改成功");
        }
        return R.error("修改失败");

    }

    @Override
    public R getLoginQwStatus(QwLoginParam loginParam) {

        QwUser qwUser = qwUserMapper.selectQwUserByAppKey(loginParam.getAppKey());
        if (qwUser!=null){

            return R.ok().put("status",qwUser.getLoginStatus());

        }else {
            return R.ok("未查询到当前key的账号");
        }
    }

    /**
    * 根据appKey请求 绑定服务器
    */
    @Override
    public R qwBindCloudHost(String appKey) {

        QwFsServerBindParam qwUserVOS = qwUserMapper.selectQwServerBindParam(appKey);

        if (qwUserVOS==null){
            return R.error("该appkey查不到相关销售信息："+appKey);
        }

        if (StringUtil.strIsNullOrEmpty(qwUserVOS.getValue())){
            return R.error("查询到销售没有设置 所属区域，请先在销售【员工管理】处设置所属区域");
        }

        qwUserVOS.setIsBind(1);
        qwUserVOS.setAppKey(appKey);
        qwUserVOS.setCompany(cloudHostProper.getCompanyName());

        String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                .body(JSON.toJSONString(qwUserVOS), "application/json;charset=UTF-8")
                .execute().body();
//        String body = HttpRequest.post("http://192.168.10.155:8111/server/bind")
//                .body(JSON.toJSONString(qwUserVOS), "application/json;charset=UTF-8")
//                .execute().body();


        if (StringUtil.strIsNullOrEmpty(body)){
            return R.error("请求绑定失败");
        }

        QwFsServerBindResult result = JSON.parseObject(body, QwFsServerBindResult.class);

        if (result.getCode()!=200){
            return  R.error("请求绑定失败："+result.getMsg());
        }

        if (result.getData().flag){
            QwUser qwUser=new QwUser();
            qwUser.setAppKey(appKey);
            qwUser.setLoginCodeUrl(result.getData().ipAddress);

            int i = qwUserMapper.updateQwUserByAppKeyToUrl(qwUser);
            if (i>0){
                return R.ok("请求绑定成功");
            }else {
                //没绑定成功 解绑
                QwFsServerBindParam qwFsServerBindParam=new QwFsServerBindParam();
                qwFsServerBindParam.setIpAddress(result.getData().ipAddress);
                qwFsServerBindParam.setIsBind(0);

                HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                        .body(JSON.toJSONString(qwFsServerBindParam), "application/json;charset=UTF-8")
                        .execute().body();

                return R.error("请求绑定失败");
            }


        }else {
            return R.error("请求绑定失败："+result.getData().msg);
        }

    }

    @Override
    public R selectCloudAP(QwCloudAPParam param) throws Exception {

        String bodyKey = HttpRequest.get("http://watch.ylrzcloud.com/prod-api/server/getKey?serverIp="+param.getIpAddress())
                .execute().body();

//        String bodyKey = HttpRequest.get("http://192.168.10.155:8111/server/getKey?serverIp="+param.getIpAddress())
//                .execute().body();

        QwFsServerBindResult resultDecode = JSON.parseObject(bodyKey, QwFsServerBindResult.class);

        PrivateKey privateKey = getPrivateKeyFromString(resultDecode.getMsg());

        String signature = RSASignatureUtils.sign(param.getIpAddress() + "ylrz321!#@1", privateKey );

        QwCloudAPParamB paramB=new QwCloudAPParamB();
        paramB.setServerIp(param.getIpAddress());
        paramB.setSignature(signature);

        String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/getAccount")
                .body(JSON.toJSONString(paramB), "application/json;charset=UTF-8")
                .execute().body();
//        String body = HttpRequest.post("http://192.168.10.155:8111/server/getAccount")
//                .body(JSON.toJSONString(paramB), "application/json;charset=UTF-8")
//                .execute().body();

        QwFsServerAPResult result = JSON.parseObject(body, QwFsServerAPResult.class);

        if (result.getCode()==200){
            //账号 解密
            String apAdmin = RSAUtils.decrypt(result.getData().serverAccount, privateKey);

            //密码
            String apPassword = RSAUtils.decrypt(result.getData().serverPassword, privateKey);

            QwCloudAPVO apvo=new QwCloudAPVO();
            apvo.setApAdmin(apAdmin);
            apvo.setApPassword(apPassword);

            return  R.ok().put("data",apvo);

        }else {
            return  R.error("获取账号密码失败，请重试！！错误码："+result.getMsg());
        }

    }


    @Override
    public R qwBindCloudHostByIp2(String appKey, String IP, List<String> appkeyList, List<String> appkeyUnNow) {

        QwFsServerBindParam qwUserVOS = qwUserMapper.selectQwServerBindParam(appKey);

        if (qwUserVOS==null){
            logger.error("该appkey查不到销售数据："+appKey+"|"+IP);

            appkeyUnNow.add(appKey);

        }
        else {
            if (StringUtil.strIsNullOrEmpty(qwUserVOS.getValue())){
                logger.error("查询到销售没有设置 所属区域，请先在销售【员工管理】处设置所属区域:"+appKey+"|id:"+IP);
                appkeyList.add(appKey);
            }else {
                qwUserVOS.setIsBind(1);
                qwUserVOS.setAppKey(appKey);
                qwUserVOS.setIpAddress(IP);

                String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                        .body(JSON.toJSONString(qwUserVOS), "application/json;charset=UTF-8")
                        .execute().body();
//        String body = HttpRequest.post("http://192.168.10.155:8111/server/bind")
//                .body(JSON.toJSONString(qwUserVOS), "application/json;charset=UTF-8")
//                .execute().body();


                if (StringUtil.strIsNullOrEmpty(body)){
//                    logger.error("请求绑定失败:"+appKey+"|"+IP);
                }

                QwFsServerBindResult result = JSON.parseObject(body, QwFsServerBindResult.class);

                if (result.getCode()!=200){
//                    logger.error("请求绑定失败："+result.getMsg()+"|"+appKey+"|"+IP);
                }

                if (result.getData().flag){
                    QwUser qwUser=new QwUser();
                    qwUser.setAppKey(appKey);
                    qwUser.setLoginCodeUrl(result.getData().ipAddress);

                    int i = qwUserMapper.updateQwUserByAppKeyToUrl(qwUser);
                    if (i>0){
//                        logger.info("请求绑定成功");
                    }else {
                        //没绑定成功 解绑
                        QwFsServerBindParam qwFsServerBindParam=new QwFsServerBindParam();
                        qwFsServerBindParam.setIpAddress(result.getData().ipAddress);
                        qwFsServerBindParam.setIsBind(0);

                        HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                                .body(JSON.toJSONString(qwFsServerBindParam), "application/json;charset=UTF-8")
                                .execute().body();

//                        logger.error("请求绑定失败"+appKey+"|"+IP);
                    }


                }else {
//                    logger.error("请求绑定失败："+result.getData().msg);
                }
            }

        }

        return R.ok().put("data1",appkeyList).put("data2",appkeyUnNow);
    }

    public static PrivateKey getPrivateKeyFromString(String privateKeyStr) throws Exception {
        byte[] decoded = Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    @Override
    public R qwBindCloudHostByIp(String appKey, String IP) {

        QwFsServerBindParam qwUserVOS = qwUserMapper.selectQwServerBindParam(appKey);


        if (qwUserVOS==null){
            return R.error("该appkey查不到数据："+appKey+"|"+IP);
        }
        else {
            if (StringUtil.strIsNullOrEmpty(qwUserVOS.getValue())){
                return R.error("查询到销售没有设置 所属区域，请先在销售【员工管理】处设置所属区域:"+appKey+"|id:"+IP);
            }else {
                qwUserVOS.setIsBind(1);
                qwUserVOS.setAppKey(appKey);
                qwUserVOS.setIpAddress(IP);

                String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                        .body(JSON.toJSONString(qwUserVOS), "application/json;charset=UTF-8")
                        .execute().body();
//        String body = HttpRequest.post("http://192.168.10.155:8111/server/bind")
//                .body(JSON.toJSONString(qwUserVOS), "application/json;charset=UTF-8")
//                .execute().body();


                if (StringUtil.strIsNullOrEmpty(body)){
                    return R.error("请求绑定失败:"+appKey+"|"+IP);
                }

                QwFsServerBindResult result = JSON.parseObject(body, QwFsServerBindResult.class);

                if (result.getCode()!=200){
                    return R.error("请求绑定失败："+result.getMsg()+"|"+appKey+"|"+IP);
                }

                if (result.getData().flag){
                    QwUser qwUser=new QwUser();
                    qwUser.setAppKey(appKey);
                    qwUser.setLoginCodeUrl(result.getData().ipAddress);

                    int i = qwUserMapper.updateQwUserByAppKeyToUrl(qwUser);
                    if (i>0){
//                        logger.info("请求绑定成功");
                    }else {
                        //没绑定成功 解绑
                        QwFsServerBindParam qwFsServerBindParam=new QwFsServerBindParam();
                        qwFsServerBindParam.setIpAddress(result.getData().ipAddress);
                        qwFsServerBindParam.setIsBind(0);

                        HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                                .body(JSON.toJSONString(qwFsServerBindParam), "application/json;charset=UTF-8")
                                .execute().body();

                        return R.error("请求绑定失败"+appKey+"|"+IP);
                    }


                }else {
                    return R.error("请求绑定失败："+result.getData().msg);
                }
            }

        }

        return R.ok();
    }

    /**
     * 根据appKey请求 解除服务器
     */
    @Override
    public R qwUnbindCloudHost(String appKey) {

        String IP = qwUserMapper.selectQwUserByAppKeyToIP(appKey);

        QwFsServerBindParam qwFsServerBindParam=new QwFsServerBindParam();
        qwFsServerBindParam.setIpAddress(IP);
        qwFsServerBindParam.setIsBind(0);

        String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/bind")
                .body(JSON.toJSONString(qwFsServerBindParam), "application/json;charset=UTF-8")
                .execute().body();

        QwFsServerBindResult result = JSON.parseObject(body, QwFsServerBindResult.class);

        if (result.getCode()!=200){
            return R.error("请求解除绑定失败:"+result.getMsg());
        }

        if (result.getData().flag){
            QwUser qwUser=new QwUser();
            qwUser.setAppKey(appKey);
            qwUser.setLoginCodeUrl(null);

            int i = qwUserMapper.updateQwUserByAppKeyToUrl(qwUser);
            if (i>0){
                return R.ok("解除绑定成功");
            }else {

                QwFsServerBindParam qwUserVOS = qwUserMapper.selectQwServerBindParam(appKey);
                qwUserVOS.setIsBind(1);
                qwUserVOS.setIpAddress(IP);

                return R.error("解除绑定失败");
            }

        }else {
            return R.error("请求绑定失败："+result.getData().msg);
        }

    }

    @Override
    public int updateQwUserByAppKey(QwUser qwUser) {
        return  qwUserMapper.updateQwUserByAppKey(qwUser);
    }

    @Override
    public int updateQwUserByAppKeyTool(QwUser qwUser) {
        return  qwUserMapper.updateQwUserByAppKeyTool(qwUser);
    }

    /**
     * 查询企微用户列表
     *
     * @param qwUser 企微用户
     * @return 企微用户
     */
    @Override
    public List<QwUser> selectQwUserList(QwUser qwUser)
    {
        return qwUserMapper.selectQwUserList(qwUser);
    }

    /**
     * 新增企微用户
     *
     * @param qwUser 企微用户
     * @return 结果
     */
    @Override
    public int insertQwUser(QwUser qwUser)
    {
        return qwUserMapper.insertQwUser(qwUser);
    }

    /**
     * 修改企微用户
     *
     * @param qwUser 企微用户
     * @return 结果
     */
    @Override
    public int updateQwUser(QwUser qwUser)
    {
        return qwUserMapper.updateQwUser(qwUser);
    }

    /**
     * 批量删除企微用户
     *
     * @param ids 需要删除的企微用户主键
     * @return 结果
     */
    @Override
    public int deleteQwUserByIds(Long[] ids)
    {
        return qwUserMapper.deleteQwUserByIds(ids);
    }

    /**
     * 删除企微用户信息
     *
     * @param id 企微用户主键
     * @return 结果
     */
    @Override
    public int deleteQwUserById(Long id)
    {
        QwUser qwUser = new QwUser();
        qwUser.setId(id);
        qwUser.setIsDel(1);
        return qwUserMapper.updateQwUser(qwUser);
    }



    @Override
    public List<QwUserVO> selectQwUserListVO(QwUserListParam qwUser) {
        return qwUserMapper.selectQwUserListVO(qwUser);
    }

    @Override
    public List<QwUserVO> selectQwUserListStaffVO(QwUserListParam qwUser) {
        List<QwUserVO> qwUserVOS = qwUserMapper.selectQwUserListStaffVO(qwUser);
        qwUserVOS.forEach(item->{

            if (!StringUtil.strIsNullOrEmpty(item.getLoginCodeUrl())) {
                QwFsServerBindParam param=new QwFsServerBindParam();
                param.setIpAddress(item.getLoginCodeUrl());

                String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/externalList")
                        .body(JSON.toJSONString(param), "application/json;charset=UTF-8")
                        .execute().body();

                QwFsServerIPResult result = JSON.parseObject(body, QwFsServerIPResult.class);
                if (result.getCode() == 200 && result.getRows().length > 0) {
                    String serverType = result.getRows()[0].getServerType();
                    if (StringUtil.strIsNullOrEmpty(serverType)) {
                        item.setLoginCodeUrl(item.getLoginCodeUrl()+"【老版本】");
                    }else {
                        item.setLoginCodeUrl(item.getLoginCodeUrl()+"【新版本】");
                    }

                }

            }
        });

        return qwUserVOS;
    }

    /**
     *  查询所有企微用户列表
     */
    @Override
    public List<QwUserVO> selectQwUserListBindVO(QwUserParam qwUser) {
        return qwUserMapper.selectQwUserListBindVO(qwUser);
    }

    @Override
    public R syncQwUser(String corpId) {
        QwUserIdResult userList = qwApiService.getUserList(corpId);
        List<DeptUser> deptUser = userList.getDept_user();
        System.out.println("企微部门："+deptUser);
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
        for (DeptUser user : deptUser) {
            QwUser qw=qwUserMapper.selectQwUserByCorpIdAndUserId(corpId,user.getUserid());
            String serverQwUserName = qwApiService.getServerQwUserName(corpId, qwCompany.getOpenSecret(), user.getUserid());
            QwUser qwUser = new QwUser();
            qwUser.setQwUserId(user.getUserid());
            qwUser.setDepartment(user.getDepartment().toString());
            qwUser.setQwUserName(serverQwUserName);
            qwUser.setCorpId(corpId);
            QwOpenidByUserParams param=new QwOpenidByUserParams();
            param.setUserid(user.getUserid());
            QwOpenidResult qwOpenidResult = qwApiService.useridToOpenid(param, corpId);
            System.out.println("企微返回："+qwOpenidResult);
            qwUser.setOpenid(qwOpenidResult.getOpenid());
            if (qw==null){
                qwUserMapper.insertQwUser(qwUser);
            }else {
                System.out.println("不等于空");
                qwUser.setId(qw.getId());
                qwUser.setIsDel(0);
                qwUserMapper.updateQwUser(qwUser);
            }
        }
        return R.ok();
    }


    public R syncQwUserName(String corpId) {
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
        List<QwUser> qwUsers=qwUserMapper.selectQwUserByCorpId(corpId);
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        for (QwUser user : qwUsers) {
            executorService.submit(() -> updateQwUserName(user, qwCompany));
        }
        executorService.shutdown(); // 关闭线程池，等待所有任务完成
        return R.ok();
    }

    @Override
    public void addRedisKey(String id, String key) {
        redisCache.setCacheObject(key,id,10,TimeUnit.SECONDS);
    }

    /**
     * 根据企微用户ID和企微ID查询企微用户记录
     * @param qwUserId  企微用户ID
     * @param corpId    企微ID
     * @return  QwUser
     */
    @Override
    public QwUser getByQwUserIdAndCorId(String qwUserId, String corpId) {
        return qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, qwUserId);
    }

    void updateQwUserName(QwUser user,QwCompany qwCompany){
        String serverQwUserName = qwApiService.getServerQwUserName(qwCompany.getCorpId(), qwCompany.getOpenSecret(), user.getQwUserId());
        if (serverQwUserName==null|| serverQwUserName.isEmpty()){
            return;
        }
        if (serverQwUserName.equals(user.getQwUserName())){
            return;
        }
        QwUser qwUser = new QwUser();
        qwUser.setId(user.getId());
        qwUser.setQwUserName (serverQwUserName);
        qwUserMapper.updateQwUser(qwUser);
    }

    @Override
    public List<QwOptionsVO> selectQwUserListOptionsVO(String corpId) {
        return qwUserMapper.selectQwUserListOptionsVO(corpId);
    }

    /** 修改企微用户的欢迎语 */
    @Override
    public R weclomeQwUser(QwUser qwUser) throws Exception {

        //图片
        String welcomeImage = qwUser.getWelcomeImage(); // 假设这是一个包含逗号分隔地址的字符串
        String[] imageArray = welcomeImage.split(","); // 使用逗号作为分隔符进行拆分
        StringBuilder stringBuilder=new StringBuilder();
        // 现在 imageArray 包含了拆分后的各个图片地址
        for (String image : imageArray) {

//            File file = urlToFile(image);
            QwUploadImgResult uploadimg = qwApiService.uploadimgs(image, qwUser.getCorpId());
            if (uploadimg.getErrcode()!=0){
                return R.error("修改欢迎语失败，图片上传失败:"+uploadimg.getErrMsg());
            }else {

                // 确保不重复添加逗号
                if (stringBuilder.length() > 0) {
                    stringBuilder.append(",");
                }
                stringBuilder.append(uploadimg.getUrl());

            }
//            file.delete();
        }

        // 最终的逗号分隔字符串
        String imageList = stringBuilder.toString();
        qwUser.setWelcomeImage(imageList);

        int i = qwUserMapper.updateQwUser(qwUser);
        if (i>0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @Override
    public void updateUserByUserId(Long companyUserId) {
        qwUserMapper.updateUserByUserId(companyUserId);
    }
    @Override
    public void updateUnBindUserById(String id) {
        qwUserMapper.updateUnBindUserById(id);
    }
    @Override
    public QwUser selectQwUserByQwUserId(String qwUserId) {
        return qwUserMapper.selectQwUserByQwUserId(qwUserId);
    }

    @Override
    public List<QwOptionsVO> selectQwUserListOptionsVOByCompanyUserId(Long userId) {
        return qwUserMapper.selectQwUserListOptionsVOByCompanyUserId(userId);
    }

    @Override
    public QwUser selectQwUserByAppKey(String key) {
        return qwUserMapper.selectQwUserByAppKey(key);
    }

    @Override
    public String selectQwUserByQwUserIdAndCorId(String cropId, String QwUserId) {
        return qwUserMapper.selectQwUserByQwUserIdAndCorId(cropId,QwUserId);
    }

    @Override
    public QwHookAuthVO selectQwUserByAppKeyAuth(String key) {
        return qwUserMapper.selectQwUserByAppKeyAuth(key);
    }

    @Override
    public List<QwOptionsVO> selectQwCompanyListOptionsVOByCompanyId(Long companyId) {
        return qwUserMapper.selectQwCompanyListOptionsVOByCompanyId(companyId);
    }



    /**
    * 解绑AI客服
    */
    @Override
    public R relieveFastGptRoleById(Long id) {
        int i = qwUserMapper.relieveFastGptRoleById(id);
        if (i > 0) {
            return R.ok();
        }else {
            return R.error();
        }

    }

    @Override
    public List<QwUserVO> selectAllQwUserListVO(QwUserListParam qwUser) {
        return qwUserMapper.selectAllQwUserListVO(qwUser);
    }

    @Override
    public QwUserVO selectQwUserVOById(Long id) {

      return   qwUserMapper.selectQwUserVOById(id);
    }


    @Override
    public List<QwUserVO> selectQwUserVOByIds(Long[] ids) {

        return   qwUserMapper.selectQwUserVOByIds(ids);
    }

    @Override
    public List<QwOptionsVO> selectQwCompanyListAllOptionsVO() {
        return qwUserMapper.selectQwCompanyListAllOptionsVO();
    }

    @Override
    public List<QwOptionsVO> getQwUserAll() {
        return qwUserMapper.getQwUserAll();
    }


    @Override
    public Long getQwUserCompanyId(String corpId, String qwUserid) {
        return qwUserMapper.getQwUserCompanyId(corpId,qwUserid);
    }

    @Override
    public R selectCloudByCompany(Long companyId, Long userId) {
        List<QwUserByToolDTO> qwUserByToolDTOS = qwUserMapper.selectQwUserListByTools(companyId, userId);
        qwUserByToolDTOS.forEach(item->{
            try {
                R r = GetIPAdminAndPassWord(item.getLoginCodeUrl());
                Object data = r.get("data");
                String jsonString = JSON.toJSONString(data);
                QwCloudAPVO apvo = JSON.parseObject(jsonString, QwCloudAPVO.class);

                item.setApAdmin(apvo.getApAdmin());
                item.setApPassword(apvo.getApPassword());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return R.ok().put("data",qwUserByToolDTOS);
    }

    @Override
    public List<UserVOs> getUserList(Long userId) {
        return qwWorkTaskMapper.getUserList(userId);
    }

    /**
     * 查询企微用户列表
     * @param params    条件
     * @return list
     */
    @Override
    public List<OptionVO> selectQwUserListByMap(Map<String, Object> params) {
        return qwUserMapper.selectQwUserListByMap(params);
    }

    @Override
    public R loginQwIpad(QwLoginHookParam loginParam) {
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        if (qwUser.getAppKey()==null){
            return R.error("请先授权key");
        }
        Long serverId = qwUser.getServerId();
        if (serverId==null){
            return R.error("请先获取ai主机");
        }
        if (qwUser.getServerStatus()!=1){
            return R.error("请先获取ai主机");
        }

        if (qwUser.getUid()!=null){
            WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
            wxWorkGetQrCodeDTO.setUuid(qwUser.getUid());
            WxWorkResponseDTO wxWorkResponseDTO = wxWorkService.automaticLogin(wxWorkGetQrCodeDTO,qwUser.getServerId());
            if (wxWorkResponseDTO.getErrcode()==0){
                updateIpadStatus(qwUser.getId(),1);
                redisCache.setCacheObject("qrCode:uuid:"+qwUser.getUid(),loginParam.getQwUserId());
                return R.ok("登录成功");
            }
        }
        //自动登录失败
        WxWorkInitDTO wxWorkInitDTO = new WxWorkInitDTO();
        if (qwUser.getVid()!=null){
            wxWorkInitDTO.setVid(qwUser.getVid());
        }
        WxWorkResponseDTO<WxWorkInitRespDTO> init = wxWorkService.init(wxWorkInitDTO,serverId);
        if (init.getErrcode()!=0){
            //vid登录失败
            return R.error("初始化失败");
        }
        WxWorkInitRespDTO data = init.getData();
        QwUser u = new QwUser();

        u.setId(loginParam.getQwUserId());
        u.setUid(data.getUuid());

        qwUserMapper.updateQwUser(u);
        if (data.getIs_login().equals("true")) {
            updateIpadStatus(qwUser.getId(),1);
            redisCache.setCacheObject("qrCode:uuid:"+data.getUuid(),loginParam.getQwUserId());
            return R.ok("登录成功");
        }
        WxWorkSetCallbackUrlDTO wxWorkSetCallbackUrlDTO = new WxWorkSetCallbackUrlDTO();
        wxWorkSetCallbackUrlDTO.setUrl("http://1.14.207.209:8008/msg/callback/"+serverId);
        wxWorkSetCallbackUrlDTO.setUuid(data.getUuid());
        wxWorkService.SetCallbackUrl(wxWorkSetCallbackUrlDTO,serverId);

        WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
        wxWorkGetQrCodeDTO.setUuid(data.getUuid());
        WxWorkResponseDTO<WxWorkGetQrCodeRespDTO> qrCode = wxWorkService.getQrCode(wxWorkGetQrCodeDTO,serverId);
        WxWorkGetQrCodeRespDTO qrData = qrCode.getData();


        redisCache.setCacheObject("qrCode:uuid:"+data.getUuid(),loginParam.getQwUserId());
        redisCache.setCacheObject("qrCode:qwUserId:"+loginParam.getQwUserId(),qrData.getKey(),10, TimeUnit.MINUTES);
        redisCache.setCacheObject("qrCodeUid:qwUserId:"+loginParam.getQwUserId(),data.getUuid(),10, TimeUnit.MINUTES);
        return R.ok().put("qrCode",qrData.getQrcode()).put("qrCode64",qrData.getQrcodeData());
    }

    void updateIpadStatus(Long id ,Integer status){
        QwUser u = new QwUser();
        u.setId(id);
        u.setIpadStatus(status);
        qwUserMapper.updateQwUser(u);
    }

    @Override
    public R qrCodeStatus(QwLoginHookParam loginParam) {
        String uid = redisCache.getCacheObject("qrCodeUid:qwUserId:" + loginParam.getQwUserId());
        if (uid == null) {
            return R.error("未获取到Uid");
        }
        Integer status = redisCache.getCacheObject("qrCodeUid:" + uid);
        if (status==null){
            return R.ok("100000");
        }

        return R.ok(status.toString());

    }

    @Override
    public R qrCodeVerify(QwLoginHookParam loginParam) {

        String key = redisCache.getCacheObject("qrCode:qwUserId:" + loginParam.getQwUserId());
        String uid = redisCache.getCacheObject("qrCodeUid:qwUserId:" + loginParam.getQwUserId());
        if (key==null||uid==null){
            return R.error("初始化错误请重新登录");
        }
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        WxWorkCheckCodeDTO wxWorkCheckCodeDTO = new WxWorkCheckCodeDTO();
        wxWorkCheckCodeDTO.setUuid(uid);
        wxWorkCheckCodeDTO.setCode(loginParam.getCode());
        wxWorkCheckCodeDTO.setQrcodeKey(key);
        System.out.println("登录参数："+wxWorkCheckCodeDTO);
        WxWorkResponseDTO wxWorkResponseDTO = wxWorkService.CheckCode(wxWorkCheckCodeDTO,qwUser.getServerId());
        if (wxWorkResponseDTO.getErrcode()==0){
            return R.ok();
        }
        return R.error("验证码错误重新输入验证码或重新扫码登录");
    }

    @Override
    public R outLoginQwIpad(QwLoginHookParam loginParam) {
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        if (qwUser.getAppKey()==null){
            return R.error("请先授权key");
        }
        if (qwUser.getServerStatus()!=1){
            return R.error("请先获取ai主机");
        }
        if (qwUser.getServerId()==null){
            return R.error("请先获取ai主机");
        }
        WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
        wxWorkGetQrCodeDTO.setUuid(qwUser.getUid());
        wxWorkService.LoginOut(wxWorkGetQrCodeDTO,qwUser.getServerId());
        updateIpadStatus(qwUser.getId(),0);
        return R.ok();
    }

    @Override
    public R getTwoCode(QwLoginHookParam loginParam) {
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        if (qwUser.getAppKey()==null){
            return R.error("请先授权key");
        }
        if (qwUser.getServerStatus()!=1){
            return R.error("请先获取ai主机");
        }
        if (qwUser.getServerId()==null){
            return R.error("请先获取ai主机");
        }
        WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
        wxWorkGetQrCodeDTO.setUuid(qwUser.getUid());
        WxWorkResponseDTO<WxwSecondaryValidationRespDTO> wxwSecondaryValidationRespDTOWxWorkResponseDTO = wxWorkService.SecondaryValidation(wxWorkGetQrCodeDTO,qwUser.getServerId());
        if (wxwSecondaryValidationRespDTOWxWorkResponseDTO.getErrcode()==0){
            WxwSecondaryValidationRespDTO data = wxwSecondaryValidationRespDTOWxWorkResponseDTO.getData();

            try {
                String base64 = convertImageToBase64(data.getQrcode());
                return R.ok().put("data",data).put("qrCode",base64);
            } catch (IOException e) {
                return R.error("二维码图片解析失败");
            }

        }
        return R.error("未获取到二次验证信息");
    }

    public static String convertImageToBase64(String imageUrl) throws IOException {
        // 创建URL对象
        URL url = new URL(imageUrl);

        // 打开输入流
        try (InputStream inputStream = url.openStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            // 读取图片数据
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 将字节数组转换为Base64字符串
            byte[] imageBytes = outputStream.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        }
    }

    @Override
    public R getTwoCodeStatus(QwLoginHookParam loginParam) {
        String uid = redisCache.getCacheObject("qrCodeUid:qwUserId:" + loginParam.getQwUserId());
        if (uid == null) {
            return R.error("未获取到Uid");
        }
        Integer status = redisCache.getCacheObject("twoCodeUid:" + uid);
        if (status==null){
            return R.ok("100000");
        }

        return R.ok(status.toString());
    }

    @Autowired
    ICompanyUserService companyUserService;
    @Autowired
    IQwIpadServerService ipadServerService;
    @Autowired
    IQwIpadServerLogService qwIpadServerLogService;
    @Autowired
    IQwIpadServerUserService qwIpadServerUserService;
    @Override
    public R getQwIpad(QwLoginHookParam loginParam) {
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        Integer serverStatus = qwUser.getServerStatus();
        if (serverStatus!=null && serverStatus==1){
            return R.error("已经绑定过");
        }
        if (qwUser.getAppKey()==null){
            return R.error("请先授权key");
        }
        CompanyUser companyUser = companyUserService.selectCompanyUserById(qwUser.getCompanyUserId());
        if (companyUser==null){
            return R.error("未绑定销售");
        }
        String addressId = companyUser.getAddressId();
        if (addressId==null || addressId.isEmpty()){
            return R.error("请先绑定地址");
        }
        Long serverId = ipadServerService.selectQwIpadServerByAddressId(addressId);
        if (serverId==null){
            return  R.error(501,"该地区服务器剩余数量不足");
        }
        QwUser u = new QwUser();
        u.setId(qwUser.getId());
        u.setServerId(serverId);
        u.setServerStatus(1);
        qwUserMapper.updateQwUser(u);


        ipadServerService.subtractServer(serverId);
        QwIpadServerLog qwIpadServerLog = new QwIpadServerLog();
        qwIpadServerLog.setType(1);
        qwIpadServerLog.setTilie("绑定");
        qwIpadServerLog.setServerId(serverId);
        qwIpadServerLog.setQwUserId(qwUser.getId());
        qwIpadServerLog.setCompanyUserId(companyUser.getUserId());
        qwIpadServerLog.setCompanyId(companyUser.getCompanyId());
        qwIpadServerLog.setCreateTime(new Date());
        qwIpadServerLogService.insertQwIpadServerLog(qwIpadServerLog);
        QwIpadServerUser qwIpadServerUser = new QwIpadServerUser();
        qwIpadServerUser.setCompanyUserId(companyUser.getUserId());
        qwIpadServerUser.setCompanyId(companyUser.getCompanyId());
        qwIpadServerUser.setCreateTime(new Date());
        qwIpadServerUser.setServerId(serverId);
        qwIpadServerUser.setQwUserId(qwUser.getId());
        qwIpadServerUserService.insertQwIpadServerUser(qwIpadServerUser);

        return R.ok();
    }

    @Override
    public R delQwIpad(QwLoginHookParam loginParam) {
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        Integer serverStatus = qwUser.getServerStatus();
        Long serverId = qwUser.getServerId();
        if (serverStatus==0){
            return R.error("不需要解绑");
        }
        if (serverId==null){
            return R.error("serverId不存在");
        }
        QwUser u = new QwUser();
        u.setId(qwUser.getId());
        u.setServerId(null);
        u.setServerStatus(0);
        qwUserMapper.updateQwUser(u);
        ipadServerService.addServer(serverId);
        QwIpadServerLog qwIpadServerLog = new QwIpadServerLog();
        qwIpadServerLog.setType(2);
        qwIpadServerLog.setTilie("解绑");
        qwIpadServerLog.setServerId(serverId);
        qwIpadServerLog.setQwUserId(qwUser.getId());
        qwIpadServerLog.setCompanyUserId(qwUser.getCompanyUserId());
        qwIpadServerLog.setCompanyId(qwUser.getCompanyId());
        qwIpadServerLog.setCreateTime(new Date());
        qwIpadServerLogService.insertQwIpadServerLog(qwIpadServerLog);
        qwIpadServerUserService.deleteQwIpadServerUserByQwUserId(qwUser.getId());
        WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
        wxWorkGetQrCodeDTO.setUuid(qwUser.getUid());
        wxWorkService.LoginOut(wxWorkGetQrCodeDTO,qwUser.getServerId());
        updateIpadStatus(qwUser.getId(),0);
        return R.ok();
    }

    @Override
    public R allocateRemoteHost(QwLoginHookParam loginParam) {
        QwUser qwUser = qwUserMapper.selectQwUserById(loginParam.getQwUserId());
        Integer serverStatus = qwUser.getServerStatus();
        if (serverStatus!=null && serverStatus==1){
            return R.error("已经绑定过");
        }
        if (qwUser.getAppKey()==null){
            return R.error("请先授权key");
        }
        CompanyUser companyUser = companyUserService.selectCompanyUserById(qwUser.getCompanyUserId());
        if (companyUser==null){
            return R.error("未绑定销售");
        }
        String addressId = companyUser.getAddressId();
        if (addressId==null || addressId.isEmpty()){
            return R.error("请先绑定地址");
        }
        Long serverId = ipadServerService.selectQwIpadServerByOtherAddressId();
        if (serverId==null){
            return  R.error("服务器剩余数量不足");
        }
        QwUser u = new QwUser();
        u.setId(qwUser.getId());
        u.setServerId(serverId);
        u.setServerStatus(1);
        qwUserMapper.updateQwUser(u);


        ipadServerService.subtractServer(serverId);
        QwIpadServerLog qwIpadServerLog = new QwIpadServerLog();
        qwIpadServerLog.setType(1);
        qwIpadServerLog.setTilie("绑定");
        qwIpadServerLog.setServerId(serverId);
        qwIpadServerLog.setQwUserId(qwUser.getId());
        qwIpadServerLog.setCompanyUserId(companyUser.getUserId());
        qwIpadServerLog.setCompanyId(companyUser.getCompanyId());
        qwIpadServerLog.setCreateTime(new Date());
        qwIpadServerLogService.insertQwIpadServerLog(qwIpadServerLog);
        QwIpadServerUser qwIpadServerUser = new QwIpadServerUser();
        qwIpadServerUser.setCompanyUserId(companyUser.getUserId());
        qwIpadServerUser.setCompanyId(companyUser.getCompanyId());
        qwIpadServerUser.setCreateTime(new Date());
        qwIpadServerUser.setServerId(serverId);
        qwIpadServerUser.setQwUserId(qwUser.getId());
        qwIpadServerUserService.insertQwIpadServerUser(qwIpadServerUser);

        return R.ok();
    }

    @Override
    public List<UserVOs> getQwUserList(Long userId, String qwUserId) {
        return qwWorkTaskMapper.getQwUserList(userId, qwUserId);
    }

    public R GetIPAdminAndPassWord(String ipAddress ) throws Exception {

        String bodyKey = HttpRequest.get("http://watch.ylrzcloud.com/prod-api/server/getKey?serverIp="+ipAddress)
                .execute().body();

//        String bodyKey = HttpRequest.get("http://192.168.10.155:8111/server/getKey?serverIp="+param.getIpAddress())
//                .execute().body();

        QwFsServerBindResult resultDecode = JSON.parseObject(bodyKey, QwFsServerBindResult.class);

        PrivateKey privateKey = getPrivateKeyFromString(resultDecode.getMsg());

        String signature = RSASignatureUtils.sign(ipAddress+ "ylrz321!#@1", privateKey );

        QwCloudAPParamB paramB=new QwCloudAPParamB();
        paramB.setServerIp(ipAddress);
        paramB.setSignature(signature);

        String body = HttpRequest.post("http://watch.ylrzcloud.com/prod-api/server/getAccount")
                .body(JSON.toJSONString(paramB), "application/json;charset=UTF-8")
                .execute().body();
//        String body = HttpRequest.post("http://192.168.10.155:8111/server/getAccount")
//                .body(JSON.toJSONString(paramB), "application/json;charset=UTF-8")
//                .execute().body();

        QwFsServerAPResult result = JSON.parseObject(body, QwFsServerAPResult.class);

        if (result.getCode()==200){
            //账号 解密
            String apAdmin = RSAUtils.decrypt(result.getData().serverAccount, privateKey);

            //密码
            String apPassword = RSAUtils.decrypt(result.getData().serverPassword, privateKey);

            QwCloudAPVO apvo=new QwCloudAPVO();
            apvo.setApAdmin(apAdmin);
            apvo.setApPassword(apPassword);

            return  R.ok().put("data",apvo);

        }else {
            return  R.error("获取账号密码失败，请重试！！错误码："+result.getMsg());
        }
    }

    /**
     *  url转临时文件filr
     */
    public static File urlToFile(String fileUrl) throws Exception {

        // 从URL中提取文件名，文件后缀
        String fileExtension = getFileExtension(new File(fileUrl).getName());
        String fileName = extractFileName(new URL(fileUrl))+new Date().getTime();
        File tempFile=null;
        if (!StringUtil.strIsNullOrEmpty(fileExtension)){
            // 创建一个临时文件
            tempFile = File.createTempFile(fileName, "."+fileExtension);
        }else {
            tempFile = File.createTempFile(fileName, null);
        }


        // 使用 try-with-resources 语句自动关闭资源
        try (BufferedInputStream in = new BufferedInputStream(new URL(fileUrl).openStream());
             FileOutputStream out = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[1024];
            int len;

            // 读取数据并写入到临时文件
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            // 处理异常，例如删除创建的临时文件
            tempFile.delete();
            throw e;
        }

        return tempFile;
    }

    /**
     *  获取文件名
     */
    private static String extractFileName(URL url) throws Exception {
        String path = url.getPath();
        int lastSlashIndex = path.lastIndexOf('/');
        String fileNameWithExt = path.substring(lastSlashIndex + 1);

        int dotIndex = fileNameWithExt.lastIndexOf('.');
        String baseName;
        if (dotIndex > 0) {
            // 如果有扩展名，移除扩展名
            baseName = fileNameWithExt.substring(0, dotIndex);
        } else {
            // 如果没有扩展名，直接使用文件名
            baseName = fileNameWithExt;
        }

        return baseName;
    }

    /**
     *  获取文件名后缀
     */

    public static String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex != -1 && lastIndex + 1 < fileName.length()) {
            return fileName.substring(lastIndex + 1);
        }
        return ""; // 如果没有扩展名，返回空字符串
    }
}
