package com.yeejoin.amos.knowledgebase.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.StringUtil;
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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.service.DocContentService;
import com.yeejoin.amos.knowledgebase.face.service.DocLibraryService;
import com.yeejoin.amos.knowledgebase.face.service.DynamicsOptionService;

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

/**
 * <p>
 * 知识库文档存储 前端控制器
 * </p>
 *
 * @author 子杨
 * @since 2020-08-05
 */

@RestController
@TycloudResource(module = "knowledgebase", value = "doccontent")
@RequestMapping(value = "/v1/doccontent")
@Api(tags = "knowledgebase-知识库文档存储")
public class DocContentResource {

    @Autowired
    private DocContentService docContentService;
    @Autowired
    private DynamicsOptionService dynamicsOptionService;
    @Autowired
    private DocLibraryService docLibraryService;


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "创建文档")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseModel<KnowledgeDocContentModel> createDoc(@RequestBody KnowledgeDocContentModel model) {
        if (ValidationUtil.isEmpty(model)
                || ValidationUtil.isEmpty(model.getHtmlContent())
                || ValidationUtil.isEmpty(model.getDocTitle())
                || ValidationUtil.isEmpty(model.getDirectoryId())) {
            throw new BadRequest("参数校验失败.");
        }
        return ResponseHelper.buildResponse(docContentService.createDoc(model));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "更新文档")
    @RequestMapping(value = "/{sequenceNbr}", method = RequestMethod.PUT)
    public ResponseModel<KnowledgeDocContentModel> update(
            @RequestBody KnowledgeDocContentModel model,
            @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        if (ValidationUtil.isEmpty(model)
                || ValidationUtil.isEmpty(model.getDocTitle())
                || ValidationUtil.isEmpty(model.getDirectoryId())
                || ValidationUtil.isEmpty(model.getHtmlContent())) {
            throw new BadRequest("参数校验失败.");
        }
        model.setSequenceNbr(sequenceNbr);
        return ResponseHelper.buildResponse(docContentService.updateDoc(model));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "更新文档内容")
    @RequestMapping(value = "/content/{sequenceNbr}", method = RequestMethod.PUT)
    public ResponseModel<KnowledgeDocContent> updateContent(
            @RequestBody KnowledgeDocContentModel model,
            @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        if (ValidationUtil.isEmpty(sequenceNbr)
                || ValidationUtil.isEmpty(model.getHtmlContent())) {
            throw new BadRequest("参数校验失败.");
        }
        return ResponseHelper.buildResponse(docContentService.updateHtmlContent(sequenceNbr, model.getHtmlContent()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "删除文档")
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    public ResponseModel<List<Long>> deleteDoc(
            @PathVariable(value = "ids") String ids) {
        List<Long> idList = StringUtil.String2LongList(ids);
        if (ValidationUtil.isEmpty(ids)) {
            throw new BadRequest("请选择要删除的文档.");
        }
        return ResponseHelper.buildResponse(docContentService.deleteDoc(idList));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "给文档点赞")
    @RequestMapping(value = "/{sequenceNbr}/like", method = RequestMethod.PUT)
    public ResponseModel like(
            @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(docContentService.like(sequenceNbr));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "给文档吐槽")
    @RequestMapping(value = "/{sequenceNbr}/dislike", method = RequestMethod.PUT)
    public ResponseModel dislike(
            @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(docContentService.disLike(sequenceNbr));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询单个文档内容信息")
    @RequestMapping(value = "/{sequenceNbr}", method = RequestMethod.GET)
    public ResponseModel<KnowledgeDocContentModel> seleteOne(@PathVariable("sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(docContentService.queryOneDocDetail(sequenceNbr));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取管理界面的表头")
    @RequestMapping(value = "/docmanagement/header", method = RequestMethod.GET)
    public ResponseModel docmanagementHeader() {
        return ResponseHelper.buildResponse(dynamicsOptionService.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name()));
    }


//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "分页查询文档信息")
//    @RequestMapping(value = "/page", method = RequestMethod.GET)
//    public ResponseModel<Page> queryDocPage(HttpServletRequest request) {
//        Map paramMap = request.getParameterMap();
//
//        String[] auditStatus = request.getParameterValues("auditStatus");
//        String[] docStatus = request.getParameterValues("docStatus");
//
//        if (!ValidationUtil.isEmpty(auditStatus) && auditStatus[0].length() == 0) {
//            auditStatus = null;
//        }
//        if (!ValidationUtil.isEmpty(docStatus) && docStatus[0].length() == 0) {
//            docStatus = null;
//        }
//        Date createTimeLeft = null;
//        Date createTimeRight = null;
//        try {
//            if (!ValidationUtil.isEmpty(paramMap.get("createTimeLeft"))) {
//                createTimeLeft = DateUtil.formatStringToDate(request.getParameterValues("createTimeLeft")[0], null);
//            }
//            if (!ValidationUtil.isEmpty(paramMap.get("createTimeRight"))) {
//                createTimeRight = DateUtil.formatStringToDate(request.getParameterValues("createTimeRight")[0], null);
//            }
//        } catch (Exception e) {
//            throw new BadRequest("时间范围参数格式有误");
//        }
//        int offset = Integer.parseInt(request.getParameterValues("offset")[0]);
//        int end = Integer.parseInt(request.getParameterValues("end")[0]);
//
//        paramMap.remove("offset");
//        paramMap.remove("end");
//        paramMap.remove("total");
//        paramMap.remove("auditStatus");
//        paramMap.remove("docStatus");
//        paramMap.remove("createTimeLeft");
//        paramMap.remove("createTimeRight");
//
//        return ResponseHelper.buildResponse(docContentService.queryDocPage(offset, end, paramMap, auditStatus, docStatus, createTimeLeft, createTimeRight));
//    }


    @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 = "directoryId", required = false) Long directoryId,
                                               @RequestParam(value = "docTitle", required = false) String docTitle,
                                               @RequestParam(value = "auditStatus", required = false) String[] auditStatus,
                                               @RequestParam(value = "docStatus", required = false) String docStatus,
                                               @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, auditStatus, docStatus,
                requestMap, createTimeLeft, createTimeRight, false, true);
        return ResponseHelper.buildResponse(page);
    }


