package com.yice.webadmin.app.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.page.PageMethod;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yice.common.core.annotation.MyRequestBody;
import com.yice.common.core.constant.ErrorCodeEnum;
import com.yice.common.core.object.*;
import com.yice.common.core.util.MyCommonUtil;
import com.yice.common.core.util.MyModelUtil;
import com.yice.common.core.util.MyPageUtil;
import com.yice.common.log.annotation.OperationLog;
import com.yice.common.log.model.constant.SysOperationLogType;
import com.yice.webadmin.app.config.KnowledgeConfig;
import com.yice.webadmin.app.dto.KnowledgeManageDto;
import com.yice.webadmin.app.model.KnowledgeManage;
import com.yice.webadmin.app.model.KnowledgeUser;
import com.yice.webadmin.app.service.KnowledgeManageService;
import com.yice.webadmin.app.service.ProxyPythonService;
import com.yice.webadmin.app.vo.KnowledgeManageVo;
import com.yice.webadmin.upms.dto.SysUserDto;
import com.yice.webadmin.upms.model.SysUser;
import com.yice.webadmin.upms.vo.SysUserVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 知识库管理操作控制器类。
 *
 * @author linking
 * @date 2023-04-13
 */
@Api(tags = "知识库管理管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/knowledgeManage")
public class KnowledgeManageController {

    @Autowired
    private KnowledgeManageService knowledgeManageService;
    @Autowired
    private ProxyPythonService proxyPythonService;
    @Autowired
    private KnowledgeConfig knowledgeConfig;

