package cn.chnmuseum.party.web.controller;

import cn.chnmuseum.party.common.enums.AuditOperationEnum;
import cn.chnmuseum.party.common.enums.AuditStatusEnum;
import cn.chnmuseum.party.common.enums.AuditTypeEnum;
import cn.chnmuseum.party.common.enums.FileCatEnum;
import cn.chnmuseum.party.common.log.MethodLog;
import cn.chnmuseum.party.common.log.OperModule;
import cn.chnmuseum.party.common.log.OperType;
import cn.chnmuseum.party.common.validator.groups.Add;
import cn.chnmuseum.party.common.validator.groups.Update;
import cn.chnmuseum.party.common.vo.GenericPageParam;
import cn.chnmuseum.party.model.*;
import cn.chnmuseum.party.service.*;
import cn.chnmuseum.party.web.controller.base.BaseController;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * 学习内容 前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-26
 */
@Slf4j
@RestController
@RequestMapping("/learningContent")
@Api(tags = {"学习内容操作接口"})
public class LearningContentController extends BaseController {

    @Resource
    private ExhibitionBoardCatService exhibitionBoardCatService;
    @Resource
    private VideoContentService videoContentService;
    @Resource
    private CopyrightOwnerService copyrightOwnerService;
    @Resource
    private LearningContentService learningContentService;
    @Resource
    private LearningContentBoardCatService learningContentBoardCatService;
    @Resource
    private LearningContentBoardService learningContentBoardService;
    @Resource
    private ExhibitionBoardService exhibitionBoardService;
    @Resource
    private LearningContentCopyrightOwnerService learningContentCopyrightOwnerService;
    @Resource
    private LearningProjectService learningProjectService;
    @Resource
    private AuditService auditService;
    @Resource
    private AssetService assetService;

