package com.yizhi.application.caseLibrary.controller;

import com.baomidou.mybatisplus.plugins.Page;

import com.yizhi.application.caseLibrary.util.StuCommonUtils;

import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.library.application.feign.CaseLibraryClassifyClient;
import com.yizhi.library.application.feign.CaseLibraryClient;
import com.yizhi.library.application.feign.StudentCaseClient;
import com.yizhi.library.application.feign.StudentCaseManageClient;
import com.yizhi.library.application.param.SelectionStudentCaseParam;
import com.yizhi.library.application.param.StudentCaseAuditParam;
import com.yizhi.library.application.param.StudentCaseParam;
import com.yizhi.library.application.param.UpdateCaseRelatedClassifyParam;
import com.yizhi.library.application.vo.*;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ding
 * @className StudentLibraryController
 * @description TODO
 * @date 2019/7/9
 **/
@Api(tags = "学员案例接口", description = "学员案例接口")
@RestController
@RequestMapping("/api/studentCase/")
public class StudentLibraryController {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudentLibraryController.class);

    @Autowired
    private StudentCaseClient studentCaseClient;

    @Autowired
    private StuCommonUtils stuCommonUtils;

    @Autowired
    private StudentCaseManageClient studentCaseManageClient;

    @Autowired
    private CaseLibraryClassifyClient caseLibraryClassifyClient;
    @Autowired
    private CaseLibraryClient caseLibraryClient;


    @ApiOperation(value = "学员端我的案例列表", notes = "学员端我的案例列表", response = CaseLibraryVO.class)
    @GetMapping("/myCaseLibrary")
    public Response<CaseLibraryVO> getMyCaseLibrary(@ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                             @ApiParam(value = "每页条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize) {

        try {

            Map<String, Integer> map = new HashMap<>(3);
            Page<CaseLibraryVO> page = studentCaseClient.myCaseLibraryList(pageNo, pageSize);
            map.put("pageNo", pageNo);
            map.put("pageSize", pageSize);
            if (null != page) {
                map.put("total", page.getTotal());
            }
            return Response.ok(page, map);

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员提交案例获取案例库信息", notes = "学员提交案例获取案例库信息", response = StudentCaseVO.class)
    @GetMapping("/prepareStudentCase")
    public Response<StudentCaseVO> prepareStudentCase(@ApiParam(value = "案例活动id", required = true) @RequestParam(name = "caseLibraryId", required = true) Long caseLibraryId) {

        try {
            StudentCaseVO studentCaseVO = studentCaseClient.prepareStudentCase(caseLibraryId);
            if (null != studentCaseVO.getResultState() && studentCaseVO.getResultState() == 0) {
                //返回案例活动已经下架,不能参加
                return Response.fail(Constants.CASELIBRARY_HAS_OFFLINE);
            } else {
                return Response.ok(studentCaseVO);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例提交", notes = "学员案例提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "学员案例主题", paramType = "body", required = false),
            @ApiImplicitParam(name = "logoUrl", value = "学员案例封面图片", paramType = "body", required = false),
            @ApiImplicitParam(name = "caseLibraryId", value = "案例活动id", paramType = "body", required = false),
            @ApiImplicitParam(name = "textEditType", value = "案例内容提交形式 1:富文本 2:导入外部文档 3:纯文本格式", paramType = "body", required = false),
            @ApiImplicitParam(name = "contentFileName", value = "上传文档文件名", paramType = "body", required = false),
            @ApiImplicitParam(name = "content", value = "学员案例内容", paramType = "body", required = false),
            @ApiImplicitParam(name = "url", value = "附件url", paramType = "body", required = false),
            @ApiImplicitParam(name = "name", value = "附件名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "fileSize", value = "文件大小", paramType = "body", required = false),
            @ApiImplicitParam(name = "type", value = "0:保存 1:提交", paramType = "body", required = false)
    })
    @PostMapping("/submit")
    public Response<Object> submitStudentCase(@RequestBody StudentCaseParam studentCaseParam) {

        try {

            if (null != studentCaseParam.getTextEditType() && studentCaseParam.getTextEditType() == 2) {
                if (null != studentCaseParam.getContentFileName()) {
                    studentCaseParam.setPdfFileName(studentCaseParam.getContentFileName());
                }
                String content = stuCommonUtils.translatePdfToPhoto(studentCaseParam.getPdfOssUrl(), studentCaseParam.getPdfFileName());
                if (StringUtils.isNotBlank(content)) {
                    studentCaseParam.setContent(content);
                }
            }
            Long id = studentCaseParam.getCaseLibraryId();
            CaseLibraryVO caseLibraryVO =null;
            if (id!=null) {
                 caseLibraryVO = caseLibraryClient.getCaseLibrary(id);
            }
            //活动是否已经过期
            Date now=new Date();
            if (caseLibraryVO.getEndTime().getTime()>now.getTime()){
                if (studentCaseClient.submitStudentCase(studentCaseParam)) {
                    return Response.ok();
                } else {
                    LOGGER.error("############学员案例提交过程中出现错误");
                    return Response.fail(Constants.MSG_BIZ_FAIL);
                }
            }else {
                LOGGER.error("############原创活动已经过期，不能提交学员案例");
                return Response.fail(InternationalEnums.CASELIBRARY_HAS_EXPIRED.getName());
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例提交记录中提交", notes = "学员案例提交记录中提交")
    @GetMapping("/record/submit")
    public Response<Object> studentCaseRecordSubmit(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            if (studentCaseClient.studentCaseRecordSubmit(studentCaseId)) {
                return Response.ok();
            } else {
                LOGGER.error("############学员案例提交记录中提交过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例提交记录中撤回", notes = "学员案例提交记录中撤回")
    @GetMapping("/record/recall")
    public Response<Object> studentCaseRecall(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            if (studentCaseClient.studentCaseRecall(studentCaseId)) {
                return Response.ok();
            } else {
                LOGGER.error("############学员案例提交记录中撤回过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例删除", notes = "学员案例删除")
    @GetMapping("/record/delete")
    public Response<Object> delete(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            return Response.ok(studentCaseManageClient.delete(studentCaseId));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例记录查看", notes = "学员案例记录查看", response = StudentCaseViewVO.class)
    @GetMapping("/record/view")
    public Response<StudentCaseViewVO> studentCaseView(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            return Response.ok(studentCaseClient.studentCaseView(studentCaseId, null));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "获取学员案例提交记录列表", notes = "获取学员案例提交记录列表", response = StudentCaseRecordListVO.class)
    @GetMapping("/getSubmitRecords")
    public Response<StudentCaseRecordListVO> getSubmitRecords(@ApiParam(value = "案例活动id", required = true) @RequestParam(name = "caseLibraryId", required = true) Long caseLibraryId,
                                                       @ApiParam(value = "案例活动结束时间", required = false) @RequestParam(name = "endTime", required = false) String endTime) {

        try {
            return Response.ok(studentCaseClient.getSubmitRecords(caseLibraryId, endTime));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例审核,评分获取案例列表", notes = "学员案例审核,评分获取案例列表", response = StudentCaseStudyVO.class)
    @GetMapping("/getAuditList")
    public Response<StudentCaseStudyVO> getAuditList(
            @ApiParam(value = "请求类型 1:审核 2:评分", required = true) @RequestParam(name = "type", required = true) Integer type,
            @ApiParam(value = "审核/评分,案例名称关键字", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
            @ApiParam(value = "每页显示条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {

        try {
            Page<StudentCaseStudyVO> page = studentCaseClient.getAuditList(type, name, pageNo, pageSize);
            Map<String, Integer> map = new HashMap<>(3);
            map.put("pageNo", pageNo);
            map.put("pageSize", pageSize);
            if (null != page) {
                map.put("total", page.getTotal());
            }
            return Response.ok(page, map);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例学习获取案例信息/审核,评分获取案例信息", notes = "学员案例学习获取案例信息/审核,评分获取案例信息", response = StudentCaseStudyVO.class)
    @GetMapping("/studyStudentCase")
    public Response<StudentCaseStudyVO> studyStudentCase(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId,
                                                  @ApiParam(value = "请求类型 0:学习案例 1:审核 2:评分", required = true) @RequestParam(name = "type", required = true) Integer type,
                                                  @ApiParam(value = "审核/评分,临时索引第几条", required = false) @RequestParam(name = "number", required = false) Integer number,
                                                  @ApiParam(value = "审核/评分,案例名称关键字", required = false) @RequestParam(name = "name", required = false) String name) {

        try {
            StudentCaseStudyVO studyVO = studentCaseClient.studyStudentCase(studentCaseId, type, number, name);
            //案例已经被删除,提示案例已经下架,或者不存在
            if (studyVO.getResultState() != null && studyVO.getResultState() == 0) {
                return Response.fail(Constants.STUDENTCASE_HAS_OFFLINE);
            }
            return Response.ok(studyVO);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }


    @ApiOperation(value = "学员案例审核提交", notes = "学员案例审核提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentCaseId", value = "学员案例id", paramType = "body", required = true),
            @ApiImplicitParam(name = "auditState", value = "审核是否通过 0:不通过 1:通过", paramType = "body", required = true),
            @ApiImplicitParam(name = "audiEvaluate", value = "审核反馈", paramType = "body", required = false)
    })
    @PostMapping("/audit")
    public Response<Object> studentCaseAudit(@RequestBody StudentCaseAuditParam studentCaseAuditParam) {

        try {
            return Response.ok(studentCaseClient.studentCaseAudit(studentCaseAuditParam));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例批量审核", notes = "学员案例批量审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idList", value = "学员案例id", paramType = "body", required = true),
            @ApiImplicitParam(name = "auditState", value = "审核是否通过 2:不通过 1:通过", paramType = "body", required = true),
            @ApiImplicitParam(name = "audiEvaluate", value = "审核反馈", paramType = "body", required = false)
    })
    @PostMapping("/batchAudit")
    public Response<Object> studentCaseBatchAudit(@RequestBody StudentCaseAuditParam studentCaseAuditParam) {

        try {
            if (CollectionUtils.isEmpty(studentCaseAuditParam.getIdList())) {
                return Response.fail(Constants.CASELIBRARY_SELECT_NULL);
            }
            return Response.ok(studentCaseClient.studentCaseBatchAudit(studentCaseAuditParam));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例评分提交", notes = "学员案例评分提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentCaseId", value = "学员案例id", paramType = "body", required = true),
            @ApiImplicitParam(name = "score", value = "评分", paramType = "body", required = true)
    })
    @PostMapping("/score")
    public Response<Object> studentCaseScore(@RequestBody StudentCaseAuditParam studentCaseAuditParam) {

        try {
            return Response.ok(studentCaseClient.studentCaseScore(studentCaseAuditParam));

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例批量评分", notes = "学员案例批量评分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idList", value = "学员案例id", paramType = "body", required = true),
            @ApiImplicitParam(name = "score", value = "评分", paramType = "body", required = true)
    })
    @PostMapping("/batchScore")
    public Response<Object> studentCaseBatchScore(@RequestBody StudentCaseAuditParam studentCaseAuditParam) {

        try {
            if (CollectionUtils.isEmpty(studentCaseAuditParam.getIdList())) {
                return Response.fail(Constants.CASELIBRARY_SELECT_NULL);
            }
            return Response.ok(studentCaseClient.studentCaseBatchScore(studentCaseAuditParam));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员案例审核/评分导出案例", notes = "学员案例审核/评分导出案例")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idList", value = "学员案例id", paramType = "body", required = true)
    })
    @PostMapping("/batchExport")
    public Response<Object> studentCaseBatchExport(@RequestBody StudentCaseAuditParam studentCaseAuditParam) {

        try {
            if (CollectionUtils.isEmpty(studentCaseAuditParam.getIdList())) {
                return Response.fail(Constants.CASELIBRARY_SELECT_NULL);
            }
            String serialNo = studentCaseClient.studentCaseBatchExport(studentCaseAuditParam);
            return Response.ok("导出成功," + " " + "编号:" + serialNo);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "微信端获取我的收藏列表", notes = "微信端获取我的收藏列表", response = FavoriteVO.class)
    @GetMapping("/getFavorites")
    public Response<FavoriteVO> getFavorites(@ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                      @ApiParam(value = "每页显示条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                      @ApiParam(value = "案例名称", required = true) @RequestParam(name = "name", required = false) String name) {

        try {
            return Response.ok(studentCaseClient.getFavorites(pageNo, pageSize, name));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "精选案例搜索页面", notes = "精选案例搜索页面", response = FavoriteVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "作者或者案例姓名模糊查询", paramType = "body", required = false),
            @ApiImplicitParam(name = "classifyIdList", value = "分类筛选id", paramType = "body", required = false),
            @ApiImplicitParam(name = "sortType", value = "排序类型 1:提交时间由近到远 2:提交时间由远到近 3:学习量由多到少 4:点赞数由多到少 5:评分由高到低", paramType = "sortType", required = true),
            @ApiImplicitParam(name = "pageNo", value = "当前第几页", paramType = "body", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", paramType = "body", required = true)
    })
    @PostMapping("/getSelectionList")
    public Response<FavoriteVO> getSelectionStudentCaseList(@RequestBody SelectionStudentCaseParam selectionStudentCaseParam) {

        try {

            Map<String, Integer> pageMap = new HashMap<>(3);
            Page<FavoriteVO> page = studentCaseClient.getSelectionStudentCaseList(selectionStudentCaseParam);
            pageMap.put("pageNo", selectionStudentCaseParam.getPageNo());
            pageMap.put("pageSize", selectionStudentCaseParam.getPageSize());
            if (null != page) {
                pageMap.put("total", page.getTotal());
            }

            return Response.ok(page, pageMap);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "精选案例筛选获取分类列表", notes = "精选案例筛选获取分类列表", response = ClassifyListVO.class)
    @GetMapping("/getClassifyList")
    public Response<ClassifyListVO> getClassifyList() {

        try {
            List<ClassifyListVO> list = caseLibraryClassifyClient.getClassifyList();
//            list = JSON.parseArray(JSON.toJSONString(list), ClassifyListVO.class);
//            String s = JSON.toJSONString(list);
            return Response.ok(list);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学员端审核案例修改关联分类", notes = "学员端审核案例修改关联分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentCaseId", value = "学员案例id", paramType = "body", required = false),
            @ApiImplicitParam(name = "relatedClassifyList", value = "关联分类list", paramType = "body", required = true)
    })
    @PostMapping("/modifyRlatedClassifys")
    public Response<Object> modifyRlatedClassifys(@RequestBody UpdateCaseRelatedClassifyParam param) {

        try {
            return Response.ok(studentCaseClient.modifyRlatedClassifys(param));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }
}
