package com.tzld.piaoquan.api.component;

import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.model.param.wecom.thirdpart.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WeComThirdPartyApiClient {

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private final OkHttpClient client;

    {
        client = new OkHttpClient().newBuilder()
                .connectTimeout(3, TimeUnit.MINUTES)
                .readTimeout(3, TimeUnit.MINUTES)
                .writeTimeout(3, TimeUnit.MINUTES).build();
    }

    @Value("${wecom.thirdpart.baseUrl:http://47.96.102.58:8083}")
    private String baseUrl;

    /**
     * 初始化
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String init(InitRequest request) {
        return postRequest("/wxwork/init", request);
    }

    /**
     * 设置回调地址
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String setCallbackUrl(SetCallbackUrlRequest request) {
        return postRequest("/wxwork/SetCallbackUrl", request);
    }

    /**
     * 获取登录二维码
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String getQrCode(UuidRequest request) {
        return postRequest("/wxwork/getQrCode", request);
    }

    /**
     * 设置验证码
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String checkCode(CheckCodeRequest request) {
        return postRequest("/wxwork/CheckCode", request);
    }

    /**
     * 获取二次验证二维码接口
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String secondaryValidation(UuidRequest request) {
        return postRequest("/wxwork/SecondaryValidation", request);
    }

    /**
     * 获取当前登录详情
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String getRunClientByUuid(UuidRequest request) {
        return postRequest("/wxwork/GetRunClientByUuid", request);
    }

    /**
     * 获取当前账号对外名片二维码
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String getExternalBusinessCard(UuidRequest request) {
        return postRequest("/wxwork/ExternalBusinessCard", request);
    }

    /**
     * 获取内部联系人列表
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String getInnerContacts(GetInnerContactsRequest request) {
        return postRequest("/wxwork/GetInnerContacts", request);
    }

    /**
     * 获取外部联系人列表
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String getExternalContacts(GetExternalContactsRequest request) {
        return postRequest("/wxwork/GetExternalContacts", request);
    }

    /**
     * 自动登录
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String automaticLogin(UuidRequest request) {
        return postRequest("/wxwork/automaticLogin", request);
    }

    /**
     * 创建群
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String createRoomWx(CreateRoomWxRequest request) {
        return postRequest("/wxwork/CreateRoomWx", request);
    }

    /**
     * 添加群管理员
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String addRoomAdmins(AddRoomAdminsRequest request) {
        return postRequest("/wxwork/AddRoomAdmins", request);
    }

    /**
     * 群邀请确认
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String setChatroomInvite(SetChatroomInviteRequest request) {
        return postRequest("/wxwork/SetChatroomInvite", request);
    }

    /**
     * 修改群名
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String updateRoomName(UpdateRoomNameRequest request) {
        return postRequest("/wxwork/UpdateRoomName", request);
    }

    /**
     * 禁止群内添加和禁止修改群名
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String setRoomManagement(SetRoomManagementRequest request) {
        return postRequest("/wxwork/setRoomManagement", request);
    }

    /**
     * 禁止修改群名
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String disableRenameChatroom(DisableRenameChatroomRequest request) {
        return postRequest("/wxwork/DisableRenameChatroom", request);
    }

    /**
     * 获取群防骚扰规则列表
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String queryCRMAntiSpamRule(QueryCRMAntiSpamRuleRequest request) {
        return postRequest("/wxwork/queryCRMAntiSpamRule", request);
    }

    /**
     * 设置或者移除群防骚扰规则
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String setRoomAnti(SetRoomAntiRequest request) {
        return postRequest("/wxwork/setRoomAnti", request);
    }

    /**
     * 直接邀请进群
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String invitationToRoom(InvitationToRoomRequest request) {
        return postRequest("/wxwork/InvitationToRoom", request);
    }

    /**
     * 获取客户群列表
     * @param request
     * @return
     */
    public String getChatroomMembers(GetChatroomMembersRequest request) {
        return postRequest("/wxwork/GetChatroomMembers", request);
    }

    /**
     * 获取群成员列表
     * @param request
     * @return
     */
    public String getRoomUserList(GetRoomUserListRequest request) {
        return postRequest("/wxwork/GetRoomUserList", request);
    }

    /**
     * 转让群主
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String transferChatroomOwner(TransferChatroomOwnerRequest request) {
        return postRequest("/wxwork/TransferChatroomOwner", request);
    }

    /**
     * 发送文本消息
     *
     * @param request 请求体
     * {
     *     "uuid":"1753cdff-0501-42fe-bb5a-2a4b9629f7fb",
     *     "kf_id":0,   //用来客服消息回复，正常发送忽略这个字段。
     *     "send_userid":7881302555913738,
     *     "isRoom":false,
     *     "content":"ddddddd"
     * }
     * @return 响应结果
     */
    public String sendTextMsg(SendTextMsgRequest request) {
        return postRequest("/wxwork/SendTextMsg", request);
    }

    /**
     * 发送小程序消息
     *
     * @param request 请求体
     * {
     *     "uuid":"543ed7f3-6ec1-4b1a-9e47-db8339a140f7",
     *     "send_userid":7881302555913738,
     *     "desc":"内容",
     *     "appName":"小程序名称头像右边的",
     *     "title":"小程序标题头像下边的",
     *     "weappIconUrl":"https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",//小程序头像
     *     "pagepath":"pages/train/index/index.html",//小程序跳转地址
     *     "username":"gh_c4a2a98a7366@app", //账号原始id
     *     "appid":"wx45dff5234240ad90",//小程序appid
     *     "cdnkey":"30680201020461305f750bed0b3c7d089fa7d55720d6cf0201010201000400", //小程序封面图 cdn上传获取
     *     "md5":"d9c8750bed0b3c7d089fa7d55720d6cf",//封面图md5
     *     "aeskey":"34323235376238666264636630663166",//封面图 返回的aeskey
     *     "fileSize":15444,//封面图大小
     *     "isRoom":false
     * }
     * @return 响应结果
     */
    public String sendAppMsg(SendAppMsgRequest request) {
        return postRequest("/wxwork/SendAppMsg", request);
    }

    /**
     * CDN上传网络图片
     * @param request
     * @return
     */
    public String cdnUploadImgLink(CdnUploadImgLinkRequest request) {
        return postRequest("/wxwork/CdnUploadImgLink", request);
    }

    /**
     * 退出登录
     *
     * @param request 请求体
     * @return 响应结果
     */
    public String loginOut(UuidRequest request) {
        return postRequest("/wxwork/LoginOut", request);
    }

    private String postRequest(String path, Object requestBody) {
        String url = baseUrl + path;
        String json = JSONObject.toJSONString(requestBody);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                String responseStr = response.body().string();
                log.info("企微三方平台 请求成功, url: {}, body: {}, response: {}", url, json, responseStr);
                return responseStr;
            } else {
                log.error("企微三方平台 请求失败, url: {}, body: {}, response: {}", url, json, response);
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            log.error("请求失败", e);
        }
        return null;
    }
}