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.util.ListUtil;
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.vo.AssetVo;
import cn.chnmuseum.party.web.controller.base.BaseController;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
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;
    @Autowired
    TOrganService organService;

    @Resource
    private LearningContentAssetService learningContentAssetService;

    @PostMapping("/save")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:save")
    @ApiOperation(value = "添加学习内容", notes = "添加学习内容")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.ADD)
    @Transactional
    public Map<String, Object> saveLearningContent(@Validated(value = {Add.class}) LearningContent learningContent, Boolean isMajor) {
        TUser tUser1 = getcurUser();
        if ("1".equals(tUser1.getType())){
            learningContent.setCreateType(1);
        }else {
            learningContent.setCreateType(2);
        }
        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());
        }
        //
        boolean nonUnitRole = !isUnitRole(tUser);
        if (nonUnitRole){
            learningContent.setAuditStatus(AuditStatusEnum.TBC.name());
        }else {
            //是单位管理员直接变成通过
            learningContent.setAuditStatus(AuditStatusEnum.APPROVED_FINAL.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);
        }
        // 如果isMajor为null则新建学习内容为子学习内容
        if (isMajor == null) {
            learningContent.setIsMajor(false);
        }else {
            learningContent.setIsMajor(true);
        }
        // 保存业务节点信息
        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);
                learningContentBoard.setSortorder(one.getSortorder() + 1);
            } else {
//                learningContent.setSortorder(1);
                learningContentBoard.setSortorder(1);
            }
            this.learningContentBoardService.save(learningContentBoard);
        }

        // 保存需要在app端显示的参考资料
        List<String> fileList = learningContent.getFileList();
        if (!CollectionUtils.isEmpty(fileList)) {
            List<LearningContentAsset> learningContentAssets = new ArrayList<>();
            List<Asset> assets = this.assetService.listByIds(fileList);
            assets.forEach(asset -> {
                LearningContentAsset learningContentAsset = LearningContentAsset.builder()
                        .learningContentId(learningContentId)
                        .boardId(asset.getRefItemId())
                        .assetId(asset.getId())
                        .build();
                learningContentAssets.add(learningContentAsset);
            });
            boolean b = this.learningContentAssetService.saveBatch(learningContentAssets);
            if (!b) {
                return getFailResult("添加数据失败!");
            }
        }

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

    /**
     * 判断是否为单位管理员
     *
     * @param tUser
     * @return
     */
    private boolean isUnitRole(TUser tUser) {
        boolean result = false;
        if (tUser != null) {
            List<String> roleList = tUser.getRoleList();
            if (!CollectionUtils.isEmpty(roleList)) {
                //单位管理员角色id为2
                result = roleList.contains("2");
            }
        }
        return result;
    }

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("learning:content:update")
    @ApiOperation(value = "修改学习内容信息", notes = "修改学习内容信息")
    @MethodLog(operModule = OperModule.LEARNCONTENT, operType = OperType.UPDATE)
    @Transactional
    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());

        //单位管理员只能修改所属机构及其子机构下的的学习内容
        List<String> curUserSubOrgIds = getCurUserSubOrgIds();
        if (!CollectionUtils.isEmpty(curUserSubOrgIds)){
            String organCode = one.getOrganCode();
            boolean contains = curUserSubOrgIds.contains(organCode);
            if (!contains){
                return getFailResult("单位管理员只能修改所属机构及其子机构的学习内容");
            }
        }

        one.setAuditStatus(AuditStatusEnum.TBC.name());
        this.learningContentService.updateById(one);

        final TUser tUser = getcurUser();
        final Audit audit = Audit.builder()
                .content(learningContent.getName())
                .name(learningContent.getName())
                .userId(tUser.getId())
                .organId(tUser.getOrgId())
                .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<>();
        // 分页查询这里不包括主学习内容
        queryWrapper.eq(LearningContent::getIsMajor, false);
        // 上级机构
