package com.yeejoin.amos.knowledgebase.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.service.DocLibraryService;
import com.yeejoin.amos.knowledgebase.face.service.ESDocService;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelImportConfig;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 文档库管理
 * </p>
 *
 * @author 子杨
 * @since 2020-08-05
 */
@RestController
@TycloudResource(module = "knowledgebase", value = "doclibrary")
@RequestMapping(value = "/v1/doccontent/doclibrary")
@Api(tags = "knowledgebase-文档库管理")
public class DocLibraryResource {

    @Autowired
    private DocLibraryService docLibraryService;

    /**
     * 下拉式查询文档信息
     *
     * @param request            请求对象
     * @param offset             跳过条数
     * @param end                截止条数
     * @param filterByCollection 是否以收藏作为条件
     * @param createTimeLeft     创建时间左范围
     * @param createTimeRight    创建时间右范围
     * @return Page
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "下拉式查询文档信息")
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public ResponseModel<Page> queryDocPageNew(HttpServletRequest request,
                                               @RequestParam(value = "offset") Integer offset,
                                               @RequestParam(value = "end") Integer end,
                                               @RequestParam(value = "filterByCollection") String filterByCollection,
                                               @RequestParam(value = "directoryId", required = false) Long directoryId,
                                               @RequestParam(value = "docTitle", required = false) String docTitle,
                                               @RequestParam(value = "createTimeLeft", required = false) String createTimeLeft,
                                               @RequestParam(value = "createTimeRight", required = false) String createTimeRight) {
        Map requestMap = request.getParameterMap();
        Page page = docLibraryService.queryDocList(offset, end, directoryId, docTitle, null, Constants.DOC_STATUS_PUBLISHED,
                requestMap, createTimeLeft, createTimeRight, Boolean.parseBoolean(filterByCollection), false);
        return ResponseHelper.buildResponse(page);
    }

    /**
     * 收藏文档
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "文档收藏")
    @RequestMapping(value = "/collect/{id}", method = RequestMethod.PUT)
    public ResponseModel docCollect(@PathVariable(value = "id") Long id) {
        return ResponseHelper.buildResponse(docLibraryService.favorite(id, true));
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "文档取消收藏")
    @RequestMapping(value = "/uncollect/{id}", method = RequestMethod.PUT)
    public ResponseModel docUncollect(@PathVariable(value = "id") Long id) {
        return ResponseHelper.buildResponse(docLibraryService.favorite(id, false));
    }

    /**
     * 获取文档引用数和收藏数
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取文档引用数和收藏数")
    @RequestMapping(value = "/count/{id}", method = RequestMethod.GET)
    public ResponseModel DocCount(@PathVariable(value = "id") Long id) {
        return ResponseHelper.buildResponse(docLibraryService.countDoc(id));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "搜索联想")
    @RequestMapping(value = "/associate", method = RequestMethod.GET)
    public ResponseModel worldAssociate(
            @RequestParam(value = "queryStr") String queryStr) {
        if (ValidationUtil.isEmpty(queryStr)) {
            queryStr = "";
        }
        return ResponseHelper.buildResponse(docLibraryService.associate(queryStr.trim()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "文档数量统计")
    @RequestMapping(value = "/statistics/count", method = RequestMethod.GET)
    public ResponseModel statisticsCount(@RequestParam(value = "rangeDays", required = false) Integer rangeDays) {
        if (ValidationUtil.isEmpty(rangeDays)) {
            rangeDays = 5;
        }
        return ResponseHelper.buildResponse(docLibraryService.count(rangeDays));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询最新文档列表")
    @RequestMapping(value = "/list/new/{top}", method = RequestMethod.GET)
    public ResponseModel queryNews(@PathVariable(value = "top") Integer top) {
        return ResponseHelper.buildResponse(docLibraryService.queryNewDocs(top));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询我的收藏列表")
    @RequestMapping(value = "/list/favorites", method = RequestMethod.GET)
    public ResponseModel queryFavorites() {
        return ResponseHelper.buildResponse(docLibraryService.queryMyCollectedDocs());
    }


    @Autowired
    private ESDocService eSDocService;

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "耗时* 重建ES索引")
    @RequestMapping(value = "/es/init", method = RequestMethod.PUT)
    public ResponseModel initEs() {
        RequestContext.setExeUserId("super");
        return ResponseHelper.buildResponse(eSDocService.init());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "耗时* 刷新历史文档数据以支持高级检索，仅升级至高级检索版本时调用一次即可")
    @RequestMapping(value = "/as/init", method = RequestMethod.PUT)
    public ResponseModel initAdvancedSearch() {
        RequestContext.setExeUserId("super");
        return ResponseHelper.buildResponse(docLibraryService.init());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据文档标题和标签名称查询文档")
    @RequestMapping(value = "/es/query", method = RequestMethod.GET)
    public ResponseModel filter(@RequestParam(value = "queryStr", required = false) String queryStr,
                                @RequestParam(value = "current", defaultValue = "0") int current,
                                @RequestParam(value = "size", defaultValue = "10") int size) {
        return ResponseHelper.buildResponse(eSDocService.queryByKeys(queryStr, current, size));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "高级检索")
    @RequestMapping(value = "/query/advanced", method = RequestMethod.POST)
    public ResponseModel searchAdvanced(@RequestBody Map<String, Object> condition,
                                @RequestParam(value = "current", defaultValue = "0") int current,
                                @RequestParam(value = "size", defaultValue = "10") int size) {
        Page page = new Page(current, size);
        return ResponseHelper.buildResponse(docLibraryService.searchAdvanced(page,condition));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据文档标题和标签名称查询文档-APP")
    @RequestMapping(value = "/es/query1", method = RequestMethod.GET)
    public ResponseModel filter1(@RequestParam(value = "queryStr", required = false) String queryStr,
                                 @RequestParam(value = "current", defaultValue = "0") int current,
                                 @RequestParam(value = "size", defaultValue = "10") int size) {
        return ResponseHelper.buildResponse(eSDocService.queryAndDetail(queryStr, current, size));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出为word文档")
    @RequestMapping(value = "/export/{id}/{type}", method = RequestMethod.GET)
    public void export(@PathVariable(value = "id") Long id,
                       @PathVariable(value = "type") String type,
                       HttpServletResponse response) {
        if (ValidationUtil.isEmpty(type)) {
            throw new BadRequest("参数有误");
        }
        docLibraryService.export(id, type, response);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导入excel文档")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public ResponseModel importExcel(@RequestPart(value = "file") MultipartFile file,
                                     @RequestPart(value = "module") String moduleStr) {
        ExcelImportConfig excelConfig;
        try {
            excelConfig = JSON.parseObject(moduleStr, ExcelImportConfig.class);
        } catch (Exception e) {
            throw new BadRequest("模板配置信息格式有误");
        }
        return ResponseHelper.buildResponse(docLibraryService.importExcel(file, excelConfig));
    }

}
