package com.platform.modules.live.utils;

import cn.hutool.core.map.MapUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.platform.modules.live.dto.AliRequestDto;
import com.platform.modules.live.dto.DescribeCasterStreamResponseDto;
import com.platform.modules.live.dto.DescribeCastersDto;
import com.platform.modules.live.dto.DescribeCastersResponseDto;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 请求ali服务器 工具类
 * @Author: yikaihong
 * @CreateDate: 2019/1/19 14:23
 * @Version: 1.0
 */
public class AliRequestUtils {


    /**
     * 请求数据
     *
     * @param requestDto
     * @return
     */
    public static Object request(AliRequestDto requestDto) {
        if (requestDto == null) {
            return null;
        }

        DefaultProfile profile = DefaultProfile.getProfile(requestDto.getRegionId(), requestDto.getAccessKeyId(), requestDto.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(requestDto.getMethodType());
        request.setDomain(requestDto.getDomain());
        request.setVersion(requestDto.getVersion());
        request.setAction(requestDto.getAction());
        Map<String, Object> requestParams = requestDto.getRequestParams();
        if (requestParams != null && requestParams.size() > 0) {
            requestParams.forEach((k, v) -> {
                if (v != null) {
                    request.putQueryParameter(k, v.toString());
                }
            });
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response != null ? response.getData() : null;
        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 查询导播台列表。
     *
     * @param isFree       是否是空闲状态
     * @param resultSingle 返回一条还是多条结果
     * @param dto
     * @param <T>
     * @return
     */
    public static <T> T describeCasters(boolean isFree, boolean resultSingle, DescribeCastersDto dto) {
        if (dto == null) {
            dto = new DescribeCastersDto();
        }
        AliRequestDto requestDto = new AliRequestDto(MethodType.POST, null, dto.getAction());
        Object responseData = request(requestDto);
        List<DescribeCastersResponseDto> isFreeList = new ArrayList<>();
        List<DescribeCastersResponseDto> allList = new ArrayList<>();
        if (responseData != null) {
            JSONObject describeCastersResponseObject = JSONObject.fromObject(responseData);
            JSONObject casterInfoObjects = describeCastersResponseObject.getJSONObject("CasterList");
            JSONArray casterInfoArr = casterInfoObjects.getJSONArray("Caster");
            if (casterInfoArr != null && casterInfoArr.size() > 0) {
                casterInfoArr.forEach(casterInfo -> {
                    if (casterInfo instanceof JSONObject) {
                        JSONObject casterInfoObject = (JSONObject) casterInfo;
                        int status = casterInfoObject.getInt("Status");
                        DescribeCastersResponseDto bean = new DescribeCastersResponseDto(casterInfoObject);
                        if (isFree && status == 0) {
                            isFreeList.add(bean);
                        }
                        allList.add(bean);
                    }
                });
            }
        }
        return isFree ? (resultSingle ? (isFreeList != null && isFreeList.size() > 0 ? (T) isFreeList.get(0) : null) : (T) isFreeList) : (T) allList;
    }

    /**
     * 查询导播台流信息列表。
     *
     * @param casterId
     * @return
     */
    public static List<DescribeCasterStreamResponseDto> describeCasterConfig(String casterId) {
        Map<String, Object> queryParams = MapUtil.newHashMap();
        queryParams.put("CasterId", casterId);
        AliRequestDto requestDto = new AliRequestDto(MethodType.POST, queryParams, "DescribeCasterStreamUrl");
        Object responseData = request(requestDto);
        if (responseData != null) {
            List<DescribeCasterStreamResponseDto> responseDtoList = new ArrayList<>();
            JSONObject responseDataObject = JSONObject.fromObject(responseData);
            JSONObject casterStreams = responseDataObject.getJSONObject("CasterStreams");
            if (casterStreams != null && !casterStreams.isEmpty()) {
                JSONArray casterStream = casterStreams.getJSONArray("CasterStream");
                if (casterStream != null && !casterStream.isEmpty()) {
                    casterStream.forEach(item -> {
                        if (item instanceof JSONObject) {
                            responseDtoList.add(new DescribeCasterStreamResponseDto((JSONObject) item));
                        }
                    });
                }
            }
            return responseDtoList;
        }
        return null;
    }


    public static void main(String args[]) {
//        DescribeCastersResponseDto dto = describeCasters(true, true, null);
        System.err.println(describeCasterConfig("LIVEPRODUCER_POST-cn-v0h0ynqiq0p"));
    }

}