    /**
     * 新增知识库管理数据。
     *
     * @param knowledgeManageDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"knowledgeManageDto.knowledgeId", "knowledgeManageDto.searchString"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<KnowledgeManage> add(@MyRequestBody KnowledgeManageDto knowledgeManageDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(knowledgeManageDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        String requestBody = "{\n" + "  \"knowledge_base_name\": \"" + knowledgeManageDto.getKnowledgeName() + "\",\n" + "  \"vector_store_type\": \"faiss\",\n" + "  \"embed_model\": \"m3e-base\"\n" + "}";
        try {
            String result = proxyPythonService.predictPost(knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getCreate(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            if (code != null && code == 200) {
                KnowledgeManage knowledgeManage = MyModelUtil.copyTo(knowledgeManageDto, KnowledgeManage.class);
                KnowledgeManage reKnowledgeManage = knowledgeManageService.saveNew(knowledgeManage);
                return ResponseResult.success(reKnowledgeManage);
            } else {
                return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, null);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 为指定页面添加用户列表。该操作可同时给一批用户赋值页面，并在同一事务内完成。
     *
     * @param knowledgeId       知识库id。
     * @param userIdListString 逗号分隔的用户Id列表。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.ADD_M2M)
    @PostMapping("/addKnowledgeUser")
    public ResponseResult<Void> addKnowledgeUser(@MyRequestBody Long knowledgeId,
                                                 @MyRequestBody String userIdListString) {
        if (MyCommonUtil.existBlankArgument(knowledgeId, userIdListString)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        Set<Long> userIdSet = Arrays.stream(
                userIdListString.split(",")).map(Long::valueOf).collect(Collectors.toSet());
        KnowledgeUser knowledgeUser = null;
        List<KnowledgeUser> knowledgeUserList = new LinkedList<>();
        for (Long userId : userIdSet) {
            knowledgeUser = new KnowledgeUser(userId, knowledgeId);
            knowledgeUserList.add(knowledgeUser);
        }
        knowledgeManageService.addKnowledgeUserList(knowledgeUserList);
        return ResponseResult.success();
    }

    /**
     * 获取不包含指定面Id的用户列表。
     * 用户和面是多对多关系，当前接口将返回没有赋值指定PageId的用户列表。可用于给页面添加新用户。
     *
     * @param knowledgeId      知识库标识。
     * @param sysUserDtoFilter 用户过滤对象。
     * @param orderParam       排序参数。
     * @param pageParam        分页参数。
     * @return 应答结果对象，包含用户列表数据。
     */
    @PostMapping("/listNotInKnowledgeUser")
    public ResponseResult<MyPageData<SysUserVo>> listNotInKnowledgeUser(
            @MyRequestBody Long knowledgeId,
            @MyRequestBody SysUserDto sysUserDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (MyCommonUtil.existBlankArgument(knowledgeId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        SysUser filter = MyModelUtil.copyTo(sysUserDtoFilter, SysUser.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, SysUser.class);
        List<SysUser> userList = knowledgeManageService.getNotInSysUserListByKnowledgeId(knowledgeId, filter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(userList, SysUser.INSTANCE));
    }

    /**
     * 拥有指定页面的用户列表。
     *
     * @param knowledgeId      知识库标识。
     * @param sysUserDtoFilter 用户过滤对象。
     * @param orderParam       排序参数。
     * @param pageParam        分页参数。
     * @return 应答结果对象，包含用户列表数据。
     */
    @PostMapping("/listKnowledgeUser")
    public ResponseResult<MyPageData<SysUserVo>> listKnowledgeUser(
            @MyRequestBody Long knowledgeId,
            @MyRequestBody SysUserDto sysUserDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (MyCommonUtil.existBlankArgument(knowledgeId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        SysUser filter = MyModelUtil.copyTo(sysUserDtoFilter, SysUser.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, SysUser.class);
        List<SysUser> userList = knowledgeManageService.getSysUserListByKnowledgeId(knowledgeId, filter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(userList, SysUser.INSTANCE));
    }

    /**
     * 为指定用户移除指定页面。
     *
     * @param knowledgeId 知识库标识。
     * @param userId 指定用户主键Id。
     * @return 应答数据结果。
     */
    @OperationLog(type = SysOperationLogType.DELETE_M2M)
    @PostMapping("/deleteKnowledgeUser")
    public ResponseResult<Void> deleteKnowledgeUser(@MyRequestBody Long knowledgeId, @MyRequestBody Long userId) {
        if (MyCommonUtil.existBlankArgument(knowledgeId, userId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        if (!knowledgeManageService.removeKnowledgeUser(knowledgeId, userId)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的在线表单页面列表。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/load")
    public ResponseResult<List<KnowledgeManageVo>> load() {
        KnowledgeManage knowledgeManageFilter = new KnowledgeManage();
        TokenData tokenData = TokenData.takeFromRequest();
        knowledgeManageFilter.setCreateUserId(BooleanUtil.isTrue(tokenData.getIsAdmin()) ? null : tokenData.getUserId());
        List<KnowledgeManage> knowledgeManageList = knowledgeManageService.loadKnowledgeUserList(knowledgeManageFilter, "create_time");
        return ResponseResult.success(KnowledgeManage.INSTANCE.fromModelList(knowledgeManageList));
    }

    /**
     * 更新知识库管理数据。
     *
     * @param knowledgeManageDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {"knowledgeManageDto.searchString"})
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<KnowledgeManage> update(@MyRequestBody KnowledgeManageDto knowledgeManageDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(knowledgeManageDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        KnowledgeManage knowledgeManage = MyModelUtil.copyTo(knowledgeManageDto, KnowledgeManage.class);
        KnowledgeManage originalKnowledgeManage = knowledgeManageService.getById(knowledgeManage.getKnowledgeId());
        if (originalKnowledgeManage == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!knowledgeManageService.update(knowledgeManage, originalKnowledgeManage)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success(originalKnowledgeManage);
    }
    /**
     * 删除知识库管理数据。
     *
     * @param knowledgeId 删除对象主键Id。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<String> delete(@MyRequestBody Long knowledgeId) {
        if (MyCommonUtil.existBlankArgument(knowledgeId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(knowledgeId);
    }

    /**
     * 删除知识库管理数据。
     *
     * @param knowledgeName 删除知识库名称。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/deleteByName")
    public ResponseResult<String> deleteByName(@MyRequestBody String knowledgeName) {
        if (MyCommonUtil.existBlankArgument(knowledgeName)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDeleteByName(knowledgeName);
    }

    /**
     * 搜索知识库数据。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/searchDocs")
    public ResponseResult<String> searchDocs(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getSearchDocs(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 直接更新知识库文档。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/updateDocsById")
    public ResponseResult<String> updateDocsById(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getUpdateDocsById(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 直接删除知识库文档片段。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/deleteDocsById")
    public ResponseResult<String> deleteDocsById(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getDeleteDocsById(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除知识库指定文件。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/deleteDocs")
    public ResponseResult<String> deleteDocs(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getDeleteDocs(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新现有文件到知识库。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/updateDocs")
    public ResponseResult<String> updateDocs(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getUpdateDocs(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传文件到知识库，并进行量化。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/uploadDocs")
    public ResponseResult<String> uploadDocs(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPostForFile(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getUploadDocs(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取知识库指定源文件的分段切片文档
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/listDocs")
    public ResponseResult<String> listDocs(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        String result = null;
        try {
            result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getListDocs(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            } else {
                return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据content中文档重建向量库，流式输出处理进度。
     *
     * @param requestBody 请求对象。
     * @return 应答结果对象。
     */
    @PostMapping("/recreate")
    public ResponseResult<String> recreate(@RequestBody String requestBody) {
        if (MyCommonUtil.existBlankArgument(requestBody)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        try {
            String result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + knowledgeConfig.getRecreate(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private ResponseResult<String> doDeleteByName(String knowledgeName) {
        try {
            String result = this.proxyPythonService.predictPost(this.knowledgeConfig.getKnowledgeInterface() + this.knowledgeConfig.getDelete(), "\"" + knowledgeName + "\"");
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(msg);
            } else {
                return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 列出符合过滤条件的知识库管理列表。
     *
     * @param knowledgeManageDtoFilter 过滤对象。
     * @param orderParam               排序参数。
     * @param pageParam                分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/list")
    public ResponseResult<MyPageData<KnowledgeManageVo>> list(@MyRequestBody KnowledgeManageDto knowledgeManageDtoFilter, @MyRequestBody MyOrderParam orderParam, @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        KnowledgeManage knowledgeManageFilter = MyModelUtil.copyTo(knowledgeManageDtoFilter, KnowledgeManage.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, KnowledgeManage.class);
        List<KnowledgeManage> knowledgeManageList = knowledgeManageService.getKnowledgeManageListWithRelation(knowledgeManageFilter, orderBy);
        List<KnowledgeManage> reKnowledgeManageList = new ArrayList<>();
        try {
            String result = this.proxyPythonService.predictGet(this.knowledgeConfig.getKnowledgeInterface() + this.knowledgeConfig.getList(), "");
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            JSONArray jsonArray = jo.getJSONArray("data");
            if (code != null && code == 200) {
                for (KnowledgeManage knowledgeManage : knowledgeManageList) {
                    for (Object jsonObject : jsonArray) {
                        if (knowledgeManage.getKnowledgeName().equals(String.valueOf(jsonObject))) {
                            reKnowledgeManageList.add(knowledgeManage);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.success(MyPageUtil.makeResponseData(reKnowledgeManageList, KnowledgeManage.INSTANCE));
    }

    /**
     * 列出符合过滤条件的知识库管理列表。
     *
     * @param knowledgeManageDtoFilter 过滤对象。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/listForTree")
    public ResponseResult<List<KnowledgeManageVo>> listForTree(@MyRequestBody KnowledgeManageDto knowledgeManageDtoFilter) {
        KnowledgeManage knowledgeManageFilter = MyModelUtil.copyTo(knowledgeManageDtoFilter, KnowledgeManage.class);
        List<KnowledgeManage> knowledgeManageList = knowledgeManageService.getKnowledgeManageListWithRelation(knowledgeManageFilter, "");
        List<KnowledgeManage> reKnowledgeManageList = new ArrayList<>();
        try {
            String result = this.proxyPythonService.predictGet(this.knowledgeConfig.getKnowledgeInterface() + this.knowledgeConfig.getList(), "");
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            JSONArray jsonArray = jo.getJSONArray("data");
            if (code != null && code == 200) {
                for (KnowledgeManage knowledgeManage : knowledgeManageList) {
                    for (Object jsonObject : jsonArray) {
                        if (knowledgeManage.getKnowledgeName().equals(String.valueOf(jsonObject))) {
                            reKnowledgeManageList.add(knowledgeManage);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.success(KnowledgeManage.INSTANCE.fromModelList(reKnowledgeManageList));
    }

    /**
     * 查看指定知识库管理对象详情。
     *
     * @param knowledgeId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<KnowledgeManageVo> view(@RequestParam Long knowledgeId) {
        KnowledgeManage knowledgeManage = knowledgeManageService.getByIdWithRelation(knowledgeId, MyRelationParam.full());
        if (knowledgeManage == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        KnowledgeManageVo knowledgeManageVo = KnowledgeManage.INSTANCE.fromModel(knowledgeManage);
        return ResponseResult.success(knowledgeManageVo);
    }

    /**
     * 获取知识库内的文件列表。
     *
     * @param knowledgeName 知识库名称。
     */
    @GetMapping("/listFiles")
    public ResponseResult<String> listFiles(@RequestParam String knowledgeName) {
        String result = null;
        String requestBody = "?knowledge_base_name=" + knowledgeName;
        try {
            result = this.proxyPythonService.predictGet(this.knowledgeConfig.getKnowledgeInterface() + this.knowledgeConfig.getListFiles(), requestBody);
            JSONObject jo = JSON.parseObject(result);
            Integer code = jo.getIntValue("code");
            String msg = jo.getString("msg");
            String data = jo.getString("data");
            if (code != null && code == 200) {
                return ResponseResult.success(data);
            }
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private ResponseResult<String> doDelete(Long knowledgeId) {
        String errorMessage;
        // 验证关联Id的数据合法性
        KnowledgeManage originalKnowledgeManage = knowledgeManageService.getById(knowledgeId);
        if (originalKnowledgeManage == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!knowledgeManageService.remove(knowledgeId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return this.doDeleteByName(originalKnowledgeManage.getKnowledgeName());
    }
}