//        List<String> curUserParOrgIds = getCurUserParOrgIds();

        // 下级机构展板
        List<String> curUserSubOrgIds = getCurUserSubOrgIds();
        if (!CollectionUtils.isEmpty(curUserSubOrgIds)){
            List<String> list = Arrays.asList("ALL_PLAT");
            queryWrapper.and(s -> {
//                if (CollectionUtil.isEmpty(curUserParOrgIds)){
//                s.in(LearningContent::getOrganCode, curUserSubOrgIds)
//                        .or().in(LearningContent::getApplicableScope, list);
//                }else{
//                    s.in(LearningContent::getOrganCode, curUserSubOrgIds)
//                            .or().in(LearningContent::getApplicableScope, list)
//                            .or(q ->q.in(LearningContent::getOrganCode, curUserParOrgIds)
//                                    .eq(LearningContent::getApplicableScope,"THIS_ORGAN_SUB"));
//                }
                    s.in(LearningContent::getOrganCode, curUserSubOrgIds)
                            .or().in(LearningContent::getApplicableScope, list);
            });

        }

        // 根据创建时间区间检索
        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::getCreateType,
                LearningContent::getUpdateTime);
        Page<LearningContent> page = this.learningContentService.page(getPage(), queryWrapper);
        for (LearningContent learningContent : page.getRecords()) {
            LambdaQueryWrapper<LearningContentBoard> lambdaQueryWrapper = Wrappers.<LearningContentBoard>lambdaQuery()
                    .select(LearningContentBoard::getExhibitionBoardId)
                    .eq(LearningContentBoard::getLearningContentId, learningContent.getId());
//            int exhibitionBoardCount = this.learningContentBoardService.count(lambdaQueryWrapper);
            List<String> exhibitionBoardIds = learningContentBoardService.listObjs(lambdaQueryWrapper, Object::toString);
            LambdaQueryWrapper<ExhibitionBoard> ExhibitionBoardIn = Wrappers.<ExhibitionBoard>lambdaQuery().in(ExhibitionBoard::getId, exhibitionBoardIds).eq(ExhibitionBoard::getPublished,true);
            int count = exhibitionBoardService.count(ExhibitionBoardIn);
//            learningContent.setExhibitionBoardCount(exhibitionBoardCount);
            learningContent.setExhibitionBoardCount(count);

//            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);
    }

    /**
     *  获取当前用户的上级机构
     */
    public List<String> getCurUserParOrgIds() {
        TUser tUser = getcurUser();

        // 上级机构
        List<String> parGranCode = new ArrayList<>();
        String orgId = tUser.getOrgId();

        TOrgan tOrgan = this.organService.getById(orgId);
        if (!"0".equals(tOrgan.getParentId())) {
            TOrgan tOrgan1 = this.organService.getById(tOrgan.getParentId());
            parGranCode.add(tOrgan1.getCode());
            if (!"0".equals(tOrgan1.getParentId())) {
                TOrgan tOrgan2 = this.organService.getById(tOrgan1.getParentId());
                parGranCode.add(tOrgan2.getCode());
            }
        }
        return parGranCode;
    }

    /**
     * 获取当前用户的所有子机构
     *
     * @return
     */
    public List<String> getCurUserSubOrgIds() {
        TUser tUser = getcurUser();
        if (tUser == null || StringUtils.isBlank(tUser.getOrgId())) {
            return null;
        }
        //平台管理员、单位管理员、学习内容管理员  单位管理员不能看到其它非同一机构的单位管理员
        List<String> roleList = tUser.getRoleList();
        boolean condition = !CollectionUtils.isEmpty(roleList)   //不为空
                && roleList.contains("2")      //2是单位管理员
                && !roleList.contains("1")        //不包含 1是平台管理员
                && !roleList.contains("8");       //不包含  8是学习内容管理员

        //不是只为单位管理员这种情况查询全部
//        userRoleService
        if (!condition) {
            return null;
        }
        String orgId = tUser.getOrgId();
        LambdaQueryWrapper<TOrgan> wrapper = new QueryWrapper<TOrgan>().lambda()
                .select(TOrgan::getId, TOrgan::getParentId, TOrgan::getCode)
                .eq(TOrgan::getIsDeleted, false);

        List<TOrgan> tOrgans = organService.list(wrapper);
        ArrayList<String> strings = new ArrayList<>();
        strings.add(orgId);
        List<String> result = new ArrayList<>();
        List<String> code = tOrgans.stream().filter(a -> a.getId().equals(orgId)).map(TOrgan::getCode).collect(Collectors.toList());
        if (code != null && code.size() >= 1) {
            result.add(code.get(0));
        }
        treeCode(strings, tOrgans, result);
        return result;
    }

    private void treeCode(List<String> parentCodes, List<TOrgan> all, List<String> codes) {
        if (CollectionUtils.isEmpty(parentCodes)) {
            return;
        }
        ArrayList<String> idArray = new ArrayList<>();
        parentCodes.stream().forEach(s -> {
            List<TOrgan> subOrgans = all.stream().filter(a -> a.getParentId() != null && a.getParentId().equals(s)).collect(Collectors.toList());
            subOrgans.stream().forEach(sub -> {
                String code = sub.getCode();
                String id = sub.getId();
                codes.add(code);
                idArray.add(id);
            });
        });
        //递归查询
        treeCode(idArray, all, codes);
    }

    @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,LearningContentBoard::getSortorder)
                .orderByAsc(LearningContentBoard::getSortorder);
        final List<LearningContentBoard> exhibitionBoardIdListNew = this.learningContentBoardService.list(queryWrapper2);
        final List<String> exhibitionBoardIdList = exhibitionBoardIdListNew.stream().map(LearningContentBoard::getExhibitionBoardId).collect(Collectors.toList());

