package com.shulead.datasync.manager;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dingtalkai_interaction_1_0.Client;
import com.aliyun.dingtalkai_interaction_1_0.models.PrepareResponse;
import com.aliyun.dingtalkai_interaction_1_0.models.UpdateResponse;
import com.aliyun.dingtalkai_interaction_1_0.models.UpdateResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.shulead.datasync.DatasyncApplication;
import com.shulead.datasync.entity.User;
import com.shulead.datasync.mapper.UserMapper;
import com.taobao.api.ApiException;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @Classname SendImage
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/5/8 18:03
 * @Created by liuxiangshun
 */
@SpringBootTest(classes = DatasyncApplication.class)
public class SendImage {
    @Resource
    private UserMapper userMapper;

    @Test
    public void sendImage() throws Exception {
        // ***** 获取 token ***
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);

        com.aliyun.teaopenapi.models.Config config1 = new com.aliyun.teaopenapi.models.Config();
        config1.protocol = "https";
        config1.regionId = "central";
        com.aliyun.dingtalkoauth2_1_0.Client client1 = new com.aliyun.dingtalkoauth2_1_0.Client(config1);

        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey("ding6p6hcejnpbbeszbg")
                .setAppSecret("TC4MLd9z3SSxAOBGn3loyGE3ChHVscV-h3w_PSRaDoV0d267_fCyvzvgc4vl6-qv");
//                com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
//                .setAppKey("dingopkgmzjmujpl7ulq")
//                .setAppSecret("AUhjA8T55d6-T4y_mhZs1z5dxM9sVjHHTMyeTxcuOLnBrKy_hWYUyKIX82zQ82U4");
        String token = null;
        try {
            token = client1.getAccessToken(getAccessTokenRequest).getBody().getAccessToken();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
        // ***** 获取 token ***

        // ******获取 unionId *****
//        String unionId = "QwUUiiWLkszBr5wNOs8GoPwiEiE";
//        String unionId = null;
//        try {
//            DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
//            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
//            req.setUserid("20001697");
////            req.setUserid("21212404011257985");
//            req.setLanguage("zh_CN");
//            OapiV2UserGetResponse rsp = client2.execute(req, token);
//            unionId = rsp.getResult().getUnionid();
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
        // ******获取 unionId *****

        // 获取所有用户
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getOrgId, 1L);
        List<User> users = userMapper.selectList(wrapper);
        for (User user : users) {
            String referenceUnionId = user.getReferenceUnionId();
            if (StringUtils.isBlank(referenceUnionId)) {
                continue;
            }
            // ****** 预发送 发一个转圈的 消息
            com.aliyun.dingtalkai_interaction_1_0.models.PrepareHeaders prepareHeaders = new com.aliyun.dingtalkai_interaction_1_0.models.PrepareHeaders();
            prepareHeaders.xAcsDingtalkAccessToken = token;
            com.aliyun.dingtalkai_interaction_1_0.models.PrepareRequest prepareRequest = new com.aliyun.dingtalkai_interaction_1_0.models.PrepareRequest()
                    .setUnionId(user.getReferenceUnionId())
                    .setContentType("ai_card")
                    .setContent("{\"templateId\": \"2a84ae65-620f-44f0-9ff2-b4edf9e60a9c.schema\"}");
            String conversationToken = null;
            try {
                PrepareResponse prepareResponse = client.prepareWithOptions(prepareRequest, prepareHeaders, new RuntimeOptions());
                conversationToken = prepareResponse.getBody().getResult().getConversationToken();
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    System.out.println(JSON.toJSONString(err));
                }

            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            }
            // ****** 预发送 发一个转圈的 消息

            // **** 更新消息的内容
            // 更新 markdown 部分 文字和图片
            com.aliyun.dingtalkai_interaction_1_0.models.UpdateHeaders updateHeaders = new com.aliyun.dingtalkai_interaction_1_0.models.UpdateHeaders();
            updateHeaders.xAcsDingtalkAccessToken = token;
            com.aliyun.dingtalkai_interaction_1_0.models.UpdateRequest updateRequest = new com.aliyun.dingtalkai_interaction_1_0.models.UpdateRequest()
                    .setConversationToken(conversationToken)
                    .setContentType("ai_card")
                    .setContent("""
                                { "templateId": "2a84ae65-620f-44f0-9ff2-b4edf9e60a9c.schema", "cardData": { "isFinalize": true, "value": "<font sizeToken=common_h2_text_style__font_size colorTokenV2=common_blue1_color>**别着急下班，有件事要告诉你。。。**</font> <br /><br /><font sizeToken=common_h5_text_style__font_size colorTokenV2=common_level2_base_color>双重Buff叠加，潜在下一代“药王”！咱公司的“减肥针”GLP-1R/GCGR双靶点激动剂玛仕度肽到底有多牛？作为信达的一员，如果你还不清楚可就OUT了~这个新鲜出炉的玛仕度肽作用机制视频，分享给你！1分钟，get所有“知识点”，拿走不谢！</font>
                                ", "key":"content" }, "options": { "componentTag":"streamingComponent" } }""");
            try {
                UpdateResponse updateResponse = client.updateWithOptions(updateRequest, updateHeaders, new RuntimeOptions());
                UpdateResponseBody.UpdateResponseBodyResult result = updateResponse.getBody().getResult();
                System.out.println(JSON.toJSONString(result));
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            }

            // 更新视频部分
            com.aliyun.dingtalkai_interaction_1_0.models.UpdateRequest updateRequest1 = new com.aliyun.dingtalkai_interaction_1_0.models.UpdateRequest()
                    .setConversationToken(conversationToken)
                    .setContentType("ai_card")
                    .setContent("""
                        { "templateId": "2a84ae65-620f-44f0-9ff2-b4edf9e60a9c.schema", "cardData": { "shipin":"https://mdm.innoventbio.com/images/GLP1R.GCGR.m4v","shipinfengmian":"https://mdm.innoventbio.com/images/8E9E9D38B8.jpg" }, "options": { "componentTag":"staticComponent" } }""");
            try {
                UpdateResponse updateResponse = client.updateWithOptions(updateRequest1, updateHeaders, new RuntimeOptions());
                UpdateResponseBody.UpdateResponseBodyResult result = updateResponse.getBody().getResult();
                System.out.println(JSON.toJSONString(result));
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            }

            // **** 更新消息的内容

            // 结束发消息
            com.aliyun.dingtalkai_interaction_1_0.models.FinishHeaders finishHeaders = new com.aliyun.dingtalkai_interaction_1_0.models.FinishHeaders();
            finishHeaders.xAcsDingtalkAccessToken = token;
            com.aliyun.dingtalkai_interaction_1_0.models.FinishRequest finishRequest = new com.aliyun.dingtalkai_interaction_1_0.models.FinishRequest()
                    .setConversationToken(conversationToken);
            try {
                client.finishWithOptions(finishRequest, finishHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }

            }
            Thread.sleep(100);
        }
    }
}
