package cn.chnmuseum.party.web.controller;

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.vo.GenericPageParam;
import cn.chnmuseum.party.model.*;
import cn.chnmuseum.party.service.*;
import cn.chnmuseum.party.web.controller.base.BaseController;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * <pre>
 * 视频内容分类 前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-17
 */
@Slf4j
@RestController
@RequestMapping("/videoContentCat")
@Api(tags = {"视频内容分类接口"})
public class VideoContentCatController extends BaseController {

    @Resource
    private CopyrightOwnerVideoContentCatService copyrightOwnerVideoContentCatService;
    @Resource
    private VideoContentCatService videoContentCatService;
    @Resource
    private VideoContentService videoContentService;
    @Resource
    private CopyrightOwnerService copyrightOwnerService;
    @Resource
    private ExhibitionBoardService exhibitionBoardService;
    @Resource
    private LearningContentBoardCatService learningContentBoardCatService;
    @Resource
    private LearningContentBoardService learningContentBoardService;
    @Resource
    private LearningContentCopyrightOwnerService learningContentCopyrightOwnerService;
    @Resource
    private LearningContentService learningContentService;
    @Resource
    private AssetService assetService;

    @PostMapping(value = "/save")
    @RequiresAuthentication  //@RequiresPermissions("video:content:cat:save")
    @ApiOperation(value = "添加视频内容分类", notes = "添加视频内容分类")
    @MethodLog(operModule = OperModule.VIDEOCLASSIFY, operType = OperType.ADD)
    public Map<String, Object> saveVideoContentCat(@Validated(value = {Add.class}) VideoContentCat videoContentCat) {
        // 保存业务节点信息
        boolean result = videoContentCatService.save(videoContentCat);
        // 返回操作结果
        if (result) {
            return getSuccessResult();
        } else {
            // 保存失败
            return getFailResult();
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改视频内容分类信息", notes = "修改视频内容分类信息")
    @MethodLog(operModule = OperModule.VIDEOCLASSIFY, operType = OperType.UPDATE)
    public Map<String, Object> updateVideoContentCat(@Validated VideoContentCat videoContentCat) {
        boolean flag = videoContentCatService.updateById(videoContentCat);
        if (flag) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "copyrightOwnerId", value = "视频内容版权方ID", paramType = "query", dataType = "String")
    })
    @GetMapping("/getList")
    @RequiresAuthentication  //@RequiresPermissions("video:content:cat:list")
    @ApiOperation(value = "获取视频内容分类全部列表(无分页)", notes = "获取视频内容分类全部列表(无分页)")
    @MethodLog(operModule = OperModule.VIDEOCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> getVideoContentCatList(@RequestParam(value = "copyrightOwnerId", required = false) List<String> copyrightOwnerIdList) {
        final LambdaQueryWrapper<VideoContentCat> videoContentCatLambdaQueryWrapper = Wrappers.<VideoContentCat>lambdaQuery().orderByDesc(VideoContentCat::getCreateTime);
        if (copyrightOwnerIdList != null && !copyrightOwnerIdList.isEmpty()) {
            final LambdaQueryWrapper<CopyrightOwnerVideoContentCat> queryWrapper = Wrappers.<CopyrightOwnerVideoContentCat>lambdaQuery().in(CopyrightOwnerVideoContentCat::getCopyrightOwnerId, copyrightOwnerIdList);
            final List<CopyrightOwnerVideoContentCat> copyrightOwnerVideoContentCatList = this.copyrightOwnerVideoContentCatService.list(queryWrapper);
            if (!copyrightOwnerVideoContentCatList.isEmpty()) {
                final List<String> collect = copyrightOwnerVideoContentCatList.stream().map(CopyrightOwnerVideoContentCat::getVideoContentCatId).distinct().collect(Collectors.toList());
                videoContentCatLambdaQueryWrapper.in(VideoContentCat::getId, collect);
            } else {
                return getResult(Collections.emptyList());
            }
        }
        List<VideoContentCat> videoContentCatList = videoContentCatService.list(videoContentCatLambdaQueryWrapper);
        return getResult(videoContentCatList);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @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("video:content:cat:page")
    @ApiOperation(value = "获取视频内容分类分页列表", notes = "获取视频内容分类分页列表")
    @MethodLog(operModule = OperModule.VIDEOCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> getVideoContentCatPageList(GenericPageParam genericPageParam) {
        LambdaQueryWrapper<VideoContentCat> queryWrapper = new LambdaQueryWrapper<>();
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
            queryWrapper.like(VideoContentCat::getName, genericPageParam.getNameOrCode());
        }
        // 根据创建时间区间检索
        if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
            queryWrapper.ge(VideoContentCat::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(VideoContentCat::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
        }
        // 设置排序规则
        queryWrapper.orderByDesc(VideoContentCat::getCreateTime);
        // 设置查询内容
        queryWrapper.select(
                VideoContentCat::getId,
                VideoContentCat::getName,
                VideoContentCat::getRemarks,
                VideoContentCat::getCreateTime,
                VideoContentCat::getUpdateTime);
        Page<VideoContentCat> page = this.videoContentCatService.page(getPage(), queryWrapper);
        for (VideoContentCat videoContentCat : page.getRecords()) {

//            LambdaQueryWrapper<VideoContent> lambdaQueryWrapper = Wrappers.<VideoContent>lambdaQuery().eq(VideoContent::getVideoContentCatId, videoContentCat.getId()).select(VideoContent::getVideoContentCopyrightOwnerId);
//            final List<String> videoContentCopyrightOwnerIdList = this.videoContentService.listObjs(lambdaQueryWrapper, Object::toString);

            LambdaQueryWrapper<CopyrightOwnerVideoContentCat> lambdaQueryWrapper = Wrappers.<CopyrightOwnerVideoContentCat>lambdaQuery().eq(CopyrightOwnerVideoContentCat::getVideoContentCatId, videoContentCat.getId()).select(CopyrightOwnerVideoContentCat::getCopyrightOwnerId);
            final List<String> videoContentCopyrightOwnerIdList = this.copyrightOwnerVideoContentCatService.listObjs(lambdaQueryWrapper, Object::toString);

            if (!videoContentCopyrightOwnerIdList.isEmpty()) {
                List<CopyrightOwner> copyrightOwnerList = this.copyrightOwnerService.listByIds(new LinkedHashSet<>(videoContentCopyrightOwnerIdList));
                videoContentCat.setCopyrightOwnerName(copyrightOwnerList.stream().map(CopyrightOwner::getName).collect(Collectors.joining("、")));
            }
        }
        return getResult(page);
    }

    @ApiOperation(value = "获取视频内容分类详情", notes = "获取视频内容分类详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/get/{id}")
    @RequiresAuthentication  //@RequiresPermissions("video:content:cat:get:id")
    @MethodLog(operModule = OperModule.VIDEOCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> getById(@PathVariable("id") String id) {
        VideoContentCat videoContentCat = videoContentCatService.getById(id);
        return getResult(videoContentCat);
    }

    @DeleteMapping("/delete/{id}")
    @RequiresAuthentication  //@RequiresPermissions("exhibition:board:cat:delete")
    @ApiOperation(value = "根据ID删除视频内容分类", notes = "根据ID删除视频内容分类")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "标识ID", paramType = "path", dataType = "String")
    })
    @MethodLog(operModule = OperModule.VIDEOCLASSIFY, operType = OperType.DELETE)
    public Map<String, Object> deleteVideoContentCat(@PathVariable("id") String id) {
        // 该视频分类正在被使用时,不能被删除
        final LambdaUpdateWrapper<CopyrightOwnerVideoContentCat> updateWrapper1 = Wrappers.<CopyrightOwnerVideoContentCat>lambdaUpdate().eq(CopyrightOwnerVideoContentCat::getVideoContentCatId, id);
        List<CopyrightOwnerVideoContentCat> list = this.copyrightOwnerVideoContentCatService.list(updateWrapper1);
        if (CollectionUtil.isNotEmpty(list)) {
            return getFailResult("该视频分类正在被使用,不能删除");
        }
        // 删除视频分类信息
        this.videoContentCatService.removeById(id);
        // 删除版权方和视频分类对应信息
        this.copyrightOwnerVideoContentCatService.remove(updateWrapper1);

        final LambdaQueryWrapper<VideoContent> lambdaQueryWrapper = Wrappers.<VideoContent>lambdaQuery().eq(VideoContent::getVideoContentCatId, id).select(VideoContent::getId);
        final List<String> videoContentIdList = this.videoContentService.listObjs(lambdaQueryWrapper, Object::toString);
        if (videoContentIdList != null && !videoContentIdList.isEmpty()) {
            this.videoContentService.removeByIds(videoContentIdList);
            this.assetService.remove(Wrappers.<Asset>lambdaUpdate().in(Asset::getRefItemId, videoContentIdList));

            final LambdaQueryWrapper<ExhibitionBoard> queryWrapper = Wrappers.<ExhibitionBoard>lambdaQuery().in(ExhibitionBoard::getVideoContentId, videoContentIdList).select(ExhibitionBoard::getId);
            final List<String> exhibitionBoardIdList = this.exhibitionBoardService.listObjs(queryWrapper, Object::toString);
            if (exhibitionBoardIdList != null && !exhibitionBoardIdList.isEmpty()) {
                this.exhibitionBoardService.removeByIds(exhibitionBoardIdList);
                this.assetService.remove(Wrappers.<Asset>lambdaUpdate().in(Asset::getRefItemId, exhibitionBoardIdList));

                final LambdaQueryWrapper<LearningContentBoard> learningContentBoardLambdaQueryWrapper = Wrappers.<LearningContentBoard>lambdaQuery().in(LearningContentBoard::getExhibitionBoardCatId, exhibitionBoardIdList);
                final List<LearningContentBoard> learningContentBoardList = this.learningContentBoardService.list(learningContentBoardLambdaQueryWrapper);
                if (learningContentBoardList != null && !learningContentBoardList.isEmpty()) {
                    final Map<String, List<String>> collect = learningContentBoardList.stream().collect(Collectors.groupingBy(LearningContentBoard::getLearningContentId, Collectors.mapping(LearningContentBoard::getExhibitionBoardId, Collectors.toList())));
                    collect.forEach((k, v) -> {
                        if (v.size() == 1) {
                            this.learningContentService.removeById(k);
                            this.learningContentBoardService.remove(Wrappers.<LearningContentBoard>lambdaUpdate().eq(LearningContentBoard::getLearningContentId, k));
                            this.learningContentBoardCatService.remove(Wrappers.<LearningContentBoardCat>lambdaUpdate().eq(LearningContentBoardCat::getLearningContentId, k));
                            this.learningContentCopyrightOwnerService.remove(Wrappers.<LearningContentCopyrightOwner>lambdaUpdate().eq(LearningContentCopyrightOwner::getLearningContentId, k));
                        }
                    });

                    LambdaUpdateWrapper<LearningContentBoard> deleteWrapper1 = Wrappers.<LearningContentBoard>lambdaUpdate().in(LearningContentBoard::getExhibitionBoardId, exhibitionBoardIdList);
                    this.learningContentBoardService.remove(deleteWrapper1);
                }
            }
        }

//        final LambdaQueryWrapper<CopyrightOwnerVideoContentCat> eq = Wrappers.<CopyrightOwnerVideoContentCat>lambdaQuery().eq(CopyrightOwnerVideoContentCat::getVideoContentCatId, id);
//        final List<CopyrightOwnerVideoContentCat> list = this.copyrightOwnerVideoContentCatService.list(eq);
//        final List<String> collect = list.stream().map(CopyrightOwnerVideoContentCat::getCopyrightOwnerId).distinct().collect(Collectors.toList());
//
//        final LambdaUpdateWrapper<VideoContent> updateWrapper2 = Wrappers.<VideoContent>lambdaUpdate().in(VideoContent::getVideoContentCopyrightOwnerId, collect);
//        updateWrapper2.set(VideoContent::getDeleted, true);
//        this.videoContentService.update(updateWrapper2);
//
//        final LambdaUpdateWrapper<ExhibitionBoard> updateWrapper3 = Wrappers.<ExhibitionBoard>lambdaUpdate().in(ExhibitionBoard::getBoardCopyrightOwnerId, collect);
//        updateWrapper3.set(ExhibitionBoard::getDeleted, true);
//        this.exhibitionBoardService.update(updateWrapper3);
//
//        LambdaUpdateWrapper<CopyrightOwnerBoardCat> deleteWrapper = Wrappers.<CopyrightOwnerBoardCat>lambdaUpdate().in(CopyrightOwnerBoardCat::getCopyrightOwnerId, collect);
//        this.copyrightOwnerBoardCatService.remove(deleteWrapper);

        return getSuccessResult();
    }

}