//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "字符串模糊查询文档(搜索项为文档标题和标签名称)")
//    @RequestMapping(value = "/title/tag", method = RequestMethod.GET)
//    public ResponseModel searchForDocs(
//            @RequestParam(value = "queryStr", defaultValue = "") String queryStr,
//            @RequestParam(value = "current") int current,
//            @RequestParam(value = "size") int size) {
//        Page page = new Page();
//        page.setCurrent(current);
//        page.setSize(size);
//        return ResponseHelper.buildResponse(docContentService.searchForDoc(page, queryStr));
//    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "文档被点赞/吐槽状态")
    @RequestMapping(value = "/{sequenceNbr}/statistics/likes", method = RequestMethod.GET)
    public ResponseModel queryLikeOrDis(
            @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(docContentService.queryLikeOrDis(sequenceNbr));
    }
    
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取简单的预案信息")
    @RequestMapping(value = "/getSimpleDetail/{sequenceNbr}", method = RequestMethod.GET)
    public ResponseModel<List<Map<String, Object>>> getSimpleDetail(
            @PathVariable(value = "sequenceNbr") String sequenceNbr) {
        return ResponseHelper.buildResponse(docContentService.getSimpleDetail(sequenceNbr));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据orgCode获取预案list")
    @RequestMapping(value = "/list/{orgCode}", method = RequestMethod.GET)
    public ResponseModel<List<KnowledgeDocContent>> listByOrgCode(@PathVariable(value = "orgCode") String orgCode) {
        return ResponseHelper.buildResponse(docContentService.listByOrgCode(orgCode));
    }
}