    @PostMapping("/save")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:save")
    @ApiOperation(value = "添加学习内容", notes = "添加学习内容")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.ADD)
    public Map<String, Object> saveLearningContent(@Validated(value = {Add.class}) LearningContent learningContent) {
        final LambdaQueryWrapper<LearningContent> lambdaQueryWrapper = Wrappers.<LearningContent>lambdaQuery().eq(LearningContent::getName, learningContent.getName().trim());
        final int count = this.learningContentService.count(lambdaQueryWrapper);
        if (count > 0) {
            return getFailResult("400", "名称已存在,请修改名称");
        }

        final TUser tUser = getcurUser();
        if (tUser != null) {
            learningContent.setOrganCode(tUser.getOrgCode());
        }
        learningContent.setAuditStatus(AuditStatusEnum.TBC.name());
        learningContent.setPublished(false);
        QueryWrapper<LearningContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(sortorder) as sortorder");
        LearningContent content = this.learningContentService.getOne(queryWrapper);
        if (content != null && content.getSortorder() != null) {
            learningContent.setSortorder(content.getSortorder() + 1);
        } else {
            learningContent.setSortorder(1);
        }
        // 保存业务节点信息
        boolean result = learningContentService.save(learningContent);
        final String learningContentId = learningContent.getId();

        final List<String> exhibitionBoardCatIdList = learningContent.getExhibitionBoardCatIdList();
        for (String exhibitionBoardCatId : exhibitionBoardCatIdList) {
            LearningContentBoardCat learningContentBoardCat = LearningContentBoardCat.builder().exhibitionBoardCatId(exhibitionBoardCatId).learningContentId(learningContentId).build();
            this.learningContentBoardCatService.save(learningContentBoardCat);
        }

        final List<String> copyrightOwnerIdList = learningContent.getCopyrightOwnerIdList();
        for (String copyrightOwnerId : copyrightOwnerIdList) {
            LearningContentCopyrightOwner contentCopyrightOwner = LearningContentCopyrightOwner.builder().copyrightOwnerId(copyrightOwnerId).learningContentId(learningContentId).build();
            this.learningContentCopyrightOwnerService.save(contentCopyrightOwner);
        }

        final List<String> exhibitionBoardIdList = learningContent.getExhibitionBoardIdList();
        for (String exhibitionBoardId : exhibitionBoardIdList) {
            LearningContentBoard learningContentBoard = LearningContentBoard.builder()
                    .learningContentId(learningContentId)
                    .exhibitionBoardCatId(this.exhibitionBoardService.getById(exhibitionBoardId).getExhibitionBoardCatId())
                    .exhibitionBoardId(exhibitionBoardId)
                    .build();
            QueryWrapper<LearningContentBoard> learningContentBoardQueryWrapper = new QueryWrapper<>();
            learningContentBoardQueryWrapper.select("max(sortorder) as sortorder");
            LearningContentBoard one = this.learningContentBoardService.getOne(learningContentBoardQueryWrapper);
            if (one != null && one.getSortorder() != null) {
                learningContent.setSortorder(one.getSortorder() + 1);
            } else {
                learningContent.setSortorder(1);
            }
            this.learningContentBoardService.save(learningContentBoard);
        }

        // 返回操作结果
        if (result) {
            final Audit audit = Audit.builder()
                    .content(learningContent.getName())
                    .name(learningContent.getName())
                    .refItemId(learningContent.getId())
                    .type(AuditTypeEnum.LEARNING_CONTENT.name())
                    .userId(tUser.getId())
                    .operation(AuditOperationEnum.ADD.name())
                    .status(AuditStatusEnum.TBC.name())
                    .level(AuditStatusEnum.TBC.name())
                    .build();
            this.auditService.save(audit);
            return getSuccessResult();
        } else {
            // 保存失败
            return getFailResult();
        }
    }

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:update")
    @ApiOperation(value = "修改学习内容信息", notes = "修改学习内容信息")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.UPDATE)
    public Map<String, Object> updateLearningContent(@Validated(value = {Update.class}) LearningContent learningContent) {
        final LambdaQueryWrapper<LearningContent> lambdaQueryWrapper = Wrappers.<LearningContent>lambdaQuery().eq(LearningContent::getName, learningContent.getName().trim());
        lambdaQueryWrapper.ne(LearningContent::getId, learningContent.getId());
        final int count = this.learningContentService.count(lambdaQueryWrapper);
        if (count > 0) {
            return getFailResult("400", "名称已存在,请修改名称");
        }

        final LearningContent one = this.learningContentService.getById(learningContent.getId());
        one.setAuditStatus(AuditStatusEnum.TBC.name());
        this.learningContentService.updateById(one);

        final Audit audit = Audit.builder()
                .content(learningContent.getName())
                .name(learningContent.getName())
                .userId(getcurUser().getId())
                .refItemId(learningContent.getId())
                .type(AuditTypeEnum.LEARNING_CONTENT.name())
                .operation(AuditOperationEnum.EDIT.name())
                .status(AuditStatusEnum.TBC.name())
                .level(AuditStatusEnum.TBC.name())
                .modelData(JSONObject.toJSONString(learningContent))
                .build();
        this.auditService.save(audit);
        return getSuccessResult();
    }

    @GetMapping("/getList")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:list")
    @ApiOperation(value = "获取学习内容全部列表(无分页)", notes = "获取学习内容全部列表(无分页)")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "auditStatus", value = "审核状态", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "learningProjectId", value = "学习项目ID", paramType = "query", dataType = "String")
    })
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.SELECT)
    public Map<String, Object> getLearningContentList(@RequestParam(value = "auditStatus", defaultValue = "APPROVED_FINAL", required = false) AuditStatusEnum auditStatus,
                                                      @RequestParam(value = "learningProjectId", required = false) String learningProjectId) {
        final LambdaQueryWrapper<LearningContent> lambdaQueryWrapper = Wrappers.<LearningContent>lambdaQuery().eq(LearningContent::getAuditStatus, auditStatus.name());
        lambdaQueryWrapper.eq(LearningContent::getPublished, true);
        if (StringUtils.isNotBlank(learningProjectId)) {
            lambdaQueryWrapper.eq(LearningContent::getLearningProjectId, learningProjectId);
        }
        List<LearningContent> learningContentList = learningContentService.list(lambdaQueryWrapper);
        return getResult(learningContentList);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "learningProjectId", value = "学习项目ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "nameOrCode", value = "名称或编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "创建时间-开始", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "创建时间-结束", paramType = "query", dataType = "String")
    })
    @PostMapping("/getPageList")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:page")
    @ApiOperation(value = "获取学习内容分页列表", notes = "获取学习内容分页列表")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.SELECT)
    public Map<String, Object> getLearningContentPageList(GenericPageParam genericPageParam, @RequestParam(value = "learningProjectId", required = false) String learningProjectId) {
        LambdaQueryWrapper<LearningContent> queryWrapper = new LambdaQueryWrapper<>();
        // 根据创建时间区间检索
        if (genericPageParam.getIsPublished() != null) {
            queryWrapper.eq(LearningContent::getPublished, genericPageParam.getIsPublished());
        }
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(learningProjectId)) {
            queryWrapper.eq(LearningContent::getLearningProjectId, learningProjectId);
        }
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
            queryWrapper.like(LearningContent::getName, genericPageParam.getNameOrCode());
        }
        // 根据创建时间区间检索
        if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
            queryWrapper.ge(LearningContent::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(LearningContent::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
        }
        // 设置排序规则
        queryWrapper.orderByDesc(LearningContent::getSortorder);
        // 设置查询内容
        queryWrapper.select(
                LearningContent::getId,
                LearningContent::getName,
                LearningContent::getApplicableScope,
                LearningContent::getCreatorName,
                LearningContent::getAuditStatus,
                LearningContent::getPublished,
                LearningContent::getDeleted,
                LearningContent::getSortorder,
                LearningContent::getCreateTime,
                LearningContent::getUpdateTime);
        Page<LearningContent> page = this.learningContentService.page(getPage(), queryWrapper);
        for (LearningContent learningContent : page.getRecords()) {
            LambdaQueryWrapper<LearningContentBoard> lambdaQueryWrapper = Wrappers.<LearningContentBoard>lambdaQuery().eq(LearningContentBoard::getLearningContentId, learningContent.getId());
            int exhibitionBoardCount = this.learningContentBoardService.count(lambdaQueryWrapper);
            learningContent.setExhibitionBoardCount(exhibitionBoardCount);

//            LambdaQueryWrapper<LearningContentBoardCat> boardCatLambdaQueryWrapper = Wrappers.<LearningContentBoardCat>lambdaQuery().eq(LearningContentBoardCat::getLearningContentId, learningContent.getId());
//            boardCatLambdaQueryWrapper.select(LearningContentBoardCat::getExhibitionBoardCatId);
//            List<String> exhibitionBoardCatIdList = this.learningContentBoardCatService.listObjs(boardCatLambdaQueryWrapper, Object::toString);
//            List<ExhibitionBoardCat> exhibitionBoardCatList = this.exhibitionBoardCatService.listByIds(exhibitionBoardCatIdList);
//            String exhibitionBoardCatNames = exhibitionBoardCatList.stream().map(ExhibitionBoardCat::getName).collect(Collectors.joining("、"));
//            learningContent.setExhibitionBoardCatNames(exhibitionBoardCatNames);
//
//            LambdaQueryWrapper<LearningContentCopyrightOwner> copyrightOwnerLambdaQueryWrapper = Wrappers.<LearningContentCopyrightOwner>lambdaQuery().eq(LearningContentCopyrightOwner::getLearningContentId, learningContent.getId());
//            copyrightOwnerLambdaQueryWrapper.select(LearningContentCopyrightOwner::getCopyrightOwnerId);
//             List<String> copyrightOwnerIdList = this.learningContentCopyrightOwnerService.listObjs(copyrightOwnerLambdaQueryWrapper, Object::toString);
//            List<CopyrightOwner> copyrightOwnerList = this.copyrightOwnerService.listByIds(copyrightOwnerIdList);
//            String copyrightOwnerNames = copyrightOwnerList.stream().map(CopyrightOwner::getName).collect(Collectors.joining("、"));
//            learningContent.setCopyrightOwnerNames(copyrightOwnerNames);

            learningContent.setExhibitionBoardCount(exhibitionBoardCount);
        }
        return getResult(page);
    }

    @ApiOperation(value = "获取学习内容详情", notes = "获取学习内容详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/get/{id}")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:get:id")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.SELECT)
    public Map<String, Object> getById(@PathVariable("id") String id) {
        LearningContent learningContent = learningContentService.getById(id);

        LearningProject learningProject = this.learningProjectService.getById(learningContent.getLearningProjectId());
        if (learningProject != null) {
            learningContent.setLearningProjectName(learningProject.getName());
        }

        final LambdaQueryWrapper<LearningContentBoardCat> queryWrapper = Wrappers.<LearningContentBoardCat>lambdaQuery().eq(LearningContentBoardCat::getLearningContentId, id);
        queryWrapper.select(LearningContentBoardCat::getExhibitionBoardCatId);
        final List<String> exhibitionBoardCatIdList = this.learningContentBoardCatService.listObjs(queryWrapper, Object::toString);
        if (!exhibitionBoardCatIdList.isEmpty()) {
            final List<ExhibitionBoardCat> exhibitionBoardCats = this.exhibitionBoardCatService.listByIds(exhibitionBoardCatIdList);
            learningContent.setExhibitionBoardCatIdList(exhibitionBoardCats.stream().map(ExhibitionBoardCat::getId).collect(Collectors.toList()));
            learningContent.setExhibitionBoardCatNameList(exhibitionBoardCats.stream().map(ExhibitionBoardCat::getName).collect(Collectors.toList()));
        }

        final LambdaQueryWrapper<LearningContentCopyrightOwner> queryWrapper1 = Wrappers.<LearningContentCopyrightOwner>lambdaQuery().eq(LearningContentCopyrightOwner::getLearningContentId, id);
        queryWrapper1.select(LearningContentCopyrightOwner::getCopyrightOwnerId);
        final List<String> copyrightOwnerIdList = this.learningContentCopyrightOwnerService.listObjs(queryWrapper1, Object::toString);
        if (!copyrightOwnerIdList.isEmpty()) {
            final List<CopyrightOwner> copyrightOwnerList = this.copyrightOwnerService.listByIds(copyrightOwnerIdList);
            learningContent.setCopyrightOwnerIdList(copyrightOwnerList.stream().map(CopyrightOwner::getId).collect(Collectors.toList()));
            learningContent.setCopyrightOwnerNameList(copyrightOwnerList.stream().map(CopyrightOwner::getName).collect(Collectors.toList()));
        }

        final LambdaQueryWrapper<LearningContentBoard> queryWrapper2 = Wrappers.<LearningContentBoard>lambdaQuery().eq(LearningContentBoard::getLearningContentId, id);
        queryWrapper2.select(LearningContentBoard::getExhibitionBoardId);
        final List<String> exhibitionBoardIdList = this.learningContentBoardService.listObjs(queryWrapper2, Object::toString);
        if (!exhibitionBoardIdList.isEmpty()) {
            final List<ExhibitionBoard> exhibitionBoardList = this.exhibitionBoardService.listByIds(exhibitionBoardIdList);
            if (!exhibitionBoardList.isEmpty()) {
                learningContent.setExhibitionBoardIdList(exhibitionBoardList.stream().map(ExhibitionBoard::getId).collect(Collectors.toList()));
                learningContent.setExhibitionBoardNameList(exhibitionBoardList.stream().map(ExhibitionBoard::getName).collect(Collectors.toList()));
            }

            for (ExhibitionBoard exhibitionBoard : exhibitionBoardList) {
                String exhibitionBoardCatId = exhibitionBoard.getExhibitionBoardCatId();
                if (exhibitionBoardCatId != null) {
                    exhibitionBoard.setExhibitionBoardCatName(this.exhibitionBoardCatService.getById(exhibitionBoardCatId).getName());
                }
                String boardCopyrightOwnerId = exhibitionBoard.getBoardCopyrightOwnerId();
                if (boardCopyrightOwnerId != null) {
                    final CopyrightOwner copyrightOwner = this.copyrightOwnerService.getById(boardCopyrightOwnerId);
                    if (copyrightOwner != null) {
                        exhibitionBoard.setBoardCopyrightOwnerName(copyrightOwner.getName());
                    }
                }
                if (exhibitionBoard.getVideoContentCopyrightOwnerId() != null) {
                    String name = this.copyrightOwnerService.getById(exhibitionBoard.getVideoContentCopyrightOwnerId()).getName();
                    exhibitionBoard.setVideoContentCopyrightOwnerName(name);
                }

                LambdaQueryWrapper<Asset> assetQueryWrapper = Wrappers.<Asset>lambdaQuery().eq(Asset::getRefItemId, exhibitionBoard.getId());
                assetQueryWrapper.eq(Asset::getPublished, true);
                assetQueryWrapper.eq(Asset::getFileCat, FileCatEnum.EXHIBITION_BOARD_AUDIO.name());
                final List<Asset> audioList = this.assetService.list(assetQueryWrapper);
                exhibitionBoard.setAudioList(audioList);

                assetQueryWrapper.clear();
                assetQueryWrapper = Wrappers.<Asset>lambdaQuery().eq(Asset::getRefItemId, exhibitionBoard.getId());
                assetQueryWrapper.eq(Asset::getPublished, true);
                assetQueryWrapper.eq(Asset::getFileCat, FileCatEnum.EXHIBITION_BOARD_DATUM.name());
                final List<Asset> datumList = this.assetService.list(assetQueryWrapper);
                exhibitionBoard.setDatumList(datumList);

                String videoContentId = exhibitionBoard.getVideoContentId();
                if (videoContentId != null) {
                    final VideoContent videoContent = this.videoContentService.getOne(Wrappers.<VideoContent>lambdaQuery().eq(VideoContent::getId, videoContentId));
                    if (videoContent != null) {
                        assetQueryWrapper.clear();
                        assetQueryWrapper = Wrappers.<Asset>lambdaQuery().eq(Asset::getRefItemId, videoContentId);
                        assetQueryWrapper.eq(Asset::getPublished, true);
                        assetQueryWrapper.eq(Asset::getFileCat, FileCatEnum.VIDEO_CONTENT.name());
                        final List<Asset> videoList = this.assetService.list(assetQueryWrapper);
                        exhibitionBoard.setVideoList(videoList);
                        exhibitionBoard.setVideoContentName(videoContent.getName());
                    }
                }
            }
            learningContent.setExhibitionBoardList(exhibitionBoardList);
        }

        final LambdaQueryWrapper<Audit> auditQueryWrapper = Wrappers.<Audit>lambdaQuery().eq(Audit::getRefItemId, id);
        auditQueryWrapper.select(Audit::getContent);
        auditQueryWrapper.select(Audit::getType);
        auditQueryWrapper.select(Audit::getOperation);
        auditQueryWrapper.select(Audit::getStatus);
        auditQueryWrapper.select(Audit::getFirstTime);
        auditQueryWrapper.select(Audit::getFirstRemarks);
        auditQueryWrapper.select(Audit::getSecondTime);
        auditQueryWrapper.select(Audit::getSecondTime);
        auditQueryWrapper.select(Audit::getLevel);
        final List<Audit> auditList = this.auditService.list(auditQueryWrapper);
        learningContent.setAuditHistoryList(auditList);

        return getResult(learningContent);
    }

    @ApiOperation(value = "获取学习内容详情(审核详情使用)", notes = "获取学习内容详情(审核详情使用)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "审核ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/getAudit/{id}")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:get:id")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.SELECT)
    public Map<String, Object> getAuditInfoById(@PathVariable("auditId") String auditId) {
        final LearningContent learningContent = JSONObject.parseObject(this.auditService.getById(auditId).getModelData(), LearningContent.class);
        String id = learningContent.getId();
        LearningProject learningProject = this.learningProjectService.getById(learningContent.getLearningProjectId());
        if (learningProject != null) {
            learningContent.setLearningProjectName(learningProject.getName());
        }

        final LambdaQueryWrapper<LearningContentBoardCat> queryWrapper = Wrappers.<LearningContentBoardCat>lambdaQuery().eq(LearningContentBoardCat::getLearningContentId, id);
        queryWrapper.select(LearningContentBoardCat::getExhibitionBoardCatId);
        final List<String> exhibitionBoardCatIdList = this.learningContentBoardCatService.listObjs(queryWrapper, Object::toString);
        if (!exhibitionBoardCatIdList.isEmpty()) {
            final List<ExhibitionBoardCat> exhibitionBoardCats = this.exhibitionBoardCatService.listByIds(exhibitionBoardCatIdList);
            learningContent.setExhibitionBoardCatIdList(exhibitionBoardCats.stream().map(ExhibitionBoardCat::getId).collect(Collectors.toList()));
            learningContent.setExhibitionBoardCatNameList(exhibitionBoardCats.stream().map(ExhibitionBoardCat::getName).collect(Collectors.toList()));
        }

        final LambdaQueryWrapper<LearningContentCopyrightOwner> learningContentCopyrightOwnerLambdaQueryWrapper = Wrappers.<LearningContentCopyrightOwner>lambdaQuery().eq(LearningContentCopyrightOwner::getLearningContentId, id);
        learningContentCopyrightOwnerLambdaQueryWrapper.select(LearningContentCopyrightOwner::getCopyrightOwnerId);
        final List<String> copyrightOwnerIdList = this.learningContentCopyrightOwnerService.listObjs(learningContentCopyrightOwnerLambdaQueryWrapper, Object::toString);
        if (!copyrightOwnerIdList.isEmpty()) {
            final List<CopyrightOwner> copyrightOwnerList = this.copyrightOwnerService.listByIds(copyrightOwnerIdList);
            learningContent.setCopyrightOwnerIdList(copyrightOwnerList.stream().map(CopyrightOwner::getId).collect(Collectors.toList()));
            learningContent.setCopyrightOwnerNameList(copyrightOwnerList.stream().map(CopyrightOwner::getName).collect(Collectors.toList()));
        }

        final LambdaQueryWrapper<LearningContentBoard> learningContentBoardLambdaQueryWrapper = Wrappers.<LearningContentBoard>lambdaQuery().eq(LearningContentBoard::getLearningContentId, id);
        learningContentBoardLambdaQueryWrapper.select(LearningContentBoard::getExhibitionBoardId);
        final List<String> exhibitionBoardIdList = this.learningContentBoardService.listObjs(learningContentBoardLambdaQueryWrapper, Object::toString);
        if (!exhibitionBoardIdList.isEmpty()) {
            final List<ExhibitionBoard> exhibitionBoardList = this.exhibitionBoardService.listByIds(exhibitionBoardIdList);
            if (!exhibitionBoardList.isEmpty()) {
                learningContent.setExhibitionBoardIdList(exhibitionBoardList.stream().map(ExhibitionBoard::getId).collect(Collectors.toList()));
                learningContent.setExhibitionBoardNameList(exhibitionBoardList.stream().map(ExhibitionBoard::getName).collect(Collectors.toList()));
            }

            for (ExhibitionBoard exhibitionBoard : exhibitionBoardList) {
                String exhibitionBoardCatId = exhibitionBoard.getExhibitionBoardCatId();
                if (exhibitionBoardCatId != null) {
                    exhibitionBoard.setExhibitionBoardCatName(this.exhibitionBoardCatService.getById(exhibitionBoardCatId).getName());
                }
                String boardCopyrightOwnerId = exhibitionBoard.getBoardCopyrightOwnerId();
                if (boardCopyrightOwnerId != null) {
                    final CopyrightOwner copyrightOwner = this.copyrightOwnerService.getById(boardCopyrightOwnerId);
                    if (copyrightOwner != null) {
                        exhibitionBoard.setBoardCopyrightOwnerName(copyrightOwner.getName());
                    }
                }
                if (exhibitionBoard.getVideoContentCopyrightOwnerId() != null) {
                    String name = this.copyrightOwnerService.getById(exhibitionBoard.getVideoContentCopyrightOwnerId()).getName();
                    exhibitionBoard.setVideoContentCopyrightOwnerName(name);
                }

                LambdaQueryWrapper<Asset> assetQueryWrapper = Wrappers.<Asset>lambdaQuery().eq(Asset::getRefItemId, exhibitionBoard.getId());
                assetQueryWrapper.eq(Asset::getPublished, false);
                assetQueryWrapper.eq(Asset::getFileCat, FileCatEnum.EXHIBITION_BOARD_AUDIO.name());
                final List<Asset> audioList = this.assetService.list(assetQueryWrapper);
                exhibitionBoard.setAudioList(audioList);

                assetQueryWrapper.clear();
                assetQueryWrapper = Wrappers.<Asset>lambdaQuery().eq(Asset::getRefItemId, exhibitionBoard.getId());
                assetQueryWrapper.eq(Asset::getPublished, false);
                assetQueryWrapper.eq(Asset::getFileCat, FileCatEnum.EXHIBITION_BOARD_DATUM.name());
                final List<Asset> datumList = this.assetService.list(assetQueryWrapper);
                exhibitionBoard.setDatumList(datumList);

                String videoContentId = exhibitionBoard.getVideoContentId();
                if (videoContentId != null) {
                    final VideoContent videoContent = this.videoContentService.getOne(Wrappers.<VideoContent>lambdaQuery().eq(VideoContent::getId, videoContentId));
                    if (videoContent != null) {
                        assetQueryWrapper.clear();
                        assetQueryWrapper = Wrappers.<Asset>lambdaQuery().eq(Asset::getRefItemId, videoContentId);
                        assetQueryWrapper.eq(Asset::getPublished, false);
                        assetQueryWrapper.eq(Asset::getFileCat, FileCatEnum.VIDEO_CONTENT.name());
                        final List<Asset> videoList = this.assetService.list(assetQueryWrapper);
                        exhibitionBoard.setVideoList(videoList);
                        exhibitionBoard.setVideoContentName(videoContent.getName());
                    }
                }
            }
            learningContent.setExhibitionBoardList(exhibitionBoardList);
        }

        final LambdaQueryWrapper<Audit> auditQueryWrapper = Wrappers.<Audit>lambdaQuery().eq(Audit::getRefItemId, id);
        auditQueryWrapper.select(Audit::getContent);
        auditQueryWrapper.select(Audit::getType);
        auditQueryWrapper.select(Audit::getOperation);
        auditQueryWrapper.select(Audit::getStatus);
        auditQueryWrapper.select(Audit::getFirstTime);
        auditQueryWrapper.select(Audit::getFirstRemarks);
        auditQueryWrapper.select(Audit::getSecondTime);
        auditQueryWrapper.select(Audit::getSecondTime);
        auditQueryWrapper.select(Audit::getLevel);
        final List<Audit> auditList = this.auditService.list(auditQueryWrapper);
        learningContent.setAuditHistoryList(auditList);

        return getResult(learningContent);
    }

    /**
     * 通用排序方法(拖拽排序/所有排序完成后点击保存)
     *
     * @param sourceId 源实体ID
     * @param targetId 目标实体ID
     * @return Void
     */
    @ApiOperation(value = "学习内容排序")
    @PutMapping(value = "/sort")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:sort")
    public Map<String, Object> updateSortorder(String sourceId, String targetId) {
        LearningContent theSource = this.learningContentService.getById(sourceId);
        LearningContent theTarget = this.learningContentService.getById(targetId);
        String moveType = theSource.getSortorder() > theTarget.getSortorder() ? "down" : "up";
        Integer sourceSortorder = theSource.getSortorder();
        Integer targetSortorder = theTarget.getSortorder();

        //默认sortorder为降序排序,向上移动
        if ("up".equalsIgnoreCase(moveType) && sourceSortorder < targetSortorder) {
            QueryWrapper<LearningContent> wrapper = new QueryWrapper<>();
            wrapper.between("sortorder", sourceSortorder, targetSortorder);
            wrapper.select("id", "sortorder");
            List<LearningContent> list = this.learningContentService.list(wrapper);
            for (LearningContent entity : list) {
                if (!entity.getId().equals(sourceId)) {
                    entity.setSortorder(entity.getSortorder() - 1);
                    this.learningContentService.updateById(entity);
                }
            }
            theSource.setSortorder(targetSortorder);
            this.learningContentService.updateById(theSource);
        }
        //默认sortorder为降序排序,向下移动
        else if ("down".equalsIgnoreCase(moveType) && sourceSortorder > targetSortorder) {
            QueryWrapper<LearningContent> wrapper = new QueryWrapper<>();
            wrapper.between("sortorder", targetSortorder, sourceSortorder);
            wrapper.select("id", "sortorder");
            List<LearningContent> slideList = this.learningContentService.list(wrapper);
            for (LearningContent entity : slideList) {
                if (!entity.getId().equals(sourceId)) {
                    entity.setSortorder(entity.getSortorder() + 1);
                    this.learningContentService.updateById(entity);
                }
            }
            theSource.setSortorder(targetSortorder);
            this.learningContentService.updateById(theSource);
        }
        //默认sortorder为正序排序,向下移动
        else if ("down".equalsIgnoreCase(moveType) && sourceSortorder < targetSortorder) {
            QueryWrapper<LearningContent> wrapper = new QueryWrapper<>();
            wrapper.between("sortorder", sourceSortorder, targetSortorder);
            wrapper.select("id", "sortorder");
            List<LearningContent> slideList = this.learningContentService.list(wrapper);
            for (LearningContent slide : slideList) {
                if (!slide.getId().equals(sourceId)) {
                    slide.setSortorder(slide.getSortorder() - 1);
                    this.learningContentService.updateById(slide);
                }
            }
            theSource.setSortorder(targetSortorder);
            this.learningContentService.updateById(theSource);
        }
        //默认sortorder为正序排序,向上移动
        else if ("up".equalsIgnoreCase(moveType) && sourceSortorder > targetSortorder) {
            QueryWrapper<LearningContent> wrapper = new QueryWrapper<>();
            wrapper.between("sortorder", targetSortorder, sourceSortorder);
            wrapper.select("id", "sortorder");
            List<LearningContent> slideList = this.learningContentService.list(wrapper);
            for (LearningContent slide : slideList) {
                if (!slide.getId().equals(sourceId)) {
                    slide.setSortorder(slide.getSortorder() + 1);
                    this.learningContentService.updateById(slide);
                }
            }
            theSource.setSortorder(targetSortorder);
            this.learningContentService.updateById(theSource);
        }
        return getSuccessResult();
    }

    @ApiOperation(value = "启用/禁用学习内容", notes = "启用/禁用学习内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "isPublish", value = "是否启用", dataType = "boolean", paramType = "query", allowableValues = "True, False")
    })
    @PutMapping("/enable/{id}")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:enable")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.ENABLE)
    public Map<String, Object> enableLearningContent(@PathVariable("id") String id, @RequestParam("isPublish") Boolean isPublish) {
        TUser user = getcurUser();

        LearningContent learningContent = this.learningContentService.getById(id);
        final Audit audit = Audit.builder()
                .content(learningContent.getName())
                .name(learningContent.getName())
                .refItemId(id)
                .userId(user.getId())
                .type(AuditTypeEnum.LEARNING_CONTENT.name())
                .operation(isPublish ? AuditOperationEnum.ENABLE.name() : AuditOperationEnum.DISABLE.name())
                .status(AuditStatusEnum.TBC.name())
                .level(AuditStatusEnum.TBC.name())
                .build();
        this.auditService.save(audit);
        this.learningContentService.updateById(LearningContent.builder().id(id).auditStatus(AuditStatusEnum.TBC.name()).build());
        return getSuccessResult();
    }

}