package com.sifang.modules.q7link.utils;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.opensdk.BaseRequest;
import com.amazonaws.opensdk.SdkRequestConfig;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.q7link.openapi.Openapi;
import com.q7link.openapi.model.GetQueueRequest;
import com.q7link.openapi.model.Queue;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class AmazonSqsReceiveMessage {


    private static Regions regions = Regions.CN_NORTH_1;
    private static AmazonSQS amazonSQS;
    private static Openapi openapi;



  //  @Scheduled(cron = "0/10 * * * * ?") // 每隔10秒执行一次
    public void onMessage() {
        Queue queue = getQueue();
        String queueUrl = queue.getQueueUrl();
        // 接收消息
        List<Message> messages = receiveMessages(queueUrl);
        for (Message message : messages) {
            System.out.println("\n*************消息发送时间*************************\n" + LocalDateTime.now());
            // 消息体
            String body = message.getBody();

            JSONObject jsonObject = new JSONObject(body.isEmpty());
            // 进行字段解析等操作
            // ...

            // do something （构建查询参数，调用查询接口）

            System.out.println(body);
            // 删除消息
            amazonSQS().deleteMessage(queueUrl, message.getReceiptHandle());
        }
    }




    /**
     * 接收消息,推荐使用长轮询
     * <pre>
     *   1.最大等待时间：20秒 值范围：1-20秒
     *   2.最大接收消息数：10 值范围：1-10
     *   3.默认可见性超时：60秒 值范围：0-12天
     *      根据业务需求适当调整可见性超时时间
     * </pre>
     *
     * @param queueUrl 队列url
     * @return 消息列表
     */
    private static List<Message> receiveMessages(String queueUrl) {
        ReceiveMessageRequest request = new ReceiveMessageRequest()
                // 队列url
                .withQueueUrl(queueUrl)
                // 可见性超时：默认60秒，收到消息在可见性超时时间内不会再次收到该消息。注意：可见性超时无法保证不会接收消息两次
                .withVisibilityTimeout(10)
                // 最大等待时间：20秒 值范围：1-20秒
                .withWaitTimeSeconds(5)
                // 最大接收消息数：10 值范围：1-10
                .withMaxNumberOfMessages(10);
        return amazonSQS().receiveMessage(request).getMessages();
    }


    public static AmazonSQS amazonSQS() {
        if (amazonSQS == null) {
            String accessKey = Q7linkConstants.ACCESS_KEY_ID ;
            String accessSecret = Q7linkConstants.ACCESS_SECRET;
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, accessSecret);
            amazonSQS = AmazonSQSClientBuilder.standard()
                    .withRegion(regions)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                    .build();
        }
        return amazonSQS;
    }


    /**
     * 获取消息队列信息
     * @return
     */

    private static Queue getQueue() {
        GetQueueRequest request = new GetQueueRequest();
        request.sdkRequestConfig(getSdkRequestConfig(request));
        return OpenapiTemplate.openapi().getQueue(request).getQueue();
    }


    private static SdkRequestConfig getSdkRequestConfig(BaseRequest request) {
        return request.sdkRequestConfig().copyBuilder()
                .customHeader("Content-Type", "application/json")
                .customHeader("Access-Key-Id", Q7linkConstants.ACCESS_KEY_ID )
                .customHeader("Open-Id", Q7linkConstants.OPEN_ID)
                .build();
    }



//    public static Openapi openapi() {
//        if (openapi == null) {
//            String accessKey = Q7linkConstants.ACCESS_KEY_ID;
//            String accessSecret = Q7linkConstants.ACCESS_SECRET;
//            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, accessSecret);
//            openapi = Openapi.builder()
//                    .iamCredentials(new AWSStaticCredentialsProvider(awsCredentials))
//                    .build();
//        }
//        return openapi;
//    }

}
