package com.ai.da.service.impl;

import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.constant.CommonConstant;
import com.ai.da.common.context.UserContext;
import com.ai.da.common.enums.CollectionLevel1TypeEnum;
import com.ai.da.common.response.PageBaseResponse;
import com.ai.da.common.response.PageResponse;
import com.ai.da.common.response.Response;
import com.ai.da.common.security.jwt.JWTTokenHelper;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.*;
import com.ai.da.mapper.primary.entity.*;
import com.ai.da.model.dto.ChatHistoryDTO;
import com.ai.da.model.dto.ReceiveCollectionElement;
import com.ai.da.model.dto.ReceiveDesignParam;
import com.ai.da.model.enums.*;
import com.ai.da.model.vo.AuthPrincipalVo;
import com.ai.da.model.vo.UserLikeGroupVO;
import com.ai.da.python.PythonService;
import com.ai.da.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class LLMServiceImpl implements LLMService {

    @Resource
    private ChatMessageMapper chatMessageMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private PythonService pythonService;
    @Resource
    private WorkspaceMapper workspaceMapper;
    @Resource
    private SysFileService sysFileService;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private StyleMapper styleMapper;
    @Resource
    private WorkspaceRelStyleMapper workspaceRelStyleMapper;
    @Resource
    private JWTTokenHelper jwtTokenHelper;
    @Resource
    private DesignService designService;
    private final ExecutorService executor = Executors.newCachedThreadPool();
    @Resource
    private CollectionElementMapper collectionElementMapper;
    @Resource
    private CollectionElementRelModelMapper collectionElementRelModelMapper;
    @Value("${minio.bucketName.sysImage}")
    private String sysImage;
    @Resource
    private CreditsService creditsService;

    @Override
    public SseEmitter stream(String prompt, Long projectParamId, String fileUrl, List<String> imageUrlList, String token, Boolean enableThinking, String process) {
        SseEmitter emitter = new SseEmitter(0L); // 永不超时

        executor.submit(() -> {
            try {
                boolean validate = jwtTokenHelper.validateToken(token); //
                if (validate) {
                    AuthPrincipalVo principal = jwtTokenHelper.parserToUser(token);
                    Long accountId = principal.getId();
//                    String url = "http://18.167.251.121:10002/chat-stream";
                    String url = "http://10.1.1.240:1013/chat-stream";
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setRequestProperty("Content-Type", "application/json");
                    Long projectId = null;
                    if (null == projectParamId) {
                        Project project = new Project();
                        project.setCreateTime(LocalDateTime.now());
                        projectMapper.insert(project);
                        projectId = project.getId();
                    }else {
                        projectId = projectParamId;
                    }

                    JSONObject jsonBodyObject = new JSONObject();
                    jsonBodyObject.put("project_id", projectId.toString());
                    jsonBodyObject.put("role", "user");
                    jsonBodyObject.put("image", !CollectionUtils.isEmpty(imageUrlList) ? imageUrlList : new ArrayList<>()); // 可扩展
//                    jsonBodyObject.put("image", ""); // 可扩展
                    jsonBodyObject.put("file", !StringUtils.isEmpty(fileUrl) ? Collections.singletonList(fileUrl) : new ArrayList<>());
                    jsonBodyObject.put("message", prompt);
                    jsonBodyObject.put("enable_thinking", enableThinking);
                    jsonBodyObject.put("process", !StringUtils.isEmpty(process) ? process : "");
                    jsonBodyObject.put("is_create_project", false);

                    // 1. 存储用户输入
                    ChatMessage userMessage = new ChatMessage();
                    userMessage.setRole("user");
                    userMessage.setProjectId(projectId);
                    userMessage.setSeq(getNextSeq(projectId));
                    userMessage.setCreateTime(LocalDateTime.now());
                    userMessage.setContent(jsonBodyObject.toJSONString());
                    userMessage.setAccountId(accountId);
                    chatMessageMapper.insert(userMessage);

                    try (OutputStream os = conn.getOutputStream()) {
                        log.info(jsonBodyObject.toJSONString());
                        byte[] input = jsonBodyObject.toJSONString().getBytes(StandardCharsets.UTF_8);
                        os.write(input, 0, input.length);
                    }

                    // 2. 流式接收并累积内容
                    // 3. 存储系统回复
                    ChatMessage systemMessage = new ChatMessage();
                    systemMessage.setRole("system");
                    systemMessage.setIsImage(0);
                    systemMessage.setProjectId(projectId);
//                    systemMessage.setCreateTime(LocalDateTime.now());
//                    systemMessage.setContent(responseBuilder.toString());
                    systemMessage.setAccountId(accountId);
//                    chatMessageMapper.insert(systemMessage);
                    StringBuilder responseContentBuilder = new StringBuilder();
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            line = line.trim();
                            if (!line.isEmpty() && line.startsWith("data: ")) {
                                String jsonStr = line.substring(6);
                                log.info(jsonStr);
                                JSONObject json = JSON.parseObject(jsonStr);
                                String status = json.getString("status");
                                if (!StringUtils.isEmpty(status)) {
                                    String content = json.getString("content");
                                    // 结束标识
                                    if ("[DONE]".equals(status)) {
                                        break;
                                    }else if ("[RUNNING]".equals(status)) {
                                        if (content.startsWith("\n[TOOL_CALL]") || content.startsWith("\n[TOOL_RESPONSE]")) {
                                            // 不发送不存储
                                        }else {
                                            responseContentBuilder.append(content);
                                            emitter.send(json.toJSONString());
                                        }
                                    }else {
                                        if (responseContentBuilder.length() != 0) {
                                            systemMessage.setSeq(getNextSeq(projectId));
                                            systemMessage.setCreateTime(LocalDateTime.now());
                                            systemMessage.setContent(responseContentBuilder.toString());
                                            chatMessageMapper.insert(systemMessage);
                                            systemMessage.setId(null);
                                            responseContentBuilder = new StringBuilder();
                                        }
                                        JSONObject toolsData = json.getJSONObject("tools_data");
                                        if (Objects.nonNull(toolsData) && !status.equals("[DESIGN_SIGNAL]") && !status.equals("[PROJECT_CREATE_SIGNAL]")) {
                                            boolean color = true;
                                            ReceiveDesignParam receiveDesignParam = JSONObject.parseObject(JSONObject.toJSONString(toolsData), ReceiveDesignParam.class);
                                            receiveDesignParam.setProjectId(projectId);
                                            designService.receiveDesignParams(receiveDesignParam);
                                            for (ReceiveCollectionElement receiveCollectionElement : receiveDesignParam.getReceiveCollectionElementList()) {
                                                if (!StringUtils.isEmpty(receiveCollectionElement.getUrl())) {
                                                    color = false;
                                                    receiveCollectionElement.setMinioUrl(minioUtil.getPreSignedUrl(receiveCollectionElement.getUrl(), 24 * 60));
                                                }
                                            }
                                            String jsonString = JSONObject.toJSONString(receiveDesignParam);
                                            json.put("tools_data", jsonString);
                                            ChatMessage systemImage = new ChatMessage();
                                            systemImage.setRole("system");
                                            if (color) {
                                                systemImage.setIsImage(1);
                                            }else {
                                                systemImage.setIsImage(2);
                                            }
                                            systemImage.setProjectId(projectId);
                                            systemImage.setSeq(getNextSeq(projectId));
                                            systemImage.setCreateTime(LocalDateTime.now());
                                            systemImage.setContent(JSONObject.toJSONString(receiveDesignParam.getReceiveCollectionElementList()));
                                            systemImage.setAccountId(accountId);
                                            chatMessageMapper.insert(systemImage);
                                        }

                                        emitter.send(json.toJSONString());
                                    }
                                }
                            }
                        }
                        if (responseContentBuilder.length() != 0) {
                            systemMessage.setSeq(getNextSeq(projectId));
                            systemMessage.setCreateTime(LocalDateTime.now());
                            systemMessage.setContent(responseContentBuilder.toString());
                            chatMessageMapper.insert(systemMessage);
                        }
                    }
                }

                emitter.complete();
            } catch (Exception e) {
                log.info("走进异常");
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

    @Override
    public SseEmitter streamNew(String prompt, Long projectParamId, String fileUrl, List<String> imageUrlList, String token, Boolean enableThinking, String process) {
        SseEmitter emitter = new SseEmitter(0L); // 永不超时
        List<String> designTools = Arrays.asList("moodboard", "printboard", /*"generate_color_code", */"sketchboard", "colorboard");

        executor.submit(() -> {
            try {
                boolean validate = jwtTokenHelper.validateToken(token);
//                boolean validate = true;
                if (validate) {
                    AuthPrincipalVo principal = jwtTokenHelper.parserToUser(token);
                    Long accountId = principal.getId();
//                    String url = "http://18.167.251.121:10002/api/chat_stream";
                    String url = "http://18.167.251.121:2011/api/chat_stream";
//                    String url = "http://10.1.1.240:1013/chat-stream";
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setRequestProperty("Content-Type", "application/json");
                    Long projectId = null;
                    if (null == projectParamId) {
                        Project project = new Project();
                        project.setAccountId(accountId);
                        project.setCreateTime(LocalDateTime.now());
                        projectMapper.insert(project);
                        projectId = project.getId();
                    }else {
                        projectId = projectParamId;
                    }

                    JSONObject jsonBodyObject = new JSONObject();
                    jsonBodyObject.put("project_id", projectId.toString());
                    jsonBodyObject.put("role", "user");
                    jsonBodyObject.put("image", !CollectionUtils.isEmpty(imageUrlList) ? imageUrlList : new ArrayList<>()); // 可扩展
//                    jsonBodyObject.put("image", ""); // 可扩展
                    jsonBodyObject.put("file", !StringUtils.isEmpty(fileUrl) ? Collections.singletonList(fileUrl) : new ArrayList<>());
                    jsonBodyObject.put("message", prompt);
                    jsonBodyObject.put("enable_thinking", enableThinking);
                    jsonBodyObject.put("process", !StringUtils.isEmpty(process) ? process : "");
                    jsonBodyObject.put("is_create_project", false);

                    // 1. 存储用户输入
                    ChatMessage userMessage = new ChatMessage();
                    userMessage.setRole("user");
                    userMessage.setProjectId(projectId);
                    userMessage.setSeq(getNextSeq(projectId));
                    userMessage.setCreateTime(LocalDateTime.now());
                    userMessage.setContent(jsonBodyObject.toJSONString());
                    userMessage.setAccountId(accountId);
                    chatMessageMapper.insert(userMessage);

                    try (OutputStream os = conn.getOutputStream()) {
                        log.info(jsonBodyObject.toJSONString());
                        byte[] input = jsonBodyObject.toJSONString().getBytes(StandardCharsets.UTF_8);
                        os.write(input, 0, input.length);
                    }

                    // 2. 流式接收并累积内容
                    // 3. 存储系统回复
                    ChatMessage systemMessage = new ChatMessage();
                    systemMessage.setRole("system");
                    systemMessage.setIsImage(0);
                    systemMessage.setProjectId(projectId);
                    systemMessage.setAccountId(accountId);
                    StringBuilder responseContentBuilder = new StringBuilder();
                    String contentType = "";
                    BigDecimal totalTokenUsage = BigDecimal.ZERO;
                    // 需要存input_token  output_token reasoning_tokens total_cost
                    Long inputToken = 0L;
                    Long outputToken = 0L;
                    Long reasoningToken = 0L;
                    String totalCost = "0";
                    boolean tokenUsageFlag = false;

                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            line = line.trim();
                            if (!line.isEmpty() && line.startsWith("data: ")) {
                                String jsonStr = line.substring(12);
                                log.info(jsonStr);
                                JSONObject json = JSON.parseObject(jsonStr);
                                String type = json.getString("type");
                                if (!StringUtils.isEmpty(type)) {
                                    String content = json.getString("content");
                                    // 结束标识
                                    if ("done".equals(type)) {
                                        break;
                                    }
                                    if ("text".equals(type) || "think".equals(type)) {
                                        if (StringUtils.isEmpty(contentType) || !contentType.equals(type)) {
                                            if ("text".equals(type)) {
                                                contentType = "text";
                                                responseContentBuilder.append("[TEXT]");
                                            }else {
                                                contentType = "think";
                                                responseContentBuilder.append("[THINK]");
                                            }
//                                            systemMessage.setSeq(getNextSeq(projectId));
//                                            systemMessage.setCreateTime(LocalDateTime.now());
//                                            systemMessage.setContent(responseContentBuilder.toString());
//                                            chatMessageMapper.insert(systemMessage);
//                                            systemMessage.setId(null);
//                                            responseContentBuilder = new StringBuilder();
//                                            contentType = type;
                                        }
                                        responseContentBuilder.append(content);
                                        emitter.send(json.toJSONString());
                                    }else if ("tools_response".equals(type)){
                                        if (responseContentBuilder.length() != 0) {
                                            systemMessage.setSeq(getNextSeq(projectId));
                                            systemMessage.setCreateTime(LocalDateTime.now());
                                            systemMessage.setContent(responseContentBuilder.toString());
                                            if (tokenUsageFlag){
                                                systemMessage.setInputTokens(inputToken);
                                                systemMessage.setOutputTokens(outputToken);
                                                systemMessage.setReasoningTokens(reasoningToken);
                                                systemMessage.setTotalCost(totalCost);
                                                tokenUsageFlag = false;
                                            }
                                            chatMessageMapper.insert(systemMessage);
                                            systemMessage.setId(null);
                                            responseContentBuilder = new StringBuilder();
                                            contentType = null;
                                        }
                                        String toolsName = json.getString("tools_name");
                                        JSONObject toolsData = json.getJSONObject("content");
                                        /*&& !toolsName.equals("design_control_signal")
                                                && !toolsName.equals("generate_project_info")*/
                                        if (Objects.nonNull(toolsName) && designTools.contains(toolsName)) {
                                            boolean color = true;
                                            ReceiveDesignParam receiveDesignParam = JSONObject.parseObject(JSONObject.toJSONString(toolsData), ReceiveDesignParam.class);
                                            receiveDesignParam.setProjectId(projectId);
                                            designService.receiveDesignParams(receiveDesignParam);
                                            String contentSave = JSONObject.toJSONString(receiveDesignParam.getReceiveCollectionElementList());
                                            for (ReceiveCollectionElement receiveCollectionElement : receiveDesignParam.getReceiveCollectionElementList()) {
                                                if (!StringUtils.isEmpty(receiveCollectionElement.getUrl())) {
                                                    color = false;
                                                    receiveCollectionElement.setMinioUrl(minioUtil.getPreSignedUrl(receiveCollectionElement.getUrl(), 24 * 60));
                                                }
                                            }
                                            String jsonString = JSONObject.toJSONString(receiveDesignParam);
                                            json.put("content", jsonString);
                                            ChatMessage systemImage = new ChatMessage();
                                            systemImage.setRole("system");
                                            if (color) {
                                                systemImage.setIsImage(1);
                                            }else {
                                                systemImage.setIsImage(2);
                                            }
                                            systemImage.setProjectId(projectId);
                                            systemImage.setSeq(getNextSeq(projectId));
                                            systemImage.setCreateTime(LocalDateTime.now());
                                            systemImage.setContent(contentSave);
                                            systemImage.setAccountId(accountId);
                                            if (tokenUsageFlag){
                                                systemImage.setInputTokens(inputToken);
                                                systemImage.setOutputTokens(outputToken);
                                                systemImage.setReasoningTokens(reasoningToken);
                                                systemImage.setTotalCost(totalCost);
                                                tokenUsageFlag = false;
                                            }
                                            chatMessageMapper.insert(systemImage);
                                        } else if (Objects.nonNull(toolsName) && toolsName.equals("search_sketch_img")) {
                                            json.put("content", processSearchSketchToolCon(projectId, toolsData));
                                        } else if (Objects.nonNull(toolsName)
                                                && toolsName.equals("update_project_info")) {
                                            updateProjectParams(projectId, toolsData);
                                        }
                                        emitter.send(json.toJSONString());
                                    }else if ("cost".equals(type)) {
                                        JSONObject contentObj = json.getJSONObject("content");
                                        log.info("token usage: {}", contentObj);
                                        inputToken = contentObj.getLong("input_tokens");
                                        outputToken = contentObj.getLong("output_tokens");
                                        reasoningToken = contentObj.getLong("reasoning_tokens");
                                        totalCost = contentObj.getString("total_cost");
                                        totalTokenUsage = totalTokenUsage.add(new BigDecimal(totalCost).divide(new BigDecimal("0.03"), 6, RoundingMode.CEILING));
                                        log.info("totalTokenUsage: {}", totalTokenUsage);
                                        tokenUsageFlag = true;
                                    }
                                }
                            }
                        }
                        if (responseContentBuilder.length() != 0) {
                            systemMessage.setSeq(getNextSeq(projectId));
                            systemMessage.setCreateTime(LocalDateTime.now());
                            systemMessage.setContent(responseContentBuilder.toString());
                            if (tokenUsageFlag){
                                systemMessage.setInputTokens(inputToken);
                                systemMessage.setOutputTokens(outputToken);
                                systemMessage.setReasoningTokens(reasoningToken);
                                systemMessage.setTotalCost(totalCost);
                            }
                            chatMessageMapper.insert(systemMessage);
                        }
                        // 扣积分
                        creditsService.tokenUsage(accountId, totalTokenUsage);
                    }
                }
                emitter.complete();
            } catch (Exception e) {
                log.info("走进异常: {}", e.getMessage());
                e.printStackTrace(); // 详细栈信息
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

    private String processSearchSketchToolCon(Long projectId, JSONObject content){
        //  content内容 "{\"sketch_list\": [\"\\\\female\\\\blouse\\\\blouse_645.jpg\", \"\\\\female\\\\dress\\\\0902004968.jpg\"]}"
        JSONArray sketchList = content.getJSONArray("sketch_list");
        if (sketchList.isEmpty()){
            return null;
        }
        ArrayList<ReceiveCollectionElement> dataList = new ArrayList<>();
        sketchList.forEach(sketch -> {
            ReceiveCollectionElement receiveCollectionElement = new ReceiveCollectionElement();
            String path = sketch.toString().replace("\\", "/");
            String minioPath = sysImage + "/images" + path;
            receiveCollectionElement.setUrl(minioPath);
            receiveCollectionElement.setLevel1Type(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName());
            receiveCollectionElement.setLevel2Type(path.split("/")[2]);
            receiveCollectionElement.setMinioUrl(minioUtil.getPreSignedUrl(minioPath, CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
            dataList.add(receiveCollectionElement);
        });
        ReceiveDesignParam receiveDesignParam = new ReceiveDesignParam();
        receiveDesignParam.setReceiveCollectionElementList(dataList);
        receiveDesignParam.setProjectId(projectId);
        designService.receiveDesignParams(receiveDesignParam);
        return JSONArray.toJSONString(receiveDesignParam);
    }

    @Resource
    private WorkspaceService workspaceService;
    private String updateProjectParams(Long projectId, JSONObject jsonObject){
        // 1. 获取 project_info 并转换为 List<Map<String, String>>
        List<Map<String, String>> projectInfoList = (List<Map<String, String>>) jsonObject.get("project_info");

        Long workspaceId = workspaceService.getByProjectId(projectId);
        if (Objects.isNull(workspaceId)){
            throw new BusinessException("未知projectId");
        }
        Workspace workspace = workspaceService.getBaseMapper().selectOne(new QueryWrapper<Workspace>().eq("project_id", projectId));
        if (!projectInfoList.isEmpty()){
            projectInfoList.forEach(info ->
                    info.forEach((key, value) -> {
                        switch (key){
                            case "project_name":
                                Project project = projectMapper.selectById(projectId);
                                project.setName(value);
                                project.setUpdateTime(LocalDateTime.now());
                                projectMapper.updateById(project);
                                break;
                            case "ageGroup":
                                workspace.setAgeGroup(value);
                                break;
                            case "gender":
                                workspace.setSex(value);
                                break;
                            case "position":
                                workspace.setPosition(value);
                                break;
                            case "style":
                                QueryWrapper<Style> qw = new QueryWrapper<>();
                                qw.lambda().eq(Style::getName, value);
                                Style style = styleMapper.selectOne(qw);
                                if (Objects.nonNull(style)) {
                                    WorkspaceRelStyle workspaceRelStyle = workspaceRelStyleMapper.selectOne(new QueryWrapper<WorkspaceRelStyle>().eq("workspace_id", workspaceId));
                                    workspaceRelStyle.setStyleId(style.getId());
                                    workspaceRelStyleMapper.updateById(workspaceRelStyle);
                                }
                                break;
                        }
                    })
            );
            workspaceMapper.updateById(workspace);
        }
        return null;
    }

    @Override
    public Long chatCreateProject(String prompt, String process, String fileUrl, List<String> imageUrlList) {
        AuthPrincipalVo userHolder = UserContext.getUserHolder();
        JSONObject jsonObject = pythonService.getProjectParam(prompt, fileUrl, imageUrlList, process);
        JSONObject data = jsonObject.getJSONObject("data");
        Project project = new Project();
        LocalDateTime now = LocalDateTime.now();
        project.setUpdateTime(now);
        project.setCreateTime(now);
        project.setAccountId(userHolder.getId());
        project.setName(data.getString("project_name"));
        project.setOriginal(1);
//        String process = data.getString("process");
//        if (StringUtils.isEmpty(process)) {
//            project.setProcess(DesignProcess.SERIES_DESIGN.name());
//        }else {
//            if (DesignProcess.isValidName(process)) {
//                project.setProcess(process);
//            }else {
//                project.setProcess(DesignProcess.SERIES_DESIGN.name());
//            }
//        }
        project.setProcess(process);
        projectMapper.insert(project);

        Workspace workspace = new Workspace();
        workspace.setAccountId(userHolder.getId());
        workspace.setCreateTime(now);
        String ageGroup = data.getString("ageGroup");
        if (StringUtils.isEmpty(ageGroup)) {
            workspace.setAgeGroup("Adult");
        }else {
            if (AgeGroup.isValidName(ageGroup)) {
                workspace.setAgeGroup(ageGroup);
            }else {
                workspace.setAgeGroup("Adult");
            }
        }
        String gender = data.getString("gender");
        if (StringUtils.isEmpty(gender)) {
            workspace.setSex("Female");
        }else {
            if (Sex.isValidName(gender)) {
                workspace.setSex(gender);
            }else {
                workspace.setSex("Female");
            }
        }
        String position = data.getString("position");
        if (process.equals(DesignProcess.SERIES_DESIGN.name())) {
            workspace.setPosition("Overall");
        }else {
            if (StringUtils.isEmpty(position)) {
                if (workspace.getSex().equals("Female")) {
                    workspace.setPosition(Position.BLOUSE.getValue());
                }else {
                    workspace.setPosition(Position.TOPS.getValue());
                }
            }else {
                if (Position.isValidName(position) && !position.equals(Position.OVERALL.getValue())) {
                    workspace.setPosition(position);
                }else {
                    if (workspace.getSex().equals("Female")) {
                        workspace.setPosition(Position.BLOUSE.getValue());
                    }else {
                        workspace.setPosition(Position.TOPS.getValue());
                    }
                }
            }
        }
        workspace.setSystemDesignerPercentage(30);
        workspace.setProjectId(project.getId());

        String style = data.getString("style");
        String styleName = null;
        if (StringUtils.isEmpty(style)) {
            styleName = StyleEnum.NEW_CHINESE.name();
        }else {
            if (StyleEnum.isValidName(style)) {
                styleName = style;
            }else {
                styleName = StyleEnum.NEW_CHINESE.name();
            }
        }

        SysFile sysFile = sysFileService.getOneBySex(styleName, workspace.getSex(), workspace.getAgeGroup());

        CollectionElement collectionElement = new CollectionElement();
        collectionElement.setAccountId(userHolder.getId());
        collectionElement.setProjectId(project.getId());
        collectionElement.setLevel1Type(CollectionLevel1TypeEnum.MODEL.getRealName());
        collectionElement.setLevel3Type(workspaceService.getProjectSexById(project.getId()));

//                    collectionElement.setLevel2Type(board.getLevel2Type());
        collectionElement.setName(sysFile.getName());
        collectionElement.setUrl(sysFile.getUrl());
//                    collectionElement.setHasPin(board.getIsPin());
        collectionElement.setMd5(sysFile.getMd5());
        collectionElement.setCreateDate(new Date());
        collectionElement.setHasPin((byte) 0);
        collectionElementMapper.insert(collectionElement);
        CollectionElementRelModel collectionElementRelModel = new CollectionElementRelModel();
        collectionElementRelModel.setCollectionElementId(collectionElement.getId());
        collectionElementRelModel.setRelationId(sysFile.getId());
        collectionElementRelModel.setRelationType("System");
        collectionElementRelModelMapper.insert(collectionElementRelModel);

        if (workspace.getSex().equals(Sex.FEMALE.getValue())) {
            workspace.setMannequinFemaleId(sysFile.getId());
            workspace.setMannequinFemaleType("System");
        }else {
            workspace.setMannequinMaleId(sysFile.getId());
            workspace.setMannequinMaleType("System");
        }

        workspaceMapper.insert(workspace);

        if (!StringUtils.isEmpty(styleName)) {
            QueryWrapper<Style> qw = new QueryWrapper<>();
            qw.lambda().eq(Style::getName, styleName);
            Style style1 = styleMapper.selectOne(qw);
            if (Objects.nonNull(style1)) {
                WorkspaceRelStyle rel = new WorkspaceRelStyle();
                rel.setWorkspaceId(workspace.getId());
                rel.setStyleId(style1.getId());
                workspaceRelStyleMapper.insert(rel);
            }
        }

        return project.getId();
    }

    @Override
    public List<String> uploadFile(MultipartFile file) {
        AuthPrincipalVo userHolder = UserContext.getUserHolder();
        String minioUrl = minioUtil.upload("chat-message", userHolder.getId() + "/" + file.getOriginalFilename(), file, null);
        String preSignedUrl = minioUtil.getPreSignedUrl(minioUrl, CommonConstant.MINIO_IMAGE_EXPIRE_TIME);
        List<String> result = new ArrayList<>();
        result.add(minioUrl);
        result.add(preSignedUrl);
        return result;
    }

    @Override
    public PageBaseResponse<ChatMessage> getChatHistory(ChatHistoryDTO chatHistoryDTO) {
        QueryWrapper<ChatMessage> qw = new QueryWrapper<>();
        qw.lambda().eq(ChatMessage::getProjectId, chatHistoryDTO.getProjectId());
        qw.lambda().orderByDesc(ChatMessage::getSeq);
        Page<ChatMessage> chatMessagePage = chatMessageMapper.selectPage(new Page<>(chatHistoryDTO.getPage(), chatHistoryDTO.getSize()), qw);
        for (ChatMessage record : chatMessagePage.getRecords()) {
            if (record.getIsImage() != null && record.getIsImage() == 2) {
                String content = record.getContent();
                List<ReceiveCollectionElement> list = JSONObject.parseArray(content, ReceiveCollectionElement.class);
                for (ReceiveCollectionElement receiveCollectionElement : list) {
                    if (!StringUtils.isEmpty(receiveCollectionElement.getUrl())) {
                        receiveCollectionElement.setMinioUrl(minioUtil.getPreSignedUrl(receiveCollectionElement.getUrl(), 24 * 60));
                    }
                }
                record.setContent(JSONObject.toJSONString(list));
            }
            if (record.getRole().equals("user")) {
                String content = record.getContent();
                JSONObject jsonObject = JSONObject.parseObject(content);
                JSONArray fileArray = jsonObject.getJSONArray("file");
                if (!CollectionUtils.isEmpty(fileArray)) {
                    for (int i = 0; i < fileArray.size(); i++) {
                        String string = fileArray.getString(i);
                        if (!StringUtils.isEmpty(string)) {
                            fileArray.set(i, minioUtil.getPreSignedUrl(string, 24 * 60));
                        }
                    }
                    jsonObject.put("file", fileArray);
                }

                JSONArray imageArray = jsonObject.getJSONArray("image");
                if (!CollectionUtils.isEmpty(imageArray)) {
                    for (int i = 0; i < imageArray.size(); i++) {
                        String string = imageArray.getString(i);
                        if (!StringUtils.isEmpty(string)) {
                            imageArray.set(i, minioUtil.getPreSignedUrl(string, 24 * 60));
                        }
                    }
                    jsonObject.put("image", imageArray);
                }
                record.setContent(JSONObject.toJSONString(jsonObject));
            }
        }
        return PageBaseResponse.success(chatMessagePage);
    }

    private int getNextSeq(Long projectId) {
        QueryWrapper<ChatMessage> qw = new QueryWrapper<>();
        qw.lambda().eq(ChatMessage::getProjectId, projectId);
        qw.lambda().orderByDesc(ChatMessage::getSeq);
        qw.last("limit 1");
        ChatMessage chatMessage = chatMessageMapper.selectOne(qw);
        if (Objects.nonNull(chatMessage)) {
            return chatMessage.getSeq() + 1;
        }
        return 1;
    }
}
