package cn.chnmuseum.party.web.controller;

import cn.chnmuseum.party.common.enums.AuditStatusEnum;
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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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 javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <pre>
 * 展板分类 前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-19
 */
@Slf4j
@RestController
@RequestMapping("/exhibitionBoardCat")
@Api(tags = {"展板分类操作接口"})
public class ExhibitionBoardCatController extends BaseController {

    @Resource
    private ExhibitionBoardService exhibitionBoardService;
    @Resource
    private ExhibitionBoardCatService exhibitionBoardCatService;
    @Resource
    private CopyrightOwnerService copyrightOwnerService;
    @Resource
    private CopyrightOwnerBoardCatService copyrightOwnerBoardCatService;
    @Resource
    private LearningContentBoardCatService learningContentBoardCatService;
    @Resource
    private LearningContentService learningContentService;
    @Resource
    private LearningContentBoardService learningContentBoardService;
    @Resource
    private LearningContentCopyrightOwnerService learningContentCopyrightOwnerService;
    @Resource
    private AssetService assetService;

    @PostMapping("/save")
    @RequiresAuthentication  //@RequiresPermissions("exhibition:board:cat:save")
    @ApiOperation(value = "添加展板分类", notes = "添加展板分类")
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.ADD)
    public Map<String, Object> saveExhibitionBoardCat(@Validated(value = {Add.class}) ExhibitionBoardCat exhibitionBoardCat) {
        // 保存业务节点信息
        boolean result = exhibitionBoardCatService.save(exhibitionBoardCat);
        // 返回操作结果
        if (result) {
            return getSuccessResult();
        } else {
            // 保存失败
            return getFailResult();
        }
    }

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("exhibition:board:cat:update")
    @ApiOperation(value = "修改展板分类信息", notes = "修改展板分类信息")
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.UPDATE)
    public Map<String, Object> updateExhibitionBoardCat(@Validated(value = {Update.class}) ExhibitionBoardCat exhibitionBoardCat) {
        boolean flag = exhibitionBoardCatService.updateById(exhibitionBoardCat);
        if (flag) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @PutMapping("/updateAuditStatus/{id}")
    @RequiresAuthentication  //@RequiresPermissions("exhibition:board:cat:update:audit:status")
    @ApiOperation(value = "更新展板分类审核状态", notes = "更新展板分类审核状态")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "status", value = "状态", paramType = "query", dataType = "String")
    })
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> updateStatus(@NotNull(message = "展板分类ID不能为空") @PathVariable("id") String id, @RequestParam("auditStatus") AuditStatusEnum status) {
        UpdateWrapper<ExhibitionBoardCat> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.eq("audit_status", status.name());
        boolean flag = exhibitionBoardCatService.update(updateWrapper);
        if (flag) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "copyrightOwnerId", value = "展板内容版权方ID", paramType = "query", dataType = "String")
    })
    @PostMapping("/getList")
    @RequiresAuthentication  //@RequiresPermissions("exhibition:board:cat:list")
    @ApiOperation(value = "获取展板分类全部列表(无分页)", notes = "获取展板分类全部列表(无分页)")
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> getExhibitionBoardCatList(@RequestParam(value = "copyrightOwnerId", required = false) List<String> copyrightOwnerIdList) {
        final LambdaQueryWrapper<ExhibitionBoardCat> exhibitionBoardCatLambdaQueryWrapper = Wrappers.<ExhibitionBoardCat>lambdaQuery().orderByDesc(ExhibitionBoardCat::getCreateTime);
        if (copyrightOwnerIdList != null && !copyrightOwnerIdList.isEmpty()) {
            final LambdaQueryWrapper<CopyrightOwnerBoardCat> queryWrapper = Wrappers.<CopyrightOwnerBoardCat>lambdaQuery().in(CopyrightOwnerBoardCat::getCopyrightOwnerId, copyrightOwnerIdList);
            final List<CopyrightOwnerBoardCat> copyrightOwnerBoardCatList = this.copyrightOwnerBoardCatService.list(queryWrapper);
            if (!copyrightOwnerBoardCatList.isEmpty()) {
                final List<String> collect = copyrightOwnerBoardCatList.stream().map(CopyrightOwnerBoardCat::getBoardCatId).distinct().collect(Collectors.toList());
                exhibitionBoardCatLambdaQueryWrapper.in(ExhibitionBoardCat::getId, collect);
            } else {
                return getResult(Collections.emptyList());
            }
        }
        List<ExhibitionBoardCat> exhibitionBoardCatList = exhibitionBoardCatService.list(exhibitionBoardCatLambdaQueryWrapper);
        return getResult(exhibitionBoardCatList);
    }

    @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 = "copyrightOwner", 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("exhibition:board:cat:page")
    @ApiOperation(value = "获取展板分类分页列表", notes = "获取展板分类分页列表")
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> getExhibitionBoardCatPageList(GenericPageParam genericPageParam) {
        LambdaQueryWrapper<ExhibitionBoardCat> queryWrapper = new LambdaQueryWrapper<>();
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
            queryWrapper.like(ExhibitionBoardCat::getName, genericPageParam.getNameOrCode());
        }
        // 根据创建时间区间检索
        if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
            queryWrapper.ge(ExhibitionBoardCat::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(ExhibitionBoardCat::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
        }
        // 设置排序规则
        queryWrapper.orderByDesc(ExhibitionBoardCat::getCreateTime);
        // 设置查询内容
        queryWrapper.select(
                ExhibitionBoardCat::getId,
                ExhibitionBoardCat::getName,
                ExhibitionBoardCat::getRemarks,
                ExhibitionBoardCat::getCreateTime,
                ExhibitionBoardCat::getUpdateTime);
        Page<ExhibitionBoardCat> page = this.exhibitionBoardCatService.page(getPage(), queryWrapper);
        for (ExhibitionBoardCat exhibitionBoardCat : page.getRecords()) {
            LambdaQueryWrapper<ExhibitionBoard> lambdaQueryWrapper = Wrappers.<ExhibitionBoard>lambdaQuery().eq(ExhibitionBoard::getExhibitionBoardCatId, exhibitionBoardCat.getId());
            List<ExhibitionBoard> exhibitionBoardList = this.exhibitionBoardService.list(lambdaQueryWrapper);
            if (!exhibitionBoardList.isEmpty()) {
                Set<String> boardCopyrightOwnerIdList = exhibitionBoardList.stream().map(ExhibitionBoard::getBoardCopyrightOwnerId).collect(Collectors.toSet());
                List<CopyrightOwner> copyrightOwnerList = this.copyrightOwnerService.listByIds(boardCopyrightOwnerIdList);
                String copyrightOwnerNames = copyrightOwnerList.stream().map(CopyrightOwner::getName).collect(Collectors.joining("、"));
                exhibitionBoardCat.setCopyrightOwnerNames(copyrightOwnerNames);
            }
        }
        return getResult(page);
    }

    @ApiOperation(value = "获取展板分类详情", notes = "获取展板分类详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/get/{id}")
    @RequiresAuthentication  //@RequiresPermissions("exhibition:board:cat:get:id")
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.SELECT)
    public Map<String, Object> getById(@PathVariable("id") String id) {
        ExhibitionBoardCat exhibitionBoardCat = exhibitionBoardCatService.getById(id);
        return getResult(exhibitionBoardCat);
    }

    @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", required = true)
    })
    @MethodLog(operModule = OperModule.DISPLAYCLASSIFY, operType = OperType.DELETE)
    public Map<String, Object> deleteExhibitionBoardCat(@PathVariable("id") String id) {
        this.exhibitionBoardCatService.removeById(id);

        LambdaUpdateWrapper<CopyrightOwnerBoardCat> copyrightOwnerBoardCatLambdaUpdateWrapper = Wrappers.<CopyrightOwnerBoardCat>lambdaUpdate().eq(CopyrightOwnerBoardCat::getBoardCatId, id);
        this.copyrightOwnerBoardCatService.remove(copyrightOwnerBoardCatLambdaUpdateWrapper);

        final LambdaQueryWrapper<ExhibitionBoard> exhibitionBoardLambdaQueryWrapper = Wrappers.<ExhibitionBoard>lambdaQuery().eq(ExhibitionBoard::getExhibitionBoardCatId, id).select(ExhibitionBoard::getId);
        final List<String> exhibitionBoardIdList = this.exhibitionBoardService.listObjs(exhibitionBoardLambdaQueryWrapper, 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> learningContentBoardLambdaUpdateWrapper = Wrappers.<LearningContentBoard>lambdaUpdate().in(LearningContentBoard::getExhibitionBoardId, exhibitionBoardIdList);
                this.learningContentBoardService.remove(learningContentBoardLambdaUpdateWrapper);
            }
        }

        final LambdaQueryWrapper<LearningContentBoardCat> learningContentBoardCatLambdaQueryWrapper = Wrappers.<LearningContentBoardCat>lambdaQuery().eq(LearningContentBoardCat::getExhibitionBoardCatId, id);
        final List<LearningContentBoardCat> learningContentBoardCatList = this.learningContentBoardCatService.list(learningContentBoardCatLambdaQueryWrapper);
        if (learningContentBoardCatList != null && !learningContentBoardCatList.isEmpty()) {
            final Map<String, List<String>> collect = learningContentBoardCatList.stream().collect(Collectors.groupingBy(LearningContentBoardCat::getLearningContentId, Collectors.mapping(LearningContentBoardCat::getExhibitionBoardCatId, 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<LearningContentBoardCat> learningContentBoardCatLambdaUpdateWrapper = Wrappers.<LearningContentBoardCat>lambdaUpdate().eq(LearningContentBoardCat::getExhibitionBoardCatId, id);
            this.learningContentBoardCatService.remove(learningContentBoardCatLambdaUpdateWrapper);
        }

//        final LambdaUpdateWrapper<VideoContent> updateWrapper = Wrappers.<VideoContent>lambdaUpdate().eq(VideoContent::getVideoContentCopyrightOwnerId, id);
//        updateWrapper.set(VideoContent::getDeleted, true);
//        this.videoContentService.update(updateWrapper);
//
//        final LambdaUpdateWrapper<ExhibitionBoard> updateWrapper1 = Wrappers.<ExhibitionBoard>lambdaUpdate().eq(ExhibitionBoard::getBoardCopyrightOwnerId, id);
//        updateWrapper1.set(ExhibitionBoard::getDeleted, true);
//        this.exhibitionBoardService.update(updateWrapper1);
//
//        LambdaUpdateWrapper<CopyrightOwnerBoardCat> deleteWrapper = Wrappers.<CopyrightOwnerBoardCat>lambdaUpdate().eq(CopyrightOwnerBoardCat::getCopyrightOwnerId, id);
//        this.copyrightOwnerBoardCatService.remove(deleteWrapper);
//
//        LambdaUpdateWrapper<CopyrightOwnerVideoContentCat> deleteWrapper1 = Wrappers.<CopyrightOwnerVideoContentCat>lambdaUpdate().eq(CopyrightOwnerVideoContentCat::getCopyrightOwnerId, id);
//        this.copyrightOwnerVideoContentCatService.remove(deleteWrapper1);

        return getSuccessResult();
    }

}