package com.zzsn.knowbase.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzsn.knowbase.entity.KbAuthorizedUser;
import com.zzsn.knowbase.entity.KnowFile;
import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.service.IKnowledgeService;
import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.util.DocUtil;
import com.zzsn.knowbase.util.HttpUtil;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.vo.IntelligentQaParam;
import com.zzsn.knowbase.vo.KnowledgeParam;
import com.zzsn.knowbase.vo.KnowledgeVO;
import com.zzsn.knowbase.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @Description: 知识
 * @Author: chenshiqiang
 * @Version: V1.0
 */
@Api(tags = "知识")
@RestController
@RequestMapping("/api/knowledge")
@Slf4j
public class KnowledgeController {
    @Autowired
    private IKnowledgeService knowledgeService;

    @Value("${python.intelligentQaUrl:}")
    private String intelligentQaUrl;

    @Autowired
    private ILocalFileService localFileService;

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/list")
    public Result<?> queryPageList(KnowledgeParam knowledgeParam,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "column", defaultValue = "common") String column,
                                   @RequestParam(name = "order", defaultValue = "desc") String order) {
        if (null != knowledgeParam.getSearchInfo() && Integer.valueOf("2").equals(knowledgeParam.getSearchScope())) {
            IPage<KnowledgeVO> pageList = knowledgeService.listFromPython(knowledgeParam, pageNo, pageSize, column, order);
            return Result.OK(pageList);
        }
        IPage<KnowledgeVO> pageList = knowledgeService.queryPageList(knowledgeParam, pageNo, pageSize, column, order);
        return Result.OK(pageList);
    }
    /**
     * 详情
     */
    @GetMapping(value = "/getById")
    public Result<?> getById(@RequestParam String id)  {
        KnowledgeVO knowledgeVO=knowledgeService.getById(id);
        return Result.OK(knowledgeVO);
    }

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/listFromPython")
    public Result<?> listFromPython(KnowledgeParam knowledgeParam,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(name = "column", defaultValue = "common") String column,
                                    @RequestParam(name = "order", defaultValue = "desc") String order) {
        IPage<KnowledgeVO> pageList = knowledgeService.listFromPython(knowledgeParam, pageNo, pageSize, column, order);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param knowledge
     * @return
     */
    @ApiOperation(value = "知识-添加", notes = "知识-添加")
    @PostMapping(value = "/uploadKnowledge")
    public Result<?> uploadKnowledge(HttpServletRequest request, Knowledge knowledge) {
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<Result<KnowFile>> resultList = localFileService.upload(fileMap);
        KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo();
        CompletableFuture.runAsync(()-> this.add(resultList,knowledge,userInfo));
        return Result.OK("添加成功！");
    }
    private void add(List<Result<KnowFile>> resultList, Knowledge knowledge,KbAuthorizedUser userInfo){

        if (null == resultList || resultList.isEmpty()) {
            return ;
        }
        for (Result<KnowFile> knowFileResult : resultList) {
            knowledge.setId(null);
            knowledgeService.addKnowledge(knowFileResult.getResult(), knowledge,userInfo);
        }
    }

    /**
     * 编辑
     *
     * @param knowledge
     * @return
     */
    @ApiOperation(value = "信息源组类别-编辑", notes = "信息源组类别-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Knowledge knowledge) {
        knowledgeService.updateKnowledge(knowledge);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "ids") String ids) {
        knowledgeService.deleteKnowledge(ids);
        return Result.OK("删除成功!");
    }

    /**
     * 文档解析
     */
    @GetMapping(value = "/parse")
    public Result<?> parse(@RequestParam(name = "filePath") String filePath) throws IOException {
        String s = DocUtil.docParseHtml(filePath);
        return Result.OK(s);
    }

    /**
     * 智能问答
     *
     * @param intelligentQaParam
     * @return
     */
    @PostMapping(value = "/IntelligentQa")
    public Result<?> intelligentQa(@RequestBody IntelligentQaParam intelligentQaParam) throws IOException {
        JSONObject params = new JSONObject();
        params.put("question", intelligentQaParam.getQuestion());
        params.put("knowledge_base_id", intelligentQaParam.getKbKnowledgeIds().split(","));
        String result = HttpUtil.doPost(intelligentQaUrl, params, 120000);
        if (!result.isEmpty()) {
            JSONObject jsonObject = JSON.parseObject(result);
            return Result.OK(jsonObject.get("result"));
        }
        return Result.error("响应失败");
    }
}
