package com.mortals.xhx.webflux.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mortals.xhx.webflux.common.JsonUtils;
import com.mortals.xhx.webflux.enums.FlowChatSceneEnum;
import com.mortals.xhx.webflux.req.MessagesItem;
import com.mortals.xhx.webflux.req.RobotTransReq;
import com.mortals.xhx.webflux.template.AbstractFlowChatTemplate;
import com.mortals.xhx.webflux.factory.FLowChatRequest;
import com.mortals.xhx.webflux.factory.FlowChatContext;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("baseChatService")
public class BaseChatService extends AbstractFlowChatTemplate {


    @Value("${chat.streamChatUrl:''}")
    private String streamChatUrl;

    @Value("${chat.auth-head:''}")
    private String authHead;

    @Value("${chat.auth-value:''}")
    private String authValue;


    private Integer num = 0;


    @Override
    public FlowChatSceneEnum getFlowChatEnum() {
        return FlowChatSceneEnum.BASE_CHAT;
    }


    @Override
    public String onNext(String data, FlowChatContext context) {
        //return parseFastApiResp(data, context);
        return parseDifyApiResp(data, context);
    }

    @Nullable
    private String parseFastApiResp(String data, FlowChatContext context) {
        if (StrUtil.equals("[DONE]", data)) {//[DONE]是消息结束标识
            return null;
        }
        // 解析响应数据项
        JSONObject bodyJson = JSONObject.parseObject(data);
        if (bodyJson == null) {
            return data;
        }
        JSONArray choices = bodyJson.getJSONArray("choices");
        bodyJson.put("id", context.getMsgId());
        bodyJson.put("created", new Date().getTime());
        if (choices != null && choices.size() > 0) {
            JSONObject jsonObject = choices.getJSONObject(0);
            JSONObject delta = jsonObject.getJSONObject("delta");
            String role = delta.getString("role");

            delta.put("role", "");
            String content = delta.getString("content");
            if ("assistant".equals(role)) {
                context.getAnswer().append(content);
            }

            String finish_reason = jsonObject.getString("finish_reason");
            if ("stop".equals(finish_reason)) {
                delta.put("content", "");
                this.num = 0;
            } else {
                jsonObject.put("finish_reason", null);
            }

        }

        return bodyJson.toJSONString(bodyJson, SerializerFeature.WriteMapNullValue);
    }

    @Nullable
    private String parseDifyApiResp(String data, FlowChatContext context) {
        if (StrUtil.equals("[DONE]", data)) {//[DONE]是消息结束标识
            return null;
        }
        // 解析响应数据项
        JSONObject bodyJson = JSONObject.parseObject(data);
        if (bodyJson == null) {
            return data;
        }

        String event = bodyJson.getString("event");
        JSONObject rspObj = new JSONObject();

        if ("message".equalsIgnoreCase(event)) {
            rspObj.put("model", "dify");
            rspObj.put("object", "");
            rspObj.put("id", context.getMsgId());
            rspObj.put("created", new Date().getTime());

            JSONArray choices = new JSONArray();
            JSONObject object = new JSONObject();

            object.put("finish_reason", null);
            object.put("index", 0);
            JSONObject delta = new JSONObject();
            delta.put("role", "");
            delta.put("content", bodyJson.getString("answer"));

            object.put("delta", delta);
            choices.add(object);
            rspObj.put("choices", choices);
            return rspObj.toJSONString(rspObj, SerializerFeature.WriteMapNullValue);
        }

        if ("message_end".equalsIgnoreCase(event)) {
            rspObj.put("model", "dify");
            rspObj.put("object", "");
            rspObj.put("id", context.getMsgId());
            rspObj.put("created", new Date().getTime());

            JSONArray choices = new JSONArray();
            JSONObject object = new JSONObject();

            object.put("finish_reason", "stop");
            object.put("index", 0);
            JSONObject delta = new JSONObject();
            delta.put("role", "");
            delta.put("content", bodyJson.getString("answer"));

            rspObj.put("delta", delta);
            choices.add(object);
            rspObj.put("choices", choices);

            this.num = 0;

            return rspObj.toJSONString(rspObj, SerializerFeature.WriteMapNullValue);
        }

        //{
        //    "created": 1742891327432,
        //    "model": "",
        //    "id": "683a65fd-8feb-4446-ad32-714c4785f667",
        //    "choices": [
        //        {
        //            "finish_reason": "stop",
        //            "delta": {
        //                "role": "",
        //                "content": ""
        //            },
        //            "index": 0
        //        }
        //    ],
        //    "object": ""
        //}

        return bodyJson.toJSONString(bodyJson, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public void completed(FlowChatContext context) {
        // 更新对话
        updateChatMsg(context);
    }

    @Override
    public void error(FlowChatContext context) {
        // 更新对话
        updateChatMsg(context);
    }

    @Override
    protected FLowChatRequest buildRequest(FlowChatContext context) {
        //fastgptapi
        // 封装参数
        // JSONObject params = buildFastApiJsonObject(context);
        //dify
        JSONObject params = buildDifyApiJsonObject(context);
        log.info("请求参数:{}", params.toJSONString());
        return FLowChatRequest.builder().url(streamChatUrl).jsonBody(params.toJSONString()).build();
    }

    private JSONObject buildDifyApiJsonObject(FlowChatContext context) {
        JSONObject params = new JSONObject();
        // 构建请求参数
        RobotTransReq robotTransReq = context.getRequestParam();
        //messageId
        String id = robotTransReq.getId();
        context.setMsgId(id);
        Boolean stream = robotTransReq.getStream();
        params.put("inputs", new JSONObject());
        params.put("response_mode", "streaming");
        params.put("conversation_id", "");
        params.put("user", robotTransReq.getDeviceId());
        params.put("files", new JSONArray());

        List<MessagesItem> messages = robotTransReq.getMessages();
        for (MessagesItem message : messages) {
            params.put("query", message.getContent());
        }

        return params;

    }

    @NotNull
    private JSONObject buildFastApiJsonObject(FlowChatContext context) {
        JSONObject params = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        // 构建请求参数
        RobotTransReq robotTransReq = context.getRequestParam();
        //messageId
        String id = robotTransReq.getId();
        context.setMsgId(id);
        Integer maxTokens = robotTransReq.getMaxTokens();
        String enterpriseId = robotTransReq.getEnterpriseId();
        Boolean stream = robotTransReq.getStream();
        List<MessagesItem> messages = robotTransReq.getMessages();
        for (MessagesItem message : messages) {
            JSONObject obj = new JSONObject();
            obj.put("role", message.getRole());
            obj.put("content", message.getContent());
            jsonArray.add(obj);
            params.put("messages", jsonArray);
        }

        params.put("chatId", id);
        params.put("stream", stream);
        params.put("detail", false);
        params.put("responseChatItemId", "my_responseChatItemId");
        JSONObject variables = new JSONObject();
        variables.put("uid", "asdfadsfasfd2323");
        variables.put("name", "robot");
        params.put("variables", variables);
        return params;
    }

    @Override
    protected HttpHeaders buildRequestHeaders(FlowChatContext context) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(authHead, authValue);
        return headers;
    }

    @Override
    protected void doPreRequest(FlowChatContext context) {
        String query = "";
        // 保存query
        super.saveChatMsg(context, query);
    }
}
