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.service.ICompanyConfigService;
import com.fs.his.config.FsSysConfig;
import com.fs.his.utils.ConfigUtil;
import com.fs.qw.domain.QwCompany;
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.service.IQwCompanyService;
import com.fs.qw.service.IQwUserService;
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 org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.List;
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
    private QwWorkTaskMapper qwWorkTaskMapper;

//    @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("rt");

        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) {
        return qwUserMapper.selectQwUserListStaffVO(qwUser);
    }

    /**
     *  查询所有企微用户列表
     */
    @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();
        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);
            qwUser.setOpenid(qwOpenidResult.getOpenid());
             if (qw==null){
                 qwUserMapper.insertQwUser(qwUser);
             }else {
                 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);
    }

    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 ""; // 如果没有扩展名，返回空字符串
    }
}
