package com.qiuguo.iot.third.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiuguo.iot.base.constans.RedisConstans;
import com.qiuguo.iot.base.utils.WebClientUtils;

import com.qiuguo.iot.data.request.qwen.QGResponse;
import com.qiuguo.iot.data.request.qwen.TongYiCommunicationRest;
import com.qiuguo.iot.data.resp.qg.algorithm.QWenReplyRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;

@Slf4j
@RestController
@RequestMapping("/aaaa")
public class QWenService {

    @Resource
    private ReactiveStringRedisTemplate reactiveStringRedisTemplate;


    @PostMapping("/aaa")
    public Mono<QWenReplyRequest> communication(TongYiCommunicationRest rest) {
        ReactiveValueOperations<String, String> operations = reactiveStringRedisTemplate.opsForValue();
        return operations.get(RedisConstans.TY_QUEUE_LIST + rest.getOnlyId()).defaultIfEmpty("").flatMap(res -> {
            JSONArray objects = JSONArray.parseArray(res);
            List<TongYiCommunicationRest> list = new LinkedList<>();
            try {
                if (!ObjectUtils.isEmpty(objects)) {
                    list = JSONObject.parseArray(res, TongYiCommunicationRest.class);
                    if (rest.getIsWhiteList() == 0) {
                        //是白名单,插入头部
                        log.info("收到白名单对应信息,接收参数为:{}", rest);
                        list.add(0, rest);
                    }
                }
                //不是白名单插入尾部
                list.add(rest);
                operations.set(RedisConstans.TY_QUEUE_LIST + rest.getOnlyId(), JSONArray.toJSONString(list)).subscribe();
                //通知Redis让Redis进行消费
                HashMap<String, Object> map = new HashMap<>();
                map.put("task_type", "qwen");
                map.put("text", rest.getText());
                return httpTY(map);
            } catch (Exception e) {
                log.error("调用异常:");
                return Mono.just(new QWenReplyRequest());
            } finally {
                reactiveStringRedisTemplate.delete(RedisConstans.TY_QUEUE_LIST + rest.getOnlyId()).subscribe();
            }
        });
    }

    public static Mono<QWenReplyRequest> httpTY(HashMap<String, Object> map) {

        return WebClientUtils.post("http://192.168.8.211:5010/qg_human/qwen", new JSONObject(map)).flatMap(jsonObject -> {
            long time = new Date().getTime();
            QGResponse qgResponse = jsonObject.toJavaObject(QGResponse.class);
            QWenReplyRequest data = new QWenReplyRequest();
            log.info("发起TY请求,响应时间时间为:{}", new Date().getTime() - time);
            if (qgResponse.getStatusCode() == 0) {
                data = JSONObject.parseObject(qgResponse.getData().toString(), QWenReplyRequest.class);
                //成功
                log.info("通知成功:" + qgResponse.getData());
                data.setCode(200);
                return Mono.just(data);
            }
            //失败
            log.info("通知失败:" + map);
            data.setCode(500);
            return Mono.just(data);
        });
    }

    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("task_type", "qwen");
        map.put("text", "你好");
        try {
            httpTY(map);
        } catch (Exception e) {
            log.info("异常:{}", e);
        }

    }

}
