package com.fs.qwApi.service.impl;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.StringUtils;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.param.QwUpdateContactWayParam;
import com.fs.qw.service.IQwCompanyService;
import com.fs.qwApi.Result.*;
import com.fs.qwApi.config.QwApiConfig;
import com.fs.qwApi.domain.*;
import com.fs.qwApi.enums.Numbers;
import com.fs.qwApi.param.*;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import okhttp3.OkHttpClient;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class QwApiServiceImpl implements QwApiService {


      @Autowired
    IQwCompanyService iQwCompanyService;
//    @Autowired
//    ICompanyConfigService companyConfigService;

//    @Autowired
//    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();
    /**
     * 获取客户群列表 ownerFilterList 过滤的群主list,String cursor分页数据游标
     */
    @Override
    public QwGroupChatListResult groupChatList(ArrayList<String> ownerFilterList, String cursor, String corpId) {

        JSONObject jsonObject=new JSONObject();

        JSONObject ownerFilter=new JSONObject();
        ownerFilter.put("userid_list",ownerFilterList);

        jsonObject.put("limit",10);
        jsonObject.put("owner_filter",ownerFilter);
        jsonObject.put("cursor",cursor);

        String json = templateResultPost(jsonObject, QwApiConfig.groupChatList,corpId);
        QwGroupChatListResult qwGroupChatListResult = JSON.parseObject(json, QwGroupChatListResult.class);

        return qwGroupChatListResult;
    }

    /**
     * 获取客户群详情 chatId客户群id
     */
    @Override
    public QwGroupChatDetailsResult groupChatDetails(String chatId,String corpId) {

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("chat_id",chatId);
        jsonObject.put("need_name",1);
        String json = templateResultPost(jsonObject, QwApiConfig.groupChatDetails,corpId);
        QwGroupChatDetailsResult qwGroupChatDetailsResult = JSON.parseObject(json, QwGroupChatDetailsResult.class);
        return qwGroupChatDetailsResult;
    }


    /**
     * 创建企业-客户群发
     */
    @Override
    public QwAddMsgTemplateResult addMsgTemplate(QwMsgTemplate msgTemplate,String corpId) {

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("chat_type",msgTemplate.getChatType());
        jsonObject.put("external_userid",msgTemplate.getExternalUseridList());
        jsonObject.put("chat_id_list",msgTemplate.getChatIdList());

        JSONObject groupList=new JSONObject();
        groupList.put("group_list",msgTemplate.getTagFilterGroupList());
        jsonObject.put("tag_filter",groupList);
        jsonObject.put("sender",msgTemplate.getSender());
        jsonObject.put("allow_select",msgTemplate.getAllowSelect());

        JSONObject Content=new JSONObject();
        Content.put("content",msgTemplate.getTextContent());
        jsonObject.put("text",Content);
        ArrayList<Object> attachmentsList=new ArrayList<>();

        if (msgTemplate.getType()!=0){
            //获取类型
            Numbers numbers = Numbers.fromInt(msgTemplate.getType());
            switch (numbers){
                case Numbers_ONE:
                    if (!StringUtil.strIsNullOrEmpty(msgTemplate.getImagePicUrl())){
                        JSONObject attachmentsImage=new JSONObject();
                        JSONObject Image=new JSONObject();
                        Image.put("media_id",msgTemplate.getImageMediaId());
                        Image.put("pic_url", msgTemplate.getImagePicUrl());
                        attachmentsImage.put("msgtype","image");
                        attachmentsImage.put("image",Image);
                        attachmentsList.add(attachmentsImage);
                    }
                    break;
                case Numbers_TWO:
                    JSONObject attachmentsLink=new JSONObject();
                    JSONObject link=new JSONObject();
                    link.put("title",msgTemplate.getLinkTitle());
                    link.put("picurl",msgTemplate.getLinkPicurl());
                    link.put("desc",msgTemplate.getLinkDesc());
                    link.put("url",msgTemplate.getLinkUrl());
                    attachmentsLink.put("link",link);
                    attachmentsLink.put("msgtype","link");
                    attachmentsList.add(attachmentsLink);
                    break;
                case Numbers_THREE:
                    //没有小程序
//                JSONObject attachmentsMini=new JSONObject();
//                JSONObject miniProgram=new JSONObject();
//                miniProgram.put("title",msgTemplate.getMiniprogramTitle());
//                miniProgram.put("pic_media_id",msgTemplate.getMiniprogramPicMediaId());
//                miniProgram.put("appid",msgTemplate.getMiniprogramAppid());
//                miniProgram.put("page",msgTemplate.getMiniprogramPage());
//                attachmentsMini.put("miniprogram",miniProgram);
//                attachmentsMini.put("msgtype","miniprogram");
//                attachmentsList.add(attachmentsMini);
                    break;
                case Numbers_FOUR:
                    if (!StringUtil.strIsNullOrEmpty(msgTemplate.getFileMediaId())) {
                        JSONObject attachmentsFile = new JSONObject();
                        JSONObject file = new JSONObject();
                        file.put("media_id", msgTemplate.getFileMediaId());
                        attachmentsFile.put("file", file);
                        attachmentsFile.put("msgtype", "file");
                        attachmentsList.add(attachmentsFile);
                    }
                    break;
                case Numbers_FIVE:
                    if (!StringUtil.strIsNullOrEmpty(msgTemplate.getVideoMediaId())) {
                        JSONObject attachmentsMedia = new JSONObject();
                        JSONObject video = new JSONObject();
                        video.put("media_id", msgTemplate.getVideoMediaId());
                        attachmentsMedia.put("video", video);
                        attachmentsMedia.put("msgtype", "video");
                        attachmentsList.add(attachmentsMedia);
                    }
                    break;

            }
        }


        jsonObject.put("attachments",attachmentsList);
        String json = templateResultPost(jsonObject, QwApiConfig.addMsgTemplate,corpId);
        QwAddMsgTemplateResult qwAddMsgTemplateResult = JSON.parseObject(json, QwAddMsgTemplateResult.class);
        return qwAddMsgTemplateResult;
    }
    /**
     * 创建企业-客户群发SOP版
     */
    @Override
    public QwAddMsgTemplateResult addMsgTemplateBySop(QwMsgTemplateSop msgTemplate,String corpId) {

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("chat_type",msgTemplate.getChatType());
        jsonObject.put("external_userid",msgTemplate.getExternalUseridList());
        jsonObject.put("chat_id_list",msgTemplate.getChatIdList());

        JSONObject groupList=new JSONObject();
        groupList.put("group_list",msgTemplate.getTagFilterGroupList());
        jsonObject.put("tag_filter",groupList);
        jsonObject.put("sender",msgTemplate.getSender());
        jsonObject.put("allow_select",msgTemplate.getAllowSelect());

        JSONObject Content=new JSONObject();
        Content.put("content",msgTemplate.getTextContent());
        jsonObject.put("text",Content);
        ArrayList<Object> attachmentsList=new ArrayList<>();

        List<QwMsgTemplateSop.Attachment> attachments = msgTemplate.getAttachments();
        for (QwMsgTemplateSop.Attachment attachment : attachments) {
            if (attachment.getType()!=1){
                //获取类型
                switch (attachment.getType()){
                    case 2:
                        if (!StringUtil.strIsNullOrEmpty(attachment.getImagePicUrl())){
                            JSONObject attachmentsImage=new JSONObject();
                            JSONObject Image=new JSONObject();
                            Image.put("media_id",attachment.getImageMediaId());
                            Image.put("pic_url", attachment.getImagePicUrl());
                            attachmentsImage.put("msgtype","image");
                            attachmentsImage.put("image",Image);
                            attachmentsList.add(attachmentsImage);
                        }
                        break;
                    case 3:
                        JSONObject attachmentsLink=new JSONObject();
                        JSONObject link=new JSONObject();
                        link.put("title",attachment.getLinkTitle());
                        link.put("picurl",attachment.getLinkPicurl());
                        link.put("desc",attachment.getLinkDesc());
                        link.put("url",attachment.getLinkUrl());
                        attachmentsLink.put("link",link);
                        attachmentsLink.put("msgtype","link");
                        attachmentsList.add(attachmentsLink);
                        break;
                    case 4:
                        JSONObject attachmentsMiniProgram=new JSONObject();
                        JSONObject miniProgram=new JSONObject();
                        miniProgram.put("title",attachment.getMiniProgramTitle());
                        miniProgram.put("pic_media_id",attachment.getMiniProgramPicMediaId());
                        miniProgram.put("appid",attachment.getMiniProgramAppId());
                        miniProgram.put("page",attachment.getMiniProgramPage());
                        attachmentsMiniProgram.put("miniprogram",miniProgram);
                        attachmentsMiniProgram.put("msgtype","miniprogram");
                        attachmentsList.add(attachmentsMiniProgram);
                        break;
                }
            }
        }

        jsonObject.put("attachments",attachmentsList);
        String json = templateResultPost(jsonObject, QwApiConfig.addMsgTemplate,corpId);
        QwAddMsgTemplateResult qwAddMsgTemplateResult = JSON.parseObject(json, QwAddMsgTemplateResult.class);
        return qwAddMsgTemplateResult;
    }


    /**
     * 提醒成员群发
     */
    @Override
    public QwResult remindGroupmsgSend(String msgid,String corpId) {
        JSONObject jsonObject=new JSONObject();

        jsonObject.put("msgid",msgid);
        String json = templateResultPost(jsonObject, QwApiConfig.remindGroupmsgSend,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

    /**
     * 停止企业群发
     */
    @Override
    public QwResult cancelGroupmsgSend(String msgid,String corpId) {
        JSONObject jsonObject=new JSONObject();

        jsonObject.put("msgid",msgid);
        String json = templateResultPost(jsonObject, QwApiConfig.cancelGroupmsgSend,corpId);

        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

    /**
     * 获取群发记录列表
     */
    @Override
    public QwGetGroupmsgListV2Result getGroupmsgListV2(QwGetGroupmsgListV2Param param,String corpId) {

        String json = sendPost(QwApiConfig.getGroupmsgListV2, param,corpId);
        QwGetGroupmsgListV2Result qwGetGroupmsgListV2Result = JSON.parseObject(json, QwGetGroupmsgListV2Result.class);
        return qwGetGroupmsgListV2Result;
    }

    /**
     * 获取群发成员发送任务列表
     */
    @Override
    public QwGetGroupmsgTaskResult getGroupmsgTask(QwGetGroupMsgTask task,String corpId) {

        String json = sendPost(QwApiConfig.getGroupmsgTask, task,corpId);
        QwGetGroupmsgTaskResult qwGetGroupmsgTaskResult = JSON.parseObject(json, QwGetGroupmsgTaskResult.class);
        return qwGetGroupmsgTaskResult;

    }

    /**
     * 获取企业群发成员执行结果
     */
    @Override
    public QwGroupmsgSendResult getGroupmsgSendResult(QwGetGroupmsgSendParam param,String corpId) {
        String json = sendPost(QwApiConfig.getGroupmsgSendResult, param,corpId);
        QwGroupmsgSendResult qwGroupmsgSendResult = JSON.parseObject(json, QwGroupmsgSendResult.class);
        return qwGroupmsgSendResult;
    }

//    /**
//     * 创建成员标签
//     */
//    @Override
//    public QwResult createUserTag(QwCreateUserTagParam param,String corpId) {
//
////        JSONObject jsonObject=new JSONObject();
////            jsonObject.put("tagname",tagName);
//        String json = sendBookPost(QwApiConfig.createUserTag, param, corpId);
//        QwResult result = JSON.parseObject(json, QwResult.class);
//        return result;
//    }
//
//    /**
//     * 更新成员标签名称
//     */
//    @Override
//    public QwResult updateUserTag(QwUpdateUserTagParam param,String corpId) {
//
////        JSONObject jsonObject=new JSONObject();
////
////        jsonObject.put("tagid",tagId);
////        jsonObject.put("tagname",tagName);
//        String json = sendBookPost(QwApiConfig.updateUserTag, param, corpId);
//        QwResult result = JSON.parseObject(json, QwResult.class);
//        return result;
//    }
//
//    /**
//     * 删除成员标签
//     */
//    @Override
//    public QwResult deleteUserTag(int tagId,String corpId) {
//
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String bookSecret = qwCompanyConfig.getBookSecret();
//
//        String token = getToken(corpId, bookSecret);
//
//        String uploadUrl=QwApiConfig.deleteUserTag+token+"&tagid="+tagId+"";
//
//        String body = HttpUtil.createGet(uploadUrl)
//                .execute().body();
//        QwResult result = JSON.parseObject(body, QwResult.class);
//
//        return result;
//    }
//
//    /**
//     * 获取标签成员
//     */
//    @Override
//    public QwTagMemberResult getUserTag(int tagId,String corpId) {
//
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String bookSecret = qwCompanyConfig.getBookSecret();
//        String token = getToken(corpId, bookSecret);
//
//        String uploadUrl=QwApiConfig.getUserTag+token+"&tagid="+tagId+"";
//
//        String body = HttpUtil.createGet(uploadUrl)
//                .execute().body();
//        QwTagMemberResult tagResult = JSON.parseObject(body, QwTagMemberResult.class);
//        return tagResult;
//    }
//
//    /**
//     * 添加标签成员 userList企业成员ID列表,partylist企业部门ID列表（俩者不可同时为空）
//     */
//    @Override
//    public QwResult addTagUsersList(AddTagUsersListParam param,String corpId) {
//
//        String json = sendBookPost(QwApiConfig.addTagUsers, param,corpId);
//        QwResult result = JSON.parseObject(json, QwResult.class);
//        return result;
//    }
//
//    /**
//     * 删除标签成员
//     */
//    @Override
//    public QwResult delTagUsers(AddTagUsersListParam param,String corpId) {
//
//        String json = sendBookPost(QwApiConfig.delTagUsers, param,corpId);
//        QwResult result = JSON.parseObject(json, QwResult.class);
//        return result;
//    }
//
//    /**
//     * 获取成员标签列表
//     */
//    @Override
//    public QwTagListResult getUserTagList(String corpId) {
//
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String bookSecret = qwCompanyConfig.getBookSecret();
//        String token = getToken(corpId, bookSecret);
//
//        String uploadUrl=QwApiConfig.getUserTagList+token;
//
//        String body = HttpUtil.createGet(uploadUrl)
//                .execute().body();
//
//        QwTagListResult tagListResult = JSON.parseObject(body, QwTagListResult.class);
//        return tagListResult;
//    }


    /**
     * 添加入群欢迎语素材
     */
    @Override
    public QwAddWelcomeResult addGroupWelcomeTemplate(QwGroupWelcomeTemplateParam groupWelcomeTemplate, String corpId) {

        JSONObject jsonObject = typeChange(groupWelcomeTemplate);
        String json = templateResultPost(jsonObject, QwApiConfig.addGroupWelcomeTemplate,corpId);
        QwAddWelcomeResult qwResult = JSON.parseObject(json, QwAddWelcomeResult.class);
        return qwResult;

    }

    /**
     * 编辑入群欢迎语
     */
    @Override
    public QwResult editGroupWelcomeTemplate(QwGroupWelcomeTemplateParam groupWelcomeTemplate,String corpId) {

        JSONObject jsonObject = typeChange(groupWelcomeTemplate);
        jsonObject.put("template_id",groupWelcomeTemplate.getTemplateId());
        String json = templateResultPost(jsonObject, QwApiConfig.editGroupWelcomeTemplate,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;

    }

    /**
     *  类型选择录入库
     */
    public static JSONObject typeChange(QwGroupWelcomeTemplateParam groupWelcomeTemplate){
        JSONObject jsonObject=new JSONObject();
        JSONObject Content=new JSONObject();
        Content.put("content",groupWelcomeTemplate.getContent());
        jsonObject.put("text",Content);
        //获取类型
//        Numbers numbers = Numbers.fromInt(groupWelcomeTemplate.getType());
        Numbers numbers = Numbers.fromInt(groupWelcomeTemplate.getType());
        switch (numbers){
            case Numbers_ONE:
                break;
            case Numbers_TWO:
                JSONObject Image=new JSONObject();
                Image.put("media_id",groupWelcomeTemplate.getImageMediaId());
                Image.put("pic_url",groupWelcomeTemplate.getImagePicUrl());
                jsonObject.put("image",Image);
                break;
            case Numbers_THREE:
                JSONObject link=new JSONObject();
                link.put("title",groupWelcomeTemplate.getLinkTitle());
                link.put("picurl",groupWelcomeTemplate.getLinkPicurl());
                link.put("desc",groupWelcomeTemplate.getLinkDesc());
                link.put("url",groupWelcomeTemplate.getLinkUrl());
                jsonObject.put("link",link);
                break;
            case Numbers_FOUR:
                JSONObject miniProgram=new JSONObject();
                miniProgram.put("title",groupWelcomeTemplate.getMiniprogramTitle());
                miniProgram.put("pic_media_id",groupWelcomeTemplate.getMiniprogramPicMediaId());
                miniProgram.put("appid",groupWelcomeTemplate.getMiniprogramAppid());
                miniProgram.put("page",groupWelcomeTemplate.getMiniprogramPage());
                jsonObject.put("miniprogram",miniProgram);
                break;
            case Numbers_FIVE:
                JSONObject fileProgram=new JSONObject();
                fileProgram.put("media_id",groupWelcomeTemplate.getFileMediaId());
                jsonObject.put("file",fileProgram);
                break;
            case Numbers_SIX:
                JSONObject videoProgram=new JSONObject();
                videoProgram.put("media_id",groupWelcomeTemplate.getVideoMediaId());
                jsonObject.put("video",videoProgram);
                break;


        }
        return jsonObject;
    }

    /**
     * 获取入群欢迎语素材
     */
    @Override
    public QwGroupWelcomeTemplateRusult getGroupWelcomeTemplate(String templateId, String corpId) {

        JSONObject jsonObject=new JSONObject();

        jsonObject.put("template_id",templateId);
        String json = templateResultPost(jsonObject, QwApiConfig.getGroupWelcomeTemplate,corpId);
        QwGroupWelcomeTemplateRusult qwGroupWelcomeTemplate = JSON.parseObject(json, QwGroupWelcomeTemplateRusult.class);

        return qwGroupWelcomeTemplate;
    }

    /**
     * 删除入群欢迎语素材
     */
    @Override
    public QwResult delGroupWelcomeTemplate(String templateId,String corpId) {
        JSONObject jsonObject=new JSONObject();

        jsonObject.put("template_id",templateId);
        String json = templateResultPost(jsonObject, QwApiConfig.delGroupWelcomeTemplate,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

//    /**
//     * 永久上传图片
//     */
//    @Override
//    public QwUploadImgResult uploadImgByFile(MultipartFile file, String corpId) {
//        HttpClient httpClient = HttpClients.createDefault();
//
//        // 获取企业信息
//        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
//        String openSecret = qwCompany.getOpenSecret();
//        String token = getToken(corpId, openSecret);
//
//        URIBuilder uriBuilder;
//        try {
//            uriBuilder = new URIBuilder(QwApiConfig.uploadimg);
//            uriBuilder.setParameter("access_token", token);
//            URI uri = uriBuilder.build();
//
//            HttpPost httpPost = new HttpPost(uri);
//
//            // 构造表单数据
//            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//
//            // 使用 MultipartFile 获取文件流和文件名
//            builder.addBinaryBody("image", file.getInputStream(),
//                    ContentType.create("image/jpeg"), file.getOriginalFilename());
//
//            // 构建表单实体
//            HttpEntity multipart = builder.build();
//            httpPost.setEntity(multipart);
//
//            // 发送请求
//            HttpResponse response = httpClient.execute(httpPost);
//            String json = EntityUtils.toString(response.getEntity());
//
//            // 将返回 JSON 转换为结果对象
//            QwUploadImgResult qwUploadImgResult = JSON.parseObject(json, QwUploadImgResult.class);
//
//            return qwUploadImgResult;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }
//    @Override
//    public QwUploadImgResult uploadimg(File file, String corpId) {
//
//        HttpClient httpClient = HttpClients.createDefault();
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String appSecret = qwCompanyConfig.getAppSecret();
//        String token = getToken(corpId, appSecret);
//        URIBuilder uriBuilder = null;
//        try {
//            uriBuilder = new URIBuilder(QwApiConfig.uploadimg);
//            uriBuilder.setParameter("access_token", token);
//            URI uri = uriBuilder.build();
//
//            HttpPost httpPost = new HttpPost(uri);
//
//            // 构造表单数据
//            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//            builder.addBinaryBody("image", file, ContentType.create("image/jpeg"), file.getName());
//
//            // 构建表单实体
//            HttpEntity multipart = builder.build();
//            httpPost.setEntity(multipart);
//
//            // 发送请求
//            HttpResponse response = httpClient.execute(httpPost);
//            String json =  EntityUtils.toString(response.getEntity());
//
//            QwUploadImgResult qwUploadImgResult = JSON.parseObject(json, QwUploadImgResult.class);
//
//            return qwUploadImgResult;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    public QwUploadImgResult uploadimgs(String url, String corpId) throws IOException {

        HttpClient httpClient = HttpClients.createDefault();
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String appSecret = qwCompanyConfig.getAppSecret();
//        String token = getToken(corpId, appSecret);
//        String open_corpid = qwCompanyConfig.getOpen_corpid();
//        String openSecret = qwCompanyConfig.getOpen_Secret();

        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);


        String openSecret = qwCompany.getOpenSecret();

        String token = getToken(corpId, openSecret);

        URIBuilder uriBuilder = null;

        URL urlItem = new URL(url);
        InputStream inputStream =urlItem.openStream();

        try {
            uriBuilder = new URIBuilder(QwApiConfig.uploadimg);
            uriBuilder.setParameter("access_token", token);
            URI uri = uriBuilder.build();

            HttpPost httpPost = new HttpPost(uri);

            // 构造表单数据
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("image", inputStream, ContentType.create("image/jpeg"), UUID.randomUUID().toString());

            // 构建表单实体
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 发送请求
            HttpResponse response = httpClient.execute(httpPost);
            String json =  EntityUtils.toString(response.getEntity());

            QwUploadImgResult qwUploadImgResult = JSON.parseObject(json, QwUploadImgResult.class);

            return qwUploadImgResult;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
        }

        return null;
    }
    /**
     * 上传临时文件 有效期3天
     */
    @Override
    public QwUploadResult upload(File file, String type,String corpId) throws IOException {

        HttpClient httpClient = HttpClients.createDefault();
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String appSecret = qwCompanyConfig.getAppSecret();
//        String token = getToken(corpId, appSecret);
//
//        String open_corpid = qwCompanyConfig.getOpen_corpid();
//        String openSecret = qwCompanyConfig.getOpen_Secret();

        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

        String openSecret = qwCompany.getOpenSecret();

        String token = getToken(corpId, openSecret);

        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(QwApiConfig.upload);
            uriBuilder.setParameter("access_token", token);
            uriBuilder.setParameter("type", type);
            URI uri = uriBuilder.build();


            HttpPost httpPost = new HttpPost(uri);
            // 构造表单数据
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("media", file, ContentType.DEFAULT_BINARY, file.getName());

            // 构建表单实体
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            httpPost.setHeader("Content-Type", "multipart/form-data; charset=UTF-8");

            // 发送请求
            HttpResponse response = httpClient.execute(httpPost);
            String json =  EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

            QwUploadResult qwUploadResult = JSON.parseObject(json, QwUploadResult.class);

            return qwUploadResult;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

//    @Override
//    public QwUploadResult upload(MultipartFile file, String type,String corpId) throws IOException {
//
//        HttpClient httpClient = HttpClients.createDefault();
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String appSecret = qwCompanyConfig.getAppSecret();
//        String token = getToken(corpId, appSecret);
//        String open_corpid = qwCompanyConfig.getOpen_corpid();
//        String openSecret = qwCompanyConfig.getOpen_Secret();
//        String token = getToken(open_corpid, openSecret);
//
//        URIBuilder uriBuilder = null;
//        try {
//            uriBuilder = new URIBuilder(QwApiConfig.upload);
//            uriBuilder.setParameter("access_token", token);
//            uriBuilder.setParameter("type", type);
//            URI uri = uriBuilder.build();
//
//
//            HttpPost httpPost = new HttpPost(uri);
//            // 构造表单数据
//            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//            builder.addBinaryBody("media", file.getInputStream(), ContentType.DEFAULT_BINARY, file.getOriginalFilename());
//
//            // 构建表单实体
//            HttpEntity multipart = builder.build();
//            httpPost.setEntity(multipart);
//            httpPost.setHeader("Content-Type", "multipart/form-data; charset=UTF-8");
//
//            // 发送请求
//            HttpResponse response = httpClient.execute(httpPost);
//            String json =  EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
//
//            QwUploadResult qwUploadResult = JSON.parseObject(json, QwUploadResult.class);
//
//            return qwUploadResult;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    /** 获取临时素材  临时文件的mediaId*/
    @Override
    public JSONObject getMedia(String mediaId,String corpId) {
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String appSecret = qwCompanyConfig.getAppSecret();
//        String token = getToken(corpId, appSecret);
//        String open_corpid = qwCompanyConfig.getOpen_corpid();
//        String openSecret = qwCompanyConfig.getOpen_Secret();

        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

//        String open_corpid = qwCompany.getOpenCorpId();
        String openSecret = qwCompany.getOpenSecret();

        String token = getToken(corpId, openSecret);
        String uploadUrl=QwApiConfig.getMedia+token+"&media_id="+mediaId+"";

        String body = HttpUtil.createGet(uploadUrl)
                .execute().body();

        JSONObject tokenjson = JSON.parseObject(body);

        return tokenjson;
    }

    /** 配置客户联系「联系我」方式   */
    @Override
    public QwAddContactWayResult addContactWay(QwAddContactWayParam param, String corpId) {

        String json = sendPost(QwApiConfig.addContactWay, param,corpId);
        QwAddContactWayResult qwAddContactWayResult = JSON.parseObject(json, QwAddContactWayResult.class);
        return qwAddContactWayResult;

    }

    /** 获取企业已配置的「联系我」方式 */
    @Override
    public QwGetContactWayResult getContactWay(QwGetContactWayParam param, String corpId) {

        String json = sendPost(QwApiConfig.getContactWay, param,corpId);
        QwGetContactWayResult qwGetContactWayResult = JSON.parseObject(json, QwGetContactWayResult.class);
        return qwGetContactWayResult;
    }

    /** 获取企业已配置的「联系我」列表 */
    @Override
    public QwListContactWayReslut listContactWay(QwListContactWayParam param, String corpId) {

        String json = sendPost(QwApiConfig.listContactWay, param,corpId);
        QwListContactWayReslut qwListContactWayReslut = JSON.parseObject(json, QwListContactWayReslut.class);
        return qwListContactWayReslut;

    }

    /** 更新企业已配置的「联系我」方式  */
    @Override
    public QwResult updateContactWay(QwUpdateContactWayParam param, String corpId) {
        String json = sendPost(QwApiConfig.updateContactWay, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;

    }

    /** 删除企业已配置的「联系我」方式 */
    @Override
    public QwResult delContactWay(QwGetContactWayParam param, String corpId) {

        String json = sendPost(QwApiConfig.delContactWay, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

    @Override
    public QwAddContactWayResult addJoinWay(QwAddJoinWayParam param, String corpId) {
        String json = sendPost(QwApiConfig.addJoinWay, param,corpId);
        QwAddContactWayResult qwAddContactWayResult = JSON.parseObject(json, QwAddContactWayResult.class);
        return qwAddContactWayResult;
    }

    /** 获取客户群进群方式配置 */
    @Override
    public QeGetJoinWayResult getJoinWay(QwGetContactWayParam param, String corpId) {

        String json = sendPost(QwApiConfig.getJoinWay, param,corpId);
        QeGetJoinWayResult qeGetJoinWayResult = JSON.parseObject(json, QeGetJoinWayResult.class);
        return qeGetJoinWayResult;
    }

    /** 更新客户群进群方式配置 */
    @Override
    public QwResult updateJoinWay(QwAddJoinWayParam param, String corpId) {
        String json = sendPost(QwApiConfig.updateJoinWay, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;

    }

    /** 删除客户群进群方式配置 */
    @Override
    public QwResult delJoinWay(QwGetContactWayParam param, String corpId) {

        String json = sendPost(QwApiConfig.delJoinWay, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;

    }

    /** 获取客户群统计数据 */
    @Override
    public QwUserBehaviorDataResult getUserBehaviorData(QwUserBehaviorDataParam param, String corpId) {
        String json = sendPost(QwApiConfig.getUserBehaviorData, param, corpId);
        return JSON.parseObject(json, QwUserBehaviorDataResult.class);
    }

    /** 获取群聊统计数据 */
    @Override
    public QwGroupChatStatisticResult getGroupChatStatistic(QwGroupChatStatisticParam param, String corpId) {
        String json = sendPost(QwApiConfig.groupChatStatistic, param, corpId);
        return JSON.parseObject(json, QwGroupChatStatisticResult.class);
    }

    @Override
    public QwGroupChatStatisticResult getGroupChatStatisticByOwner(QwGroupChatStatisticParam param, String corpId) {
        String json = sendPost(QwApiConfig.groupChatStatisticByOwner, param, corpId);
        return JSON.parseObject(json, QwGroupChatStatisticResult.class);
    }

    @Override
    public QwOpenidResult useridToOpenid(QwOpenidByUserParams param, String corpId) {
        String json = sendBookPost(QwApiConfig.convertToOpenid, param, corpId);
        return JSON.parseObject(json, QwOpenidResult.class);
    }

    @Override
    public QwOpenidResult externalcontactToOpenid(QwOpenidByExternalcontactParams param, String corpId) {
        String json = sendPost(QwApiConfig.externalContactConvertToOpenid, param, corpId);
        return JSON.parseObject(json, QwOpenidResult.class);
    }



    @Override
    public String getToken(String corpId,String corpSecret) {
        String key =(String)redisCache.getCacheObject("qwServer:corpId:" + corpId + ":" + corpSecret);
        if (!StringUtil.strIsNullOrEmpty(key)){
            return key;
        }
        HttpClient httpClient = HttpClients.createDefault();
        String token=null;
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getTokenUrl);
            builder.setParameter("corpid", corpId);
            builder.setParameter("corpsecret", corpSecret);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);

            String tokenJson = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(tokenJson);
            token = jsonObject.getString("access_token");
            redisCache.setCacheObject("qwServer:corpId:"+corpId+":"+corpSecret,token,1,TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  token ;
    }

    @Override
    public QwcorpidToOpencorpidResult openCorpid(String corpId, String providerAccessToken) {
        JSONObject json=new JSONObject();
        json.put("corpid",corpId);
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.corpidToOpencorpid);
            builder.setParameter("provider_access_token", providerAccessToken);
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(json),StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            QwcorpidToOpencorpidResult qwcorpid = JSON.parseObject(reJson, QwcorpidToOpencorpidResult.class);
            return qwcorpid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取通过零时授权码和通用的suite_access_token 获取企业永久授权码以及其他信息
     */
    @Override
    public QwPermanentCodeResult getPermanentCode(QwPermanentCodeParam param, String suite_access_token) {

        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getPermanentCode);

            builder.setParameter("suite_access_token", suite_access_token);
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(param),StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            QwPermanentCodeResult qwPermanentCodeResult = JSON.parseObject(reJson, QwPermanentCodeResult.class);
            return qwPermanentCodeResult;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 服务商-获取第三方应用凭证/代开发应用模板凭证的(通讯录才要)
     */
    @Override
    public String getSuiteToken(QwSuiteTokenParams param) {
        String suite_access_token =(String) redisCache.getCacheObject("qwServer:suite_access_token:" + param.getSuite_id());
        String token="";
        if (StringUtils.isNotBlank(suite_access_token)) {
            return suite_access_token;
        }
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getSuiteToken);
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(param),StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(reJson);
            token = jsonObject.getString("suite_access_token");
            redisCache.setCacheObject("qwServer:suite_access_token:"+param.getSuite_id(),token,2,TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 服务商-获取获取服务商凭证
     */
    @Override
    public String getProviderToken(QwProviderTokenParams params) {
        String providerToken =(String) redisCache.getCacheObject("qwServer:provider_access_token:" + params.getCorpid());
        if (StringUtils.isNotBlank(providerToken)) {
            return providerToken;
        }
        HttpClient httpClient = HttpClients.createDefault();
        String token=null;
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getProviderToken);
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(params),StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String tokenJson = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(tokenJson);
            token = jsonObject.getString("provider_access_token");
            redisCache.setCacheObject("qwServer:provider_access_token:"+params.getCorpid(),token,1,TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }


    /**
     * 服务商-获取通讯录的token
     */
    @Override
    public String getBookAccessToken(QwGetCorpTokenParam param,String suite_access_token) {
        String providerToken =(String) redisCache.getCacheObject("qwServer:serverBook_access_token:" + param.getAuth_corpid());
        if (StringUtils.isNotBlank(providerToken)) {
            return providerToken;
        }

        HttpClient httpClient = HttpClients.createDefault();
        String token=null;
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getCorp_token);
            builder.setParameter("suite_access_token", suite_access_token);
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(param),StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String tokenJson = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(tokenJson);
            token = jsonObject.getString("access_token");
            redisCache.setCacheObject("qwServer:serverBook_access_token:"+param.getAuth_corpid(),token,1,TimeUnit.HOURS);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 服务商-读取员共信息 （通过userid）
     */
    @Override
    public String getServerQwUserName(String corpId,String Secret, String userid) {

        HttpClient httpClient = HttpClients.createDefault();
        String name = "";
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getServerQwUserName);
            builder.setParameter("access_token", getToken(corpId,Secret));
            builder.setParameter("userid", userid);
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(reJson);
            name = jsonObject.getString("name");

            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  侧边栏-获取企业微信当前登录人的userId
     */
    @Override
    public QwJsapiTicketResult getQwUserid(String code,String corpId,String appSecret) {

        QwJsapiTicketResult qwResult=new QwJsapiTicketResult();

        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getuserinfo);
            builder.setParameter("access_token", getToken(corpId,appSecret));
            builder.setParameter("code",code);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            qwResult = JSON.parseObject(json, QwJsapiTicketResult.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return qwResult;
    }

    /**
     * 侧边栏-获取企业的  jsapi_ticket
     */
    @Override
    public QwJsapiTicketResult getJsapiTicket(String bookCorpId,String bookSecret) {

//        String jsApiTicket =(String) redisTemplate.opsForValue().get("ticket:corpId" + ":" + corpId);
        String jsApiTicket =(String) redisCache.getCacheObject("ticket:corpId" + ":" + bookCorpId);

        QwJsapiTicketResult qwResult=new QwJsapiTicketResult();
        if (jsApiTicket!=null&&jsApiTicket!=""){
            qwResult.setTicket(jsApiTicket);
            qwResult.setCorpId(bookCorpId);
            return qwResult;
        }

        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getJsapiTicket);
            builder.setParameter("access_token", getToken(bookCorpId,bookSecret));
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());

            qwResult = JSON.parseObject(json, QwJsapiTicketResult.class);

//            redisTemplate.opsForValue().set("ticket:corpId"+":"+corpId,qwResult.getTicket(),1,TimeUnit.HOURS);
            redisCache.setCacheObject("ticket:corpId"+":"+bookCorpId,qwResult.getTicket(),1,TimeUnit.HOURS);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return qwResult;
    }

    /**
     * 侧边栏-获取应用的 jsapi_ticket
     */
    @Override
    public QwJsapiTicketResult getJsapiTicketApp(String corpId,String appSecret) {

//        String jsApiTicket =(String) redisTemplate.opsForValue().get("ticketApp:corpId" + ":" + corpId);
        String jsApiTicket =(String) redisCache.getCacheObject("ticketApp:corpId" + ":" + corpId);

        QwJsapiTicketResult qwResult=new QwJsapiTicketResult();

        if (jsApiTicket!=null&&jsApiTicket!=""){
            qwResult.setTicket(jsApiTicket);
            qwResult.setCorpId(corpId);
            return qwResult;
        }

        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.jsapiTicket);
            builder.setParameter("access_token", getToken(corpId,appSecret));
            builder.setParameter("type","agent_config");
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());

            qwResult = JSON.parseObject(json, QwJsapiTicketResult.class);
            qwResult.setCorpId(corpId);

//            redisTemplate.opsForValue().set("ticketApp:corpId"+":"+corpId,qwResult.getTicket(),1,TimeUnit.HOURS);
            redisCache.setCacheObject("ticketApp:corpId"+":"+corpId,qwResult.getTicket(),1,TimeUnit.HOURS);
            return qwResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传附件资源（朋友圈，商品图册专用）
     */
    @Override
    public QwUploadAttachmentResult uploadAttachment(String url, String type, String corpId) throws IOException {

        HttpClient httpClient = HttpClients.createDefault();
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);

//        String open_corpid = qwCompanyConfig.getOpen_corpid();
//        String openSecret = qwCompanyConfig.getOpen_Secret();
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

//        String open_corpid = qwCompany.getOpenCorpId();
        String openSecret = qwCompany.getOpenSecret();

        String token = getToken(corpId, openSecret);

        URIBuilder uriBuilder = null;

        URL urlItem = new URL(url);
        InputStream inputStream =urlItem.openStream();

        try {
            uriBuilder = new URIBuilder(QwApiConfig.uploadAttachment);
            uriBuilder.setParameter("access_token", token);
            uriBuilder.setParameter("media_type", type);
            uriBuilder.setParameter("attachment_type", String.valueOf(1));
            URI uri = uriBuilder.build();

            HttpPost httpPost = new HttpPost(uri);

            // 构造表单数据
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("media", inputStream,  ContentType.DEFAULT_BINARY, UUID.randomUUID().toString());

            // 构建表单实体
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 发送请求
            HttpResponse response = httpClient.execute(httpPost);
            String json =  EntityUtils.toString(response.getEntity());

            QwUploadAttachmentResult qwUploadImgResult = JSON.parseObject(json, QwUploadAttachmentResult.class);

            return qwUploadImgResult;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
        }

        return null;
    }

    /**
     * 发送客户朋友圈
     */
    @Override
    public QwAddMomentTaskResult addMomentTask(QwAddMomentTask qwAddMomentTask, String corpId) {
        String json = sendPost(QwApiConfig.addMomentTask, qwAddMomentTask, corpId);
        QwAddMomentTaskResult qwAddMomentTaskResult = JSON.parseObject(json, QwAddMomentTaskResult.class);
        return qwAddMomentTaskResult;
    }
    /**
     * 获取任务创建结果
     */
    @Override
    public QwGetMomentTaskResult getMomentTaskResult(String jobid, String corpId) {

//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String appSecret = qwCompanyConfig.getAppSecret();
//        String corpId = qwCompanyConfig.getOpen_corpid();
//        String appSecret = qwCompanyConfig.getOpen_Secret();
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

        String appSecret = qwCompany.getOpenSecret();

        HttpClient httpClient = HttpClients.createDefault();
        try {

            URIBuilder builder = new URIBuilder(QwApiConfig.getMomentTaskResult);
            builder.setParameter("access_token", getToken(corpId,appSecret));
            builder.setParameter("jobid", jobid);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());

            QwGetMomentTaskResult qwResult = JSON.parseObject(json, QwGetMomentTaskResult.class);
            return qwResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  停止发表企业朋友圈
     */
    @Override
    public QwResult cancelMomentTask(QwCancelMomentTask qwCancelMomentTask, String corpId) {
        String result = sendPost(QwApiConfig.cancelMomentTask, qwCancelMomentTask, corpId);

        return JSON.parseObject(result, QwResult.class);
    }

    /**
     * 获取客户朋友圈企业发表的列表
     */
    @Override
    public QwGetMomentTaskGResult getMomentTaskGResult(QwGetMomentTask qwGetMomentTask, String corpId) {
        String json = sendPost(QwApiConfig.getMomentTask, qwGetMomentTask, corpId);
        return JSON.parseObject(json, QwGetMomentTaskGResult.class);
    }

    /**
     * 获取客户朋友圈发表时选择的可见范围
     */
    @Override
    public QwGetMomentCustomerListResult getMomentCustomerList(QwGetMomentCustomerListParam customerListParam, String corpId) {
        String json = sendPost(QwApiConfig.getMomentCustomerList, customerListParam, corpId);
        return JSON.parseObject(json, QwGetMomentCustomerListResult.class);
    }

    /**
     * 获取客户朋友圈发表后的可见客户列表
     */
    @Override
    public QwGetMomentCustomerListResult getMomentSendResult(QwGetMomentSendResultParam qwGetMomentSendResultParam, String corpId) {
        String json = sendPost(QwApiConfig.getMomentSendResult, qwGetMomentSendResultParam, corpId);
        return JSON.parseObject(json, QwGetMomentCustomerListResult.class);
    }

    /**
     * 获取客户朋友圈的互动数据
     */
    @Override
    public QwGetMomentCommentsParamResult getMomentComments(QwGetMomentCommentsParam qwGetMomentCommentsParam, String corpId) {
        String json = sendPost(QwApiConfig.getMomentComments, qwGetMomentCommentsParam, corpId);
        return JSON.parseObject(json, QwGetMomentCommentsParamResult.class);
    }

    String getAppSecret(String corpId){
        String key =(String)redisCache.getCacheObject("appSecret:corpId:" + corpId);
        if (!StringUtil.strIsNullOrEmpty(key)){
            return key;
        }
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
        if (qwCompany!=null&&qwCompany.getOpenSecret()!=null){
            redisCache.setCacheObject("appSecret:corpId:" + corpId,qwCompany.getOpenSecret(),1,TimeUnit.HOURS);
            return qwCompany.getOpenSecret();
        }
        return null;
    }
    public String sendPost(String url, Object param, String corpId) {
        int maxRetries = 3; // 最大重试次数
        int retryCount = 0; // 当前重试次数
        // 1. 获取配置信息（可放在循环外，但要确保每次都能获取到最新的token）
        String appSecret = getAppSecret(corpId);
        while (retryCount < maxRetries) {
            try {
                // 2. 构造并发送请求
                HttpClient httpClient = HttpClients.createDefault();
                URIBuilder builder = new URIBuilder(url);
                builder.setParameter("access_token", getToken(corpId, appSecret));
                URI uri = builder.build();
                HttpPost httpPost = new HttpPost(uri);
                httpPost.setEntity(new StringEntity(JSON.toJSONString(param), StandardCharsets.UTF_8));
                HttpResponse response = httpClient.execute(httpPost);
                // 3. 解析结果
                String reJson = EntityUtils.toString(response.getEntity());
                QwResult qwResult = JSON.parseObject(reJson, QwResult.class);
                // 4. 判断错误码
                if (qwResult.getErrcode() == 45035) {
                    retryCount++;
                    Thread.sleep(2000);
                } else {
                    return reJson;
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }

        return null;
    }


//    public String sendPost(String url,Object param,String corpId){
//
//        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
//
//        String appSecret = qwCompany.getOpenSecret();
//
//        HttpClient httpClient = HttpClients.createDefault();
//        try {
//            URIBuilder builder = new URIBuilder(url);
//
//            builder.setParameter("access_token", getToken(corpId,appSecret));
//            URI uri = builder.build();
//            HttpPost httpPost  = new HttpPost(uri);
//            httpPost.setEntity( new StringEntity(JSON.toJSONString(param),StandardCharsets.UTF_8));
//            HttpResponse response = httpClient.execute(httpPost);
//            String reJson = EntityUtils.toString(response.getEntity());
//            return reJson;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    public String sendBookPost(String url,Object param,String corpId){

//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//获取通讯录的
//        String corpId = qwCompanyConfig.getCorpId();
//        String bookSecret = qwCompanyConfig.getBookSecret();
//        String corpId = qwCompanyConfig.getOpen_corpid();
//        String bookSecret = qwCompanyConfig.getOpen_Secret();

        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

        String bookSecret = qwCompany.getServerBookSecret();

        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(url);

            builder.setParameter("access_token", getToken(corpId,bookSecret));
            URI uri = builder.build();
            HttpPost httpPost  = new HttpPost(uri);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(param),StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            return reJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public String sendServerBookPost(String url,Object param,String corpId){
//
////        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
////        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//
////        String corpId = qwCompanyConfig.getServerBook_Corpid();
////        String bookSecret = qwCompanyConfig.getServerBook_Secret();
//
//        //这里获取存在redis里的通讯录的suite_ticket
////        String bookSuiteTicket = (String) redisTemplate.opsForValue().get("qwServer:bookServer_suite_ticket");
//        String bookSuiteTicket = (String) redisCache.getCacheObject("qwServer:bookServer_suite_ticket");
//
//        //获取通讯录的suite_token(所有企业通用suite_token)
////        CompanyConfig bookServerConfig = companyConfigService.selectCompanyConfigByServerKey("sys:qwBookServer:config");
////        QWCompanyConfig qwBookServerConfig = JSON.parseObject(bookServerConfig.getConfigValue(), QWCompanyConfig.class);
//
//        QwSuiteTokenParams qwSuiteTokenParams=new QwSuiteTokenParams();
//        qwSuiteTokenParams.setSuite_id(qwBookServerConfig.getSuiteID());
//        qwSuiteTokenParams.setSuite_secret(qwBookServerConfig.getSecret());
//        qwSuiteTokenParams.setSuite_ticket(bookSuiteTicket);
//        String suiteToken = getSuiteToken(qwSuiteTokenParams);
//
//        //属于各自企业的通讯录auth_corpid和permanent_code（永久授权码）
//        QwGetCorpTokenParam qwGetCorpTokenParam=new QwGetCorpTokenParam();
//        qwGetCorpTokenParam.setAuth_corpid(corpId);
//        qwGetCorpTokenParam.setPermanent_code(bookSecret);
//
//        HttpClient httpClient = HttpClients.createDefault();
//        try {
//            URIBuilder builder = new URIBuilder(url);
//
//            builder.setParameter("access_token", getBookAccessToken(qwGetCorpTokenParam, suiteToken));
//            URI uri = builder.build();
//            HttpPost httpPost  = new HttpPost(uri);
//            httpPost.setEntity( new StringEntity(JSON.toJSONString(param),StandardCharsets.UTF_8));
//            HttpResponse response = httpClient.execute(httpPost);
//            String reJson = EntityUtils.toString(response.getEntity());
//            return reJson;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//

    @Override
    public QwUserIdResult getUserList(String corpId) {
        HttpClient httpClient = HttpClients.createDefault();
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);
        String bookSecret = qwCompany.getServerBookSecret();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getUserListUrl);
            builder.setParameter("access_token", getToken(corpId,bookSecret));
//            builder.setParameter("access_token", getBookAccessToken(qwGetCorpTokenParam, suiteToken));
            URI uri = builder.build();
            HttpPost  httpPost  = new HttpPost(uri);
            Map<String, Object> map = new HashMap<>();
            map.put("limit", 10000);
            httpPost.setEntity( new StringEntity(JSON.toJSONString(map)));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            QwUserIdResult qwResult = JSON.parseObject(reJson, QwUserIdResult.class);

            return qwResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public QwDeptResult getDepartmentList(String corpId) {
////        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
////        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
////        String corpId = qwCompanyConfig.getCorpId();
////        String bookSecret = qwCompanyConfig.getBookSecret();
//        String corpId = qwCompanyConfig.getOpen_corpid();
//        String bookSecret = qwCompanyConfig.getOpen_Secret();
//
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

        String bookSecret = qwCompany.getOpenSecret();

        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.getDepartmentList);
            builder.setParameter("access_token", getToken(corpId,bookSecret));
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            QwDeptResult qwResult = JSON.parseObject(json, QwDeptResult.class);
            return qwResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public QwExternalContactListResult getExternalcontactList(String userId,String corpId) {
//
////        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
////        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
////        String corpId = qwCompanyConfig.getCorpId();
////        String appSecret = qwCompanyConfig.getAppSecret();
//        String corpId = qwCompanyConfig.getOpen_corpid();
//        String appSecret = qwCompanyConfig.getOpen_Secret();
        QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

        String appSecret = qwCompany.getOpenSecret();
        HttpClient httpClient = HttpClients.createDefault();
        try {

            URIBuilder builder = new URIBuilder(QwApiConfig.externalcontactListUrl);
            builder.setParameter("access_token", getToken(corpId,appSecret));
            builder.setParameter("userid", userId);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            QwExternalContactListResult qwResult = JSON.parseObject(json, QwExternalContactListResult.class);
            return qwResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public QwExternalContactResult getExternalcontact(String userId,String corpId) {
        String appSecret = getAppSecret(corpId);

        String token = getToken(corpId, appSecret);
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwApiConfig.externalcontactUrl);
            builder.setParameter("access_token", token);
            builder.setParameter("external_userid", userId);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            QwExternalContactResult qwResult = JSON.parseObject(json, QwExternalContactResult.class);
            return qwResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public QwExternalContactAllListResult getAllExternalcontactList(QwExternalListParam param,String corpId) {
        String json = sendPost(QwApiConfig.externalcontactAllLlistUrl, param,corpId);
        QwExternalContactAllListResult qwResult = JSON.parseObject(json, QwExternalContactAllListResult.class);
        return qwResult;
    }

    @Override
    public QwExternalContactRemarkResult externalcontactRemark(QwExternalContactRemarkParam param,String corpId) {
        String json = sendPost(QwApiConfig.externalcontactRemarkUrl, param,corpId);
        QwExternalContactRemarkResult qwResult = JSON.parseObject(json, QwExternalContactRemarkResult.class);
        return qwResult;
    }

    @Override
    public QwTagResult getTag(QwTagParam param,String corpId) {
        String json = sendPost(QwApiConfig.getTagUrl, param,corpId);
        QwTagResult qwResult = JSON.parseObject(json, QwTagResult.class);
        return qwResult;
    }
    @Override
    public QwResult sendWelcomeMsg(SendWelcomeMsgParam param, String corpId) {

        String json = sendPost(QwApiConfig.sendWelcomeMsg,param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

//
//    /** 创建成员  仅通讯录同步助手或第三方通讯录应用可调用 */
//    @Override
//    public QwCreateUserResult createUser(QwCreateUserParam param, String corpId) {
//        String json = sendBookPost(QwApiConfig.createUser, param, corpId);
//        QwCreateUserResult qwCreateUserResult = JSON.parseObject(json, QwCreateUserResult.class);
//        return qwCreateUserResult;
//    }
//    /** 更新成员 仅通讯录同步助手或第三方通讯录应用可调用 */
//    @Override
//    public QwResult updateUser(QwCreateUserParam param, String corpId) {
//        String json = sendBookPost(QwApiConfig.updateUser, param, corpId);
//         QwResult qwResult = JSON.parseObject(json, QwResult.class);
//        return qwResult;
//    }
//    /** 删除成员  仅通讯录同步助手或第三方通讯录应用可调用。
//     若是绑定了腾讯企业邮，则会同时删除邮箱账号。*/
//    @Override
//    public QwResult deleteUser(String userid, String corpId) {
//        String json = sendBookPost(QwApiConfig.deleteUser, userid, corpId);
//         QwResult qwResult = JSON.parseObject(json, QwResult.class);
//        return qwResult;
//    }
//    /**  批量删除成员 仅通讯录同步助手或第三方通讯录应用可调用。 */
//    @Override
//    public QwResult batchDeleteUser(QwBatchDeleteUserParam param, String corpId) {
//        String json = sendBookPost(QwApiConfig.batchDeleteUser, param, corpId);
//         QwResult qwResult = JSON.parseObject(json, QwResult.class);
//        return qwResult;
//    }
//    /** 邀请成员  仅通讯录同步助手或第三方通讯录应用可调用。*/
//    @Override
//    public QwInviteUserResult inviteUser(QwInviteUserParam param, String corpId) {
//        String json = sendBookPost(QwApiConfig.inviteUser, param, corpId);
//        QwInviteUserResult qwResult = JSON.parseObject(json, QwInviteUserResult.class);
//        return qwResult;
//    }
//    /** 获取加入企业二维码 须拥有通讯录的管理权限，使用通讯录同步的Secret。  */
//    @Override
//    public QwJoinQrcodeResult getJoinQrcode(String corpId) {
//
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        String bookSecret = qwCompanyConfig.getBookSecret();
//        String token = getToken(corpId, bookSecret);
//
//        String uploadUrl=QwApiConfig.getJoinQrcode+token;
//
//        String body = HttpUtil.createGet(uploadUrl)
//                .execute().body();
//
//        QwJoinQrcodeResult joinQrcodeResult = JSON.parseObject(body, QwJoinQrcodeResult.class);
//
//        return joinQrcodeResult;
//    }
    /** 手机号获取userid 应用须拥有指定成员的查看权限。  */
    @Override
    public QwUseridResult getuseridBymobile(QwUseridBymobileParam param, String corpId) {

        String json = sendPost(QwApiConfig.getuseridBymobile, param,corpId);
         QwUseridResult qwResult = JSON.parseObject(json, QwUseridResult.class);

        return qwResult;
    }
    /** 邮箱获取userid 应用须拥有指定成员的查看权限。 */
    @Override
    public QwUseridResult getuseridByEmail(QwUseridByEmailParam param, String corpId) {

        String json = sendPost(QwApiConfig.getuseridByEmail, param,corpId);
        QwUseridResult qwResult = JSON.parseObject(json, QwUseridResult.class);
        return qwResult;
    }


    @Override
    public QwAddTagResult addTag(QwAddTagParam param,String corpId) {

        String json = sendPost(QwApiConfig.addTagUrl, param,corpId);
        QwAddTagResult qwResult = JSON.parseObject(json, QwAddTagResult.class);
        return qwResult;
    }

    @Override
    public QwResult editTag(QwEditTagParam param,String corpId) {

        String json = sendPost(QwApiConfig.editTagUrl, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

    @Override
    public QwResult delTag(QwTagParam param,String corpId) {

        String json = sendPost(QwApiConfig.delTagUrl, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

    @Override
    public QwTransferCustomerResult transferCustomer(QwTransferCustomerParam param,String corpId) {
        String json = sendPost(QwApiConfig.transferCustomerUrl, param,corpId);
        QwTransferCustomerResult qwResult = JSON.parseObject(json, QwTransferCustomerResult.class);
        return qwResult;
    }

    @Override
    public QwGetTransferResult getTransfer(QwGetTransferParam param,String corpId) {
        String json = sendPost(QwApiConfig.getTransferUrl, param,corpId);
        QwGetTransferResult qwResult = JSON.parseObject(json, QwGetTransferResult.class);
        return qwResult;
    }

    @Override
    public QwGroupChatTransferResult groupChatTransfer(QwGroupChatTransferParam param,String corpId) {
        String json = sendPost(QwApiConfig.groupChatTransferUrl, param,corpId);
        QwGroupChatTransferResult qwResult = JSON.parseObject(json, QwGroupChatTransferResult.class);
        return qwResult;
    }

    @Override
    public QwUnassignedListResult getUnassignedList(QwUnassignedListParam param,String corpId) {
        String json = sendPost(QwApiConfig.getUnassignedListUrl, param,corpId);
        QwUnassignedListResult qwResult = JSON.parseObject(json, QwUnassignedListResult.class);
        return qwResult;
    }

    @Override
    public QwTransferCustomerResignedResult resignedTransferCustomer(QwTransferCustomerResignedParam param,String corpId) {
        String json = sendPost(QwApiConfig.resignedTransferCustomerUrl, param,corpId);
        QwTransferCustomerResignedResult qwResult = JSON.parseObject(json, QwTransferCustomerResignedResult.class);
        return qwResult;
    }

    @Override
    public QwGetTransferResult getResignedTransfer(QwGetTransferParam param,String corpId) {
        String json = sendPost(QwApiConfig.getResignedTransferUrl, param,corpId);
        QwGetTransferResult qwResult = JSON.parseObject(json, QwGetTransferResult.class);
        return qwResult;
    }

    @Override
    public QwGroupChatTransferResult resignedGroupChatTransfer(QwGroupChatTransferParam param,String corpId) {
        String json = sendPost(QwApiConfig.resignedGroupChatTransferUrl, param,corpId);
        QwGroupChatTransferResult qwResult = JSON.parseObject(json, QwGroupChatTransferResult.class);
        return qwResult;
    }

    @Override
    public QwResult editUserTag(QwEditUserTagParam param,String corpId) {
        String json = sendPost(QwApiConfig.editUserTagUrl, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        return qwResult;
    }

    @Override
    public QwSendMsgResult sendMsg(QwSendMsgParam param, String corpId) {
        String json = sendPost(QwApiConfig.sendMsg, param,corpId);
        QwSendMsgResult qwResult = JSON.parseObject(json, QwSendMsgResult.class);
        return qwResult;
    }

    @Override
    public QwLinkListResult linkList(QwParam param, String corpId) {
        String json = sendPost(QwApiConfig.linkList, param,corpId);
        QwLinkListResult qwResult = JSON.parseObject(json, QwLinkListResult.class);
        return qwResult;
    }

    @Override
    public QwLinkGetResult linkGet(QwLinkGetParam param, String corpId) {
        String json = sendPost(QwApiConfig.linkGet, param,corpId);
        QwLinkGetResult qwResult = JSON.parseObject(json, QwLinkGetResult.class);
        return qwResult;
    }

    @Override
    public QwLinkCreateResult linkCreate(QwLinkCreateParam param, String corpId) {
        String json = sendPost(QwApiConfig.linkCreate, param,corpId);
        QwLinkCreateResult qwResult = JSON.parseObject(json, QwLinkCreateResult.class);
        if(qwResult.getErrcode() != 0) throw new BaseException("创建获客链接错误：" + qwResult.getErrmsg());
        return qwResult;
    }

    @Override
    public QwResult linkUpdate(QwLinkCreateParam param, String corpId) {
        String json = sendPost(QwApiConfig.linkUpdate, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        if(qwResult.getErrcode() != 0) throw new BaseException("修改获客链接错误：" + qwResult.getErrmsg());
        return qwResult;
    }

    @Override
    public QwResult linkDelete(QwLinkGetParam param, String corpId) {
        String json = sendPost(QwApiConfig.linkDelete, param,corpId);
        QwResult qwResult = JSON.parseObject(json, QwResult.class);
        if(qwResult.getErrcode() != 0) throw new BaseException("删除获客链接错误：" + qwResult.getErrmsg());
        return qwResult;
    }

    @Override
    public QwLinkCustomerResult linkCustomer(QwLinkCustomerParam param, String corpId) {
        String json = sendPost(QwApiConfig.linkCustomer, param,corpId);
        QwLinkCustomerResult qwResult = JSON.parseObject(json, QwLinkCustomerResult.class);
        if(qwResult.getErrcode() != 0) throw new BaseException("获客链接错误：" + qwResult.getErrmsg());
        return qwResult;
    }

    /**
     * 封装的post请求
     */
    public String templateResultPost(JSONObject object, String url,String corpId){
        HttpClient httpClient = HttpClients.createDefault();
        URIBuilder builder = null;
        try {
            builder = new URIBuilder(url);
////            CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(corpId, "sys:qw:config");
////            QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
////            String corpId = qwCompanyConfig.getCorpId();
////            String appSecret = qwCompanyConfig.getAppSecret();
//            String corpId = qwCompanyConfig.getOpen_corpid();
//            String appSecret = qwCompanyConfig.getOpen_Secret();
            QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(corpId);

            String appSecret = qwCompany.getOpenSecret();

            String token = getToken(corpId,appSecret);

            builder.setParameter("access_token", token);
            URI uri = builder.build();

            HttpPost httpPost  = new HttpPost(uri);
            // 设置请求头参数类型为utf-8
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

            httpPost.setEntity( new StringEntity(JSON.toJSONString(object),"UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());

            return reJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
