package com.yizhi.application.caseLibrary.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.accountUtil.AuthorizeQueryAccount;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.course.application.vo.RangeImportParamVo;
import com.yizhi.course.application.vo.domain.ClassifyEntityVo;
import com.yizhi.library.application.feign.CaseLibraryClient;
import com.yizhi.library.application.vo.CaseLibraryVO;
import com.yizhi.library.application.vo.CaselibraryAuthorizeVO;
import com.yizhi.library.application.vo.ClassifyVO;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.OrgVO;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ding
 * @className CaseLibraryManageController
 * @description TODO
 * @date 2019/7/4
 **/

@Api(tags = "案例库管理端接口", description = "案例库管理端接口")
@RestController
@RequestMapping("/manage/caseLibrary/")
public class CaseLibraryManageController {

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

    @Autowired
    private CaseLibraryClient caseLibraryClient;

    @Autowired
    private AuthorizeQueryAccount queryAccount;

    @ApiOperation(value = "获取案例库管理列表", notes = "获取案例库管理列表", response = CaseLibraryVO.class)
    @GetMapping("/getCaseLibraryList")
    public Response<CaseLibraryVO> getCaseLibraryList(@ApiParam(value = "案例名称模糊查询", required = false) @RequestParam(name = "name", required = false) String name,
                                               @ApiParam(value = "状态模糊查询", required = false) @RequestParam(name = "state", required = false) Integer state,
                                               @ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                               @ApiParam(value = "每页条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize) {

        try {
            if (StringUtils.isNotBlank(name)) {
                name = name.trim();
            }
            Page<CaseLibraryVO> page = caseLibraryClient.getCaseLibraryList(name, state, pageNo, pageSize);
            Map<String, Integer> pageMap = new HashMap<>(3);
            pageMap.put("pageNo", pageNo);
            pageMap.put("pageSize", pageSize);
            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 = "创建案例活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "案例活动id", paramType = "body", required = false),
            @ApiImplicitParam(name = "name", value = "案例活动名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "logoUrl", value = "封面图片", paramType = "body", required = false),
            @ApiImplicitParam(name = "explanation", value = "案例说明", paramType = "body", required = false),
            @ApiImplicitParam(name = "textEditType", value = "文本编辑形式:1文本编辑框, 2导入外部文档格式doc docx pdf", paramType = "body", required = false),
            @ApiImplicitParam(name = "point", value = "获得积分数", paramType = "body", required = false),
            @ApiImplicitParam(name = "examine", value = "学员端显示类型 1:通过后自动上架, 2:通过需要手动上架", paramType = "body", required = false),
            @ApiImplicitParam(name = "classifyList", value = "分类维度列表", paramType = "body", required = false),
            @ApiImplicitParam(name = "submitterUrl", value = "必须提交人导入附件阿里云地址", paramType = "body", required = false),
            @ApiImplicitParam(name = "submitterAccessName", value = "必须提交人导入附件名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "auditorUrl", value = "审核人导入附件阿里云地址", paramType = "body", required = false),
            @ApiImplicitParam(name = "auditorAccessName", value = "审核人导入附件名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "scorerUrl", value = "评分人导入附件阿里云地址", paramType = "body", required = false),
            @ApiImplicitParam(name = "scorerAccessName", value = "评分人导入附件名称", paramType = "body", required = false),

    })
    @PostMapping("/insert")
    public Response<Object> classifyInsert(@ApiParam("CaseLibraryVO") @RequestBody CaseLibraryVO caseLibraryVO) {
        LOGGER.info("-----------------------------caseLibraryVO:  " + JSON.toJSONString(caseLibraryVO));
        try {
            if (CollectionUtils.isNotEmpty(caseLibraryVO.getClassifyIdList())) {
                if (caseLibraryVO.getClassifyIdList().size() > 3) {
                    return Response.fail("4008", InternationalEnums.MANAGEASSIGNMENTCONTROLLER7.getName());
                }
            }
            Long id = caseLibraryClient.insertCaseLibrary(caseLibraryVO);
            if (id == 0) {
                return Response.fail("4009", InternationalEnums.MANAGEASSIGNMENTCONTROLLER4.getName());
            } else {
                return Response.ok(id);
            }
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "选择分类维度", notes = "选择分类维度", response = ClassifyVO.class)
    @GetMapping("/getClassify")
    public Response<ClassifyVO> getClassify(@ApiParam(value = "caseLibraryId", required = false) @RequestParam(name = "caseLibraryId", required = false) Long caseLibraryId) {

        try {
            return Response.ok(caseLibraryClient.getClassify(caseLibraryId));
        } catch (Exception e) {
            LOGGER.error("############ ", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "必须提交人导入", notes = "必须提交人导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ossUrl", value = "上传阿里云返回url", paramType = "body", required = true),
            @ApiImplicitParam(name = "bizdId", value = "案例活动id", paramType = "body", required = true),
    })
    @PostMapping("/submitter/import")
    public Response<ClassifyEntityVo> importSubmitter(@RequestBody RangeImportParamVo importParamVo) {

        try {
            String serialNo = caseLibraryClient.importSubmitter(importParamVo.getBizdId(), importParamVo.getOssUrl());
            return Response.ok("导入成功," + " " + "编号:" + serialNo);

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

    @ApiOperation(value = "审核对象导入", notes = "审核对象导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ossUrl", value = "上传阿里云返回url", paramType = "body", required = true),
            @ApiImplicitParam(name = "bizdId", value = "案例活动id", paramType = "body", required = true),
    })
    @PostMapping("/auditor/import")
    public Response<ClassifyEntityVo> importAuditor(@RequestBody RangeImportParamVo importParamVo) {

        try {
            String serialNo = caseLibraryClient.importAuditor(importParamVo.getBizdId(), importParamVo.getOssUrl());
            return Response.ok("导入成功," + " " + "编号:" + serialNo);

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

    @ApiOperation(value = "评分对象导入", notes = "评分对象导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ossUrl", value = "上传阿里云返回url", paramType = "body", required = true),
            @ApiImplicitParam(name = "bizdId", value = "案例活动id", paramType = "body", required = true),
    })
    @PostMapping("/scorer/import")
    public Response<ClassifyEntityVo> importScorer(@RequestBody RangeImportParamVo importParamVo) {

        try {
            String serialNo = caseLibraryClient.importScorer(importParamVo.getBizdId(), importParamVo.getOssUrl());
            return Response.ok("导入成功," + " " + "编号:" + serialNo);

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

    @ApiOperation(value = "案例活动修改获取信息", notes = "案例活动修改获取信息", response = CaseLibraryVO.class)
    @GetMapping("/view")
    public Response<CaseLibraryVO> viewCaseLibrary(@ApiParam(value = "caseLibraryId", required = true) @RequestParam("caseLibraryId") Long caseLibraryId) {

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

    @ApiOperation(value = "修改案例活动", notes = "修改案例活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "案例活动id", paramType = "body", required = false),
            @ApiImplicitParam(name = "name", value = "案例活动名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "logoUrl", value = "封面图片", paramType = "body", required = false),
            @ApiImplicitParam(name = "explanation", value = "案例说明", paramType = "body", required = false),
            @ApiImplicitParam(name = "textEditType", value = "文本编辑形式:1文本编辑框, 2导入外部文档格式doc docx pdf", paramType = "body", required = false),
            @ApiImplicitParam(name = "point", value = "获得积分数", paramType = "body", required = false),
            @ApiImplicitParam(name = "examine", value = "学员端显示类型 1:通过后自动上架, 2:通过需要手动上架", paramType = "body", required = false),
            @ApiImplicitParam(name = "classifyList", value = "分类维度列表", paramType = "body", required = false),
            @ApiImplicitParam(name = "submitterUrl", value = "必须提交人导入附件阿里云地址", paramType = "body", required = false),
            @ApiImplicitParam(name = "submitterAccessName", value = "必须提交人导入附件名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "auditorUrl", value = "审核人导入附件阿里云地址", paramType = "body", required = false),
            @ApiImplicitParam(name = "auditorAccessName", value = "审核人导入附件名称", paramType = "body", required = false),
            @ApiImplicitParam(name = "scorerUrl", value = "评分人导入附件阿里云地址", paramType = "body", required = false),
            @ApiImplicitParam(name = "scorerAccessName", value = "评分人导入附件名称", paramType = "body", required = false),

    })
    @PostMapping("/update")
    public Response<Object> classifyUpdate(@ApiParam("CaseLibraryVO") @RequestBody CaseLibraryVO caseLibraryVO) {

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

    @ApiOperation(value = "移除分类维度", notes = "移除分类维度")
    @GetMapping("/relatedClassify/delete")
    public Response<Object> deleteRelatedClassify(@ApiParam(value = "id", required = true) @RequestParam("id") Long id) {

        try {
            if (caseLibraryClient.deleteRelatedClassify(id)) {
                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("/release")
    public Response<Object> releaseCaseLibrary(@ApiParam(value = "caseLibraryId", required = true) @RequestParam("caseLibraryId") Long caseLibraryId) {

        try {
            return Response.ok(caseLibraryClient.releaseCaseLibrary(caseLibraryId));

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

    @ApiOperation(value = "案例活动下架", notes = "案例活动下架")
    @GetMapping("/putDown")
    public Response<Object> putDownCaseLibrary(@ApiParam(value = "caseLibraryId", required = true) @RequestParam("caseLibraryId") Long caseLibraryId) {

        try {
            if (caseLibraryClient.putDownCaseLibrary(caseLibraryId)) {
                return Response.ok();
            } else {
                return Response.fail("40005", "已关联培训项目,不能下架");
            }
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出s现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "案例活动草稿状态下删除", notes = "案例活动草稿状态下删除")
    @GetMapping("/delete")
    public Response<Object> deleteCaseLibrary(@ApiParam(value = "caseLibraryId", required = true) @RequestParam("caseLibraryId") Long caseLibraryId) {

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

    @ApiOperation(value = "培训项目关联案例活动获取列表", notes = "培训项目关联案例活动获取列表", response = CaseLibraryVO.class)
    @GetMapping("/getProjectList")
    public Response<CaseLibraryVO> getProjectList(@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 {
            Map<String, Integer> pageMap = new HashMap<>(3);
            Page<CaseLibraryVO> page = caseLibraryClient.getProjectList(name, pageNo, pageSize);
            pageMap.put("pageNo", pageNo);
            pageMap.put("pageSize", pageSize);
            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 = "管理端案例活动新增可见范围用户,部门")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "caseliraryId", value = "案例活动id", paramType = "body", required = true),
            @ApiImplicitParam(name = "relationId", value = "存放人或组织的ID", paramType = "body", required = true),
            @ApiImplicitParam(name = "type", value = "1：用户 、2：组织", paramType = "body", required = true),
            @ApiImplicitParam(name = "name", value = "角色名称", paramType = "body", required = false)
    })
    @PostMapping("/authorize/insert")
    public Response<Object> insertAuthorizes(@RequestBody List<CaselibraryAuthorizeVO> caseLibraryAuthorizeList) {

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

    @ApiOperation(value = "管理端案例活动获取可见范围列表", notes = "管理端案例活动获取可见范围列表", response = CaselibraryAuthorizeVO.class)
    @GetMapping("/authorize/list")
    public Response<CaselibraryAuthorizeVO> getAuthorize(@ApiParam(value = "案例活动id", required = true) @RequestParam(name = "caselibraryId", required = true) Long caselibraryId) {
        try {
            List<CaselibraryAuthorizeVO> authorizeVOList = caseLibraryClient.getAuthorize(caselibraryId);
            if (CollectionUtils.isNotEmpty(authorizeVOList)) {
                List<Long> accountIds = new ArrayList<>();
                List<Long> orgIds = new ArrayList<>();
                Map<Long, AccountVO> accountVOMap = new HashMap<>(16);
                Map<Long, OrgVO> orgVOMap = new HashMap<>(16);
                //获取用户,部门信息
                for (CaselibraryAuthorizeVO caselibraryAuthorizeVO : authorizeVOList) {
                    if (caselibraryAuthorizeVO.getType() == 1) {
                        accountIds.add(caselibraryAuthorizeVO.getRelationId());
                    } else if (caselibraryAuthorizeVO.getType() == 2) {
                        orgIds.add(caselibraryAuthorizeVO.getRelationId());
                    }
                }
                if (CollectionUtils.isNotEmpty(accountIds)) {
                    accountVOMap = queryAccount.queryAccountByIds(accountIds);
                }
                if (CollectionUtils.isNotEmpty(orgIds)) {
                    orgVOMap = queryAccount.queryOrgByIds(orgIds);
                }
                for (CaselibraryAuthorizeVO caselibraryAuthorizeVO : authorizeVOList) {
                    if (caselibraryAuthorizeVO.getType() == 1) {
                        AccountVO accountVO = accountVOMap.get(caselibraryAuthorizeVO.getRelationId());
                        if (null != accountVO) {
                            caselibraryAuthorizeVO.setName(accountVO.getName());
                            caselibraryAuthorizeVO.setAccountFullName(accountVO.getFullName());
                            caselibraryAuthorizeVO.setWorkNum(accountVO.getWorkNum());
                        }
                    } else if (caselibraryAuthorizeVO.getType() == 2) {
                        OrgVO orgVO = orgVOMap.get(caselibraryAuthorizeVO.getRelationId());
                        if (null != orgVO) {
                            caselibraryAuthorizeVO.setName(orgVO.getName());
                        }
                    }
                }
            }
            return Response.ok(authorizeVOList);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "管理端首页配置上传案例获取案例活动列表", notes = "管理端首页配置上传案例获取案例活动列表")
    @GetMapping("/home/list")
    public Response<Object> getHomeList(@ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = false) Integer pageNo,
                                 @ApiParam(value = "每页条数", required = true) @RequestParam(name = "pageSize", required = false) Integer pageSize) {
        try {
            if (null == pageNo) {
                pageNo = 1;
            }
            if (null == pageSize) {
                pageSize = Integer.MAX_VALUE;
            }
            Page<CaseLibraryVO> page = caseLibraryClient.getHomeList(pageNo, pageSize);
            Map<String, Integer> pageMap = new HashMap<>(3);
            pageMap.put("pageNo", pageNo);
            pageMap.put("pageSize", pageSize);
            if (null != page) {
                pageMap.put("pageTotal", page.getTotal());
            }
            return Response.ok(page, pageMap);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }


}