//        final List<String> exhibitionBoardIdList = this.learningContentBoardService.listObjs(queryWrapper2, Object::toString);
        if (!exhibitionBoardIdList.isEmpty()) {
            LambdaQueryWrapper<ExhibitionBoard> lambdaQuery = Wrappers.lambdaQuery();
            lambdaQuery.ne(ExhibitionBoard::getPublished, false);
            lambdaQuery.in(ExhibitionBoard::getId, exhibitionBoardIdList);
            List<ExhibitionBoard> exhibitionBoardList = this.exhibitionBoardService.list(lambdaQuery);
            //设置sortorder ,然后在排序
            exhibitionBoardList.stream().forEach(eb -> {
                exhibitionBoardIdListNew.stream().forEach(lcb -> {
                    if (eb.getId().equals(lcb.getExhibitionBoardId())) {
                        eb.setSortorder(lcb.getSortorder());
                    }
                });
            });
            exhibitionBoardList = exhibitionBoardList.stream().sorted(Comparator.comparing(ExhibitionBoard::getSortorder).reversed()).collect(Collectors.toList());

            if (!exhibitionBoardList.isEmpty()) {
                learningContent.setExhibitionBoardIdList(exhibitionBoardList.stream().sorted(Comparator.comparing(ExhibitionBoard::getSortorder).reversed()).map(ExhibitionBoard::getId).collect(Collectors.toList()));
                learningContent.setExhibitionBoardNameList(exhibitionBoardList.stream().sorted(Comparator.comparing(ExhibitionBoard::getSortorder).reversed()).map(ExhibitionBoard::getName).collect(Collectors.toList()));
            }

            for (ExhibitionBoard exhibitionBoard : exhibitionBoardList) {
                String exhibitionBoardCatId = exhibitionBoard.getExhibitionBoardCatId();
                if (StringUtils.isNotEmpty(exhibitionBoardCatId)) {
                    exhibitionBoard.setExhibitionBoardCatName(this.exhibitionBoardCatService.getById(exhibitionBoardCatId).getName());
                }
                String boardCopyrightOwnerId = exhibitionBoard.getBoardCopyrightOwnerId();
                if (StringUtils.isNotEmpty(boardCopyrightOwnerId)) {
                    final CopyrightOwner copyrightOwner = this.copyrightOwnerService.getById(boardCopyrightOwnerId);
                    if (copyrightOwner != null) {
                        exhibitionBoard.setBoardCopyrightOwnerName(copyrightOwner.getName());
                    }
                }
                if (StringUtils.isNotEmpty(exhibitionBoard.getVideoContentCopyrightOwnerId())) {
                    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::getFileCat, FileCatEnum.EXHIBITION_BOARD_AUDIO.name());
                assetQueryWrapper.eq(Asset::getPublished, true);
                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::getFileCat, FileCatEnum.EXHIBITION_BOARD_DATUM.name());
                assetQueryWrapper.eq(Asset::getPublished, true);
                final List<Asset> datumList = this.assetService.list(assetQueryWrapper);
                exhibitionBoard.setDatumList(datumList);

                String videoContentId = exhibitionBoard.getVideoContentId();
                if (StringUtils.isNotEmpty(videoContentId)) {
                    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::getFileCat, FileCatEnum.VIDEO_CONTENT.name());
                        assetQueryWrapper.eq(Asset::getPublished, true);
                        final List<Asset> videoList = this.assetService.list(assetQueryWrapper);
                        exhibitionBoard.setVideoList(videoList);
                        exhibitionBoard.setVideoContentName(videoContent.getName());
                    }
                }
            }
            learningContent.setExhibitionBoardList(exhibitionBoardList);
        }
        // 查询该学习内容下哪些展板参考资料在app展示
        LambdaQueryWrapper<LearningContentAsset> lambdaQueryWrapper = Wrappers.<LearningContentAsset>lambdaQuery().eq(LearningContentAsset::getLearningContentId, id);
        lambdaQueryWrapper.select(LearningContentAsset::getAssetId);
        List<String> list = this.learningContentAssetService.listObjs(lambdaQueryWrapper, Object::toString);
        if (CollectionUtil.isNotEmpty(list)) {
            List<Asset> assets = this.assetService.listByIds(list);
            List<AssetVo> assetVos = new ArrayList<>();
            for (Asset asset : assets) {
                ExhibitionBoard board = this.exhibitionBoardService.getById(asset.getRefItemId());
                AssetVo assetVo =  AssetVo.builder()
                        .id(asset.getId())
                        .fileName(asset.getFileName())
                        .fileType(asset.getFileExtName())
                        .boardName(board.getName())
                        .build();
                assetVos.add(assetVo);
            }
            learningContent.setAssetList(assetVos);
        }
        learningContent.setFileList(list);

        final LambdaQueryWrapper<Audit> auditQueryWrapper = Wrappers.<Audit>lambdaQuery().eq(Audit::getRefItemId, id);
        final List<Audit> auditList = this.auditService.list(auditQueryWrapper);
        learningContent.setAuditHistoryList(auditList);

        return getResult(learningContent);
    }

    @ApiOperation(value = "获取学习内容详情(审核详情使用)", notes = "获取学习内容详情(审核详情使用)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "auditId", value = "审核ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/getAudit/{auditId}")
    @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 List<String> copyrightOwnerIdList = learningContent.getCopyrightOwnerIdList();
        if (copyrightOwnerIdList != null && !copyrightOwnerIdList.isEmpty()) {
            final List<CopyrightOwner> copyrightOwnerList = this.copyrightOwnerService.listByIds(copyrightOwnerIdList);
            learningContent.setCopyrightOwnerIdList(copyrightOwnerIdList);
            learningContent.setCopyrightOwnerNameList(copyrightOwnerList.stream().map(CopyrightOwner::getName).collect(Collectors.toList()));
        }

        // 学习内容的展板分类
        final List<String> exhibitionBoardCatIdList = learningContent.getExhibitionBoardCatIdList();
        if (exhibitionBoardCatIdList != null && !exhibitionBoardCatIdList.isEmpty()) {
            final List<ExhibitionBoardCat> exhibitionBoardCats = this.exhibitionBoardCatService.listByIds(exhibitionBoardCatIdList);
            learningContent.setExhibitionBoardCatIdList(exhibitionBoardCatIdList);
            learningContent.setExhibitionBoardCatNameList(exhibitionBoardCats.stream().map(ExhibitionBoardCat::getName).collect(Collectors.toList()));
        }

        // 学习内容的展板列表
        final List<String> exhibitionBoardIdList = learningContent.getExhibitionBoardIdList();
        if (exhibitionBoardIdList != null && !exhibitionBoardIdList.isEmpty()) {
            final List<ExhibitionBoard> exhibitionBoardList = this.exhibitionBoardService.listByIds(exhibitionBoardIdList);
            if (!exhibitionBoardList.isEmpty()) {
                learningContent.setExhibitionBoardIdList(exhibitionBoardIdList);
                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 (StringUtils.isNotEmpty(boardCopyrightOwnerId )) {
                    final CopyrightOwner copyrightOwner = this.copyrightOwnerService.getById(boardCopyrightOwnerId);
                    if (copyrightOwner != null) {
                        exhibitionBoard.setBoardCopyrightOwnerName(copyrightOwner.getName());
                    }
                }
                if (StringUtils.isNotEmpty(exhibitionBoard.getVideoContentCopyrightOwnerId() )) {
                    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 (StringUtils.isNotEmpty(videoContentId)) {
                    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);
        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) {
        final TUser user = getcurUser();

        LearningContent learningContent = this.learningContentService.getById(id);

        //单位管理员只能禁用或启用所属机构及其子机构的学习内容
        List<String> curUserSubOrgIds = getCurUserSubOrgIds();
        if (!CollectionUtils.isEmpty(curUserSubOrgIds)){
            String organCode = learningContent.getOrganCode();
            boolean contains = curUserSubOrgIds.contains(organCode);
            if (!contains){
                return getFailResult("单位管理员只能禁用或启用所属机构及其子机构的学习内容");
            }
        }

        final Audit audit = Audit.builder()
                .content(learningContent.getName())
                .name(learningContent.getName())
                .refItemId(id)
                .userId(user.getId())
                .organId(user.getOrgId())
                .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();
    }

}