package com.ruoyi.cms.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cms.domain.ai.AiChatDetail;
import com.ruoyi.cms.domain.ai.AiChatHistory;
import com.ruoyi.cms.mapper.AiChatDetailMapper;
import com.ruoyi.cms.mapper.AiChatHistoryMapper;
import com.ruoyi.cms.service.AiChatHistoryService;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AiChatHistoryServiceImpl extends ServiceImpl<AiChatHistoryMapper, AiChatHistory> implements AiChatHistoryService {

    @Autowired
    private AiChatHistoryMapper aiChatHistoryMapper;
    @Autowired
    private AiChatDetailMapper aiChatDetailMapper;

    @Override
    public JSONObject getList(AiChatHistory aiChatHistory) {
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if(Objects.isNull(aiChatHistory.getUserId())){
            try {
                aiChatHistory.setUserId(SiteSecurityUtils.getUserId());
            }catch (Exception e){
                object.put("list", jsonArray);
                return object;
            }
        }
        List<AiChatHistory> list = aiChatHistoryMapper.getList(aiChatHistory);
        if(list!=null&&!list.isEmpty()){
            JSONObject jsonObject1 = new JSONObject();
            for(AiChatHistory history:list){
                jsonObject1 = JSONObject.parseObject(JSONObject.toJSONString(history));
                jsonArray.add(jsonObject1);
            }
        }
        object.put("list", jsonArray);
        return object;
    }

    @Override
    public void saveChatHistory(AiChatHistory aiChatHistory) {
        try {
            AiChatHistory history = new AiChatHistory();
            history.setChatId(aiChatHistory.getChatId());
            List<AiChatHistory> list = aiChatHistoryMapper.getList(history);
            if(list!=null&&!list.isEmpty()){
                history = list.get(0);
                history.setUpdateTime(new Date());
                aiChatHistoryMapper.updateById(history);
            }else{
                history.setTitle(aiChatHistory.getTitle());
                history.setUserId(aiChatHistory.getUserId());
                history.setAppId(aiChatHistory.getAppId());
                history.setDelFlag("0");
                history.setUpdateTime(new Date());
                aiChatHistoryMapper.insert(history);
            }
            AiChatDetail chatDetail = new AiChatDetail();
            chatDetail.setChatId(aiChatHistory.getChatId());
            chatDetail.setObj("Human");
            chatDetail.setTime(new Date());
            chatDetail.setDataId(IdUtils.fastSimpleUUID());
            chatDetail.setContent(aiChatHistory.getTitle());
            aiChatDetailMapper.insert(chatDetail);
            List<String> answerList = aiChatHistory.getAnswerStringList();
            if(answerList!=null&&!answerList.isEmpty()){
                chatDetail = new AiChatDetail();
                chatDetail.setChatId(aiChatHistory.getChatId());
                chatDetail.setObj("AI");
                chatDetail.setTime(new Date());
                chatDetail.setDataId(aiChatHistory.getDataId());
                chatDetail.setContent(String.join("",answerList));
                chatDetail.setDurationSeconds(aiChatHistory.getDurationSeconds());
                aiChatDetailMapper.insert(chatDetail);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public JSONObject getDetailList(String chatId) {
        JSONObject dataList = new JSONObject();
        JSONArray array = new JSONArray();
        AiChatDetail detail = new AiChatDetail();
        detail.setChatId(chatId);
        List<AiChatDetail> list = aiChatDetailMapper.getList(detail);
        if(list!=null&&!list.isEmpty()){
            JSONObject data = new JSONObject();
            JSONArray value = new JSONArray();
            JSONObject valueObject = new JSONObject();
            String dataId = "";
            List<String> contentList = new ArrayList<>();
            List<AiChatDetail> details = new ArrayList<>();
            for(AiChatDetail detail1:list){
                details = list.stream().filter(fi->fi.getDataId().equals(detail1.getDataId())).collect(Collectors.toList());
                if(details.size() > 1){
                    contentList = new ArrayList<>();
                    if(StringUtils.isNotEmpty(dataId)){
                        continue;
                    }
                    data = new JSONObject();
                    data.put("dataId", detail1.getDataId());
                    data.put("obj", detail1.getObj());
                    data.put("hideInUI",false);
                    data.put("customFeedbacks",new JSONArray());
                    data.put("time",detail1.getTime());
                    data.put("durationSeconds",detail1.getDurationSeconds());
                    value = new JSONArray();
                    dataId = detail1.getDataId();
                    for(AiChatDetail detail2:details){
                        if(detail2.getContent().contains("```")){
                            contentList.add(detail2.getContent());
                        }else{
                            if(contentList!=null&&!contentList.isEmpty()){
                                valueObject = new JSONObject();
                                valueObject.put("type","text");
                                valueObject.put("text",new JSONObject().fluentPut("content", String.join("",contentList)));
                                value.add(valueObject);
                            }

                            valueObject = new JSONObject();
                            valueObject.put("type","text");
                            valueObject.put("text",new JSONObject().fluentPut("content", detail2.getContent()));
                            value.add(valueObject);
                        }
                    }
                    data.put("value",value);
                    array.add(data);
                }else{
                    dataId = "";
                    data = new JSONObject();
                    data.put("dataId", detail1.getDataId());
                    data.put("obj", detail1.getObj());
                    data.put("hideInUI",false);
                    data.put("customFeedbacks",new JSONArray());
                    data.put("time",detail1.getTime());
                    if("AI".equals(detail1.getObj())){
                        data.put("durationSeconds",detail1.getDurationSeconds());
                    }
                    valueObject = new JSONObject();
                    valueObject.put("type","text");
                    valueObject.put("text",new JSONObject().fluentPut("content", detail1.getContent()));
                    value = new JSONArray();
                    value.add(valueObject);
                    data.put("value",value);
                    array.add(data);
                }
            }
        }
        dataList.put("list",array);
        return dataList;
    }

    @Override
    public JSONArray getChatHistoryData(String chatId) {
        JSONObject content = null;
        JSONArray data = new JSONArray();
        AiChatDetail detail = new AiChatDetail();
        detail.setChatId(chatId);
        List<AiChatDetail> list = aiChatDetailMapper.getList(detail);
        if(list!=null&&!list.isEmpty()){
            for(AiChatDetail d:list){
                content = new JSONObject();
                if("AI".equals(d.getObj())){
                    content.put("role","assistant");
                }else{
                    content.put("role","user");
                }
                content.put("content",d.getContent());
                data.add(content);
            }
        }
        return data;
    }
}
