package cn.com.poc.appbuilder.rest.impl;

import cn.com.poc.appbuilder.aggregation.AppBuilderService;
import cn.com.poc.appbuilder.dto.AppBuilderCommunicationDto;
import cn.com.poc.appbuilder.model.BizAppbuilderConversationModel;
import cn.com.poc.appbuilder.rest.AppBuilderRest;
import cn.com.poc.appbuilder.service.BizAppbuilderConversationService;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.SSEUtil;
import cn.com.poc.common.utils.StringUtils;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;
import com.baidubce.appbuilder.model.appbuilderclient.Event;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class AppBuilderRestImpl implements AppBuilderRest {

    private final Logger logger = LoggerFactory.getLogger(AppBuilderRest.class);

    @Resource
    private AppBuilderService appBuilderService;

    @Resource
    private BizAppbuilderConversationService bizAppbuilderConversationService;


    @Override
    public String conversation(String appId) throws Exception {
        Assert.notNull(appId, "参数不能为空");
        String conversationId = appBuilderService.conversation(appId);
        //持久化
        BizAppbuilderConversationModel model = new BizAppbuilderConversationModel();
        model.setAppId(appId);
        model.setConversationId(conversationId);
        bizAppbuilderConversationService.save(model);
        return conversationId;
    }

    @Override
    public String upload(String appId, String conversationId, MultipartFile file) throws Exception {
        Assert.notNull(appId, "参数不能为空");
        Assert.notNull(conversationId, "参数不能为空");
        return appBuilderService.upload(appId, conversationId, file);
    }

    @Override
    public List<String> getCurrentUserConversationIds() {
        return appBuilderService.getCurrentUserConversationIds();
    }

    @Override
    public void communication(AppBuilderCommunicationDto dto, HttpServletResponse httpServletResponse) throws IOException {
        Assert.notNull(dto, "参数不能为空");
        Assert.notBlank(dto.getQuery(), "对话内容不能为空");
        Assert.notBlank(dto.getConversationId(), "对话ID不能为空");
        SSEUtil sseUtil = new SSEUtil();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String conversationId = dto.getConversationId();
            String query = dto.getQuery();
            List<String> fileIds = CollectionUtils.isEmpty(dto.getFileIds()) ? new ArrayList<String>(0) : dto.getFileIds();
            AppBuilderClientIterator iterator = appBuilderService.communication(conversationId, query, fileIds, dto.getStream());
            while (iterator.hasNext()) {
                AppBuilderClientResult res = iterator.next();
                sseUtil.send(JsonUtils.serialize(res));
                if (ArrayUtils.isNotEmpty(res.getEvents())) {
                    Event event = res.getEvents()[0];
                    String eventType = event.getEventType();
                    if ("chatflow".equals(eventType)) {
                        Map<String, Object> detail = event.getDetail();
                        if (detail.containsKey("message")) {
                            String mess = detail.get("message").toString();
                            stringBuilder.append(mess);
                        }
                    }
                } else if (StringUtils.isNotEmpty(res.getAnswer())) {
                    stringBuilder.append(res.getAnswer());
                }
            }
        } catch (Exception e) {
            logger.error("appBuilder#communication对话失败，错误信息:{},入参:{}", e.getLocalizedMessage(), dto);
            sseUtil.completeByError("对话失败: " + e.getMessage());
        }finally {

        }
    }


}
