package com.cool.store.mq.util;

import com.aliyun.ons20190214.*;
import com.aliyun.ons20190214.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.cool.store.constants.CommonConstants;
import com.cool.store.enums.RocketMqGroupEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chenyupeng
 * @since 2022/1/5
 */
@Slf4j
public class RocketMqUtil {

    private static final String INSTANCE_ID = "MQ_INST_1947409023213164_BX3sLZnA";

    /**
     * 本地
     */
    private static final String LOCAL_INSTANCE_ID = "MQ_INST_1255228665351616_BX3wfyPO";

    private static final String INSTANCE_ID_ONLINE_HD_PRE = "MQ_INST_1947409023213164_BX5N7rwl";
    private static final String ACCESS_KEY = "LTAI5tJbgtyoHUvofTaeP1RP";
    private static final String ACCESS_SECRET = "myg755iCx0j4PyQkHMaUVeOr0bw1tA";
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "ons.cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }

    public static Client createLocalClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "ons.mq-internet-access.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 新增测试、开发环境的group
     * @author chenyupeng
     * @date 2022/1/13
     * @param profiles 环境后缀，逗号分隔 例如： dev,dev2
     * @return void
     */
    public static void initGroup(String profiles) throws Exception {
        Client client = RocketMqUtil.createClient(ACCESS_KEY, ACCESS_SECRET);
        List<String> profileList = Arrays.asList(profiles.split(CommonConstants.COMMA));
        if(CollectionUtils.isEmpty(profileList)){
            return;
        }

        OnsGroupListRequest onsGroupListRequest = new OnsGroupListRequest();
        onsGroupListRequest.setInstanceId(INSTANCE_ID);
        OnsGroupListResponse onsGroupListResponse = client.onsGroupList(onsGroupListRequest);
        List<OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo> subscribeInfoDo = onsGroupListResponse.getBody().getData().getSubscribeInfoDo();
        Map<String, OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo> collect = ListUtils.emptyIfNull(subscribeInfoDo).stream().
                collect(Collectors.toMap(OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo::getGroupId, data -> data, (a, b) -> a));

        for (String profile : profileList) {
            for (RocketMqGroupEnum groupEnum : RocketMqGroupEnum.values()) {
                String groupId = groupEnum.getDefaultGroup() + "_" + profile;
                //已经创建就继续
                if(collect.get(groupId) != null){
                    continue;
                }
                OnsGroupCreateRequest onsGroupCreateRequest = new OnsGroupCreateRequest();
                onsGroupCreateRequest.setGroupId(groupId);
                onsGroupCreateRequest.setInstanceId(INSTANCE_ID);
                // 复制代码运行请自行打印 API 的返回值
                try {
                    client.onsGroupCreate(onsGroupCreateRequest);
                }catch (Exception e){
                    log.error("initGroupAndTag fail",e);
                }
                Thread.sleep(1000);
            }
        }
    }

    public static void initLocalGroup(String profiles) throws Exception {
        Client client = RocketMqUtil.createLocalClient("LTAI5tDbJ7SVCYZe8kEtq9Up", "Kk4itOA0pxTK1uD4z3pWLGQ3ZV6VSD");
        List<String> profileList = Arrays.asList(profiles.split(CommonConstants.COMMA));
        if(CollectionUtils.isEmpty(profileList)){
            return;
        }

        OnsGroupListRequest onsGroupListRequest = new OnsGroupListRequest();
        onsGroupListRequest.setInstanceId(LOCAL_INSTANCE_ID);
        OnsGroupListResponse onsGroupListResponse = client.onsGroupList(onsGroupListRequest);
        List<OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo> subscribeInfoDo = onsGroupListResponse.getBody().getData().getSubscribeInfoDo();
        Map<String, OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo> collect = ListUtils.emptyIfNull(subscribeInfoDo).stream().
                collect(Collectors.toMap(OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo::getGroupId, data -> data, (a, b) -> a));

        for (String profile : profileList) {
            for (RocketMqGroupEnum groupEnum : RocketMqGroupEnum.values()) {
                String groupId = groupEnum.getDefaultGroup() + "_" + profile;
                //已经创建就继续
                if(collect.get(groupId) != null){
                    continue;
                }
                OnsGroupCreateRequest onsGroupCreateRequest = new OnsGroupCreateRequest();
                onsGroupCreateRequest.setGroupId(groupId);
                onsGroupCreateRequest.setInstanceId(LOCAL_INSTANCE_ID);
                // 复制代码运行请自行打印 API 的返回值
                try {
                    client.onsGroupCreate(onsGroupCreateRequest);
                }catch (Exception e){
                    log.error("initGroupAndTag fail",e);
                }
                Thread.sleep(1000);
            }
        }
    }

    /**
     * 新增线上、灰度、预发环境的group
     * @author chenyupeng
     * @date 2022/1/13
     * @param profiles 环境后缀，逗号分隔 例如： online,hd,pre
     * @return void
     */
    public static void initOnlineAndHdAndPreGroup(String profiles) throws Exception {
        Client client = RocketMqUtil.createClient(ACCESS_KEY, ACCESS_SECRET);
        List<String> profileList = Arrays.asList(profiles.split(CommonConstants.COMMA));
        if(CollectionUtils.isEmpty(profileList)){
            return;
        }

        OnsGroupListRequest onsGroupListRequest = new OnsGroupListRequest();
        onsGroupListRequest.setInstanceId(INSTANCE_ID_ONLINE_HD_PRE);
        OnsGroupListResponse onsGroupListResponse = client.onsGroupList(onsGroupListRequest);
        List<OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo> subscribeInfoDo = onsGroupListResponse.getBody().getData().getSubscribeInfoDo();
        Map<String, OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo> collect = ListUtils.emptyIfNull(subscribeInfoDo).stream().
                collect(Collectors.toMap(OnsGroupListResponseBody.OnsGroupListResponseBodyDataSubscribeInfoDo::getGroupId, data -> data, (a, b) -> a));

        for (String profile : profileList) {
            for (RocketMqGroupEnum groupEnum : RocketMqGroupEnum.values()) {
                String groupId = groupEnum.getDefaultGroup() + "_" + profile;
                //已经创建就继续
                if(collect.get(groupId) != null){
                    continue;
                }
                OnsGroupCreateRequest onsGroupCreateRequest = new OnsGroupCreateRequest();
                onsGroupCreateRequest.setGroupId(groupId);
                onsGroupCreateRequest.setInstanceId(INSTANCE_ID_ONLINE_HD_PRE);
                // 复制代码运行请自行打印 API 的返回值
                try {
                    client.onsGroupCreate(onsGroupCreateRequest);
                }catch (Exception e){
                    log.error("initGroupAndTag fail",e);
                }
                Thread.sleep(1000);
            }
        }

    }

    /**
     * 删除测试、开发环境的group
     * @author chenyupeng
     * @date 2022/1/13
     * @param groupId
     * @return void
     */
    public static void deleteGroupById(String groupId) throws Exception {
        Client client = RocketMqUtil.createClient(ACCESS_KEY, ACCESS_SECRET);
        OnsGroupDeleteRequest request = new OnsGroupDeleteRequest();
        request.setGroupId(groupId);
        request.setInstanceId(INSTANCE_ID);
        client.onsGroupDelete(request);
    }
}
