package com.zzsn.knowbase.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzsn.knowbase.constant.Constants;
import com.zzsn.knowbase.entity.*;
import com.zzsn.knowbase.service.IKnowledgeService;
import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.service.KbKnowledgeProjectService;
import com.zzsn.knowbase.util.AuthUtil;
import com.zzsn.knowbase.util.ExcelExportUtil;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.util.tree.Node;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 *  知识
 * @Author: chenshiqiang
 * @Version: V1.0
 */
@Api(tags = "知识")
@RestController
@RequestMapping("/api/knowledge/user")
@Slf4j
public class KnowledgeUserController {
    @Autowired
    private IKnowledgeService knowledgeService;
    @Autowired
    private KbKnowledgeProjectService knowledgeProjectService;
    @Autowired
    private ILocalFileService localFileService;


    /**
     * 新增用户分组
     */
    @PostMapping(value = "/group/add")
    public Result<?> groupAdd(@RequestBody KbKnowledgeProject knowledgeProject) {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        if(StringUtils.isNotEmpty(knowledgeProject.getName())){
            knowledgeProject.setTypeName(knowledgeProject.getName());
        }
        if(StringUtils.isEmpty(knowledgeProject.getPid())||"0".equals(knowledgeProject.getPid())){
            //未指定时设置为用户根目录
            knowledgeProject.setPid(loginUser.getId());
            knowledgeProject.setFullPath(loginUser.getId());
        }else{
            knowledgeProject.setFullPath(knowledgeProjectService.getById(knowledgeProject.getPid()).getFullPath());
        }
        knowledgeProject.setHasChild("0");
        knowledgeProject.setCategory(Constants.SC_CATEGORY);
        knowledgeProject.setCreateTime(new Date());

        log.info("新增用户分组：{}", knowledgeProject);
        knowledgeProjectService.save(knowledgeProject);
        knowledgeProject.setFullPath(knowledgeProject.getFullPath() + "," + knowledgeProject.getId());
        knowledgeProjectService.updateById(knowledgeProject);
        return Result.OK("保存成功！");
    }
    /**
     * 查询用户分组
     */
    @GetMapping(value = "/group/list")
    public Result<?> groupList() {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        List<KbKnowledgeProject> list = knowledgeProjectService.listByUserId(loginUser.getId());
        List<Node> treeList = knowledgeProjectService.treeGroup(list,loginUser.getId());
        return Result.OK(treeList);
    }
    /**
     * 查询用户分组
     */
    @PutMapping(value = "/group/edit")
    public Result<?> groupEdit(@RequestBody KbKnowledgeProject knowledgeProject) {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        if(StringUtils.isNotEmpty(knowledgeProject.getName())){
            knowledgeProject.setTypeName(knowledgeProject.getName());
        }
        KbKnowledgeProject byId = knowledgeProjectService.getById(knowledgeProject.getId());
        if(byId == null || !byId.getFullPath().contains(loginUser.getId())){
            return Result.error("分类不存在！");
        }
        //编辑仅允许修改分组名
        byId.setTypeName(knowledgeProject.getTypeName());
        log.info("编辑用户分组：{}", byId);
        knowledgeProjectService.updateById(byId);
        return Result.OK("编辑成功！");
    }
    /**
     * 删除用户分组
     */
    @DeleteMapping(value = "/group/delete")
    public Result<?> groupDelete(String id) {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        KbKnowledgeProject byId = knowledgeProjectService.getById(id);
        if(byId == null || !byId.getFullPath().contains(loginUser.getId())){
            return Result.error("分类不存在！");
        }
        log.info("删除用户分组：{}", byId);
        knowledgeProjectService.removeById(id);
        return Result.OK("删除成功！");
    }
    /**
     * 分页列表查询
     */
    @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,
                                   HttpServletRequest request) {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        knowledgeParam.setKbKnowledgeId(Constants.SC_USER);
        knowledgeParam.setTypeIds(Constants.SC_CATEGORY);
        knowledgeParam.setUserId(loginUser.getId());
        IPage<KnowledgeVO> pageList = knowledgeService.queryPageList(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) {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        knowledge.setUserId(loginUser.getId());
        //对应个人素材知识库
        knowledge.setKbKnowledgeId(Constants.SC_USER);
        knowledge.setTypeId(Constants.SC_CATEGORY);
        if(StringUtils.isEmpty(knowledge.getKnowledgeProjectId())){
            //未设置分组时使用用户id作为分组
            knowledge.setKnowledgeProjectId(loginUser.getId());
        }
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);

        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Result<List<KnowFile>> result = localFileService.upload(fileMap);
        log.info("upload result:{}", result);
        if (!Integer.valueOf("200").equals(result.getCode())) {
            return Result.error(result.getMessage());
        }
        List<KnowFile> resultList = result.getResult();
        KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo();
        knowledge.setImportData(0);
        CompletableFuture.runAsync(() -> this.add(resultList, knowledge, userInfo));
        return Result.OK("添加成功！");
    }

    private void add(List<KnowFile> resultList, Knowledge knowledge, KbAuthorizedUser userInfo) {

        if (null == resultList || resultList.isEmpty()) {
            return;
        }
        for (KnowFile knowFileResult : resultList) {
            knowledge.setId(null);
            knowledge.setTitle(null);
            knowledgeService.addKnowledge(knowFileResult, 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
     * @return
     */
    @PostMapping(value = "/delete")
    public Result<?> delete(@RequestBody DeleteParam deleteParam) {
        knowledgeService.deleteKnowledge(deleteParam.getKnowledgeList());
        return Result.OK("删除成功!");
    }

    /**
     * 通过excel导入
     *
     * @return
     */
    @RequestMapping(value = "/importInfo", method = RequestMethod.POST)
    public Result<?> importInfo(HttpServletRequest request, HttpServletResponse response) {
        LoginUser loginUser = AuthUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("用户未登录！");
        }
        return knowledgeService.doImportInfo(request, loginUser.getId());
    }

    /**
     * 下载导入模板
     */
    @RequestMapping(value = "/download")
    public Result<?> download(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<KnowledgeUserExcel> dataList = new ArrayList<>();
            String filePath = Constants.TEMP_FILES_DIR + "template.xlsx";
            ExcelExportUtil.writeExcelFront(dataList, "素材导入模板", filePath, KnowledgeUserExcel.class);
            ExcelExportUtil.download(response, filePath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();
    }

}