package cn.wisenergy.chnmuseum.party.web.controller;

import cn.wisenergy.chnmuseum.party.common.enums.CopyrightOwnerTypeEnum;
import cn.wisenergy.chnmuseum.party.common.log.MethodLog;
import cn.wisenergy.chnmuseum.party.common.log.OperModule;
import cn.wisenergy.chnmuseum.party.common.log.OperType;
import cn.wisenergy.chnmuseum.party.common.util.TimeUtils;
import cn.wisenergy.chnmuseum.party.common.validator.groups.Add;
import cn.wisenergy.chnmuseum.party.common.validator.groups.Update;
import cn.wisenergy.chnmuseum.party.common.vo.GenericPageParam;
import cn.wisenergy.chnmuseum.party.model.*;
import cn.wisenergy.chnmuseum.party.service.*;
import cn.wisenergy.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.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.ArrayList;
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("/copyrightOwner")
@Api(tags = {"版权方接口"})
public class CopyrightOwnerController extends BaseController {

    @Resource
    private CopyrightOwnerService copyrightOwnerService;

    @Resource
    private VideoContentCatService videoContentCatService;

    @Resource
    private VideoContentService videoContentService;

    @Resource
    private CopyrightOwnerVideoContentCatService copyrightOwnerVideoContentCatService;

    @Resource
    private CopyrightOwnerBoardCatService copyrightOwnerBoardCatService;

    @Resource
    private ExhibitionBoardCatService exhibitionBoardCatService;

    @Resource
    private ExhibitionBoardService exhibitionBoardService;

    @Resource
    private LearningContentCopyrightOwnerService learningContentCopyrightOwnerService;

    @Resource
    private LearningContentService learningContentService;

    @PostMapping("/save")
    @RequiresAuthentication  //@RequiresPermissions("copyright:owner:save")
    @ApiOperation(value = "添加版权方", notes = "添加版权方")
    @MethodLog(operModule = OperModule.DISPLAYCOPYRIGHT, operType = OperType.ADD)
    public Map<String, Object> saveCopyrightOwner(@Validated(value = {Add.class}) CopyrightOwner copyrightOwner) {
        final LambdaQueryWrapper<CopyrightOwner> lambdaQueryWrapper = Wrappers.<CopyrightOwner>lambdaQuery().eq(CopyrightOwner::getName, copyrightOwner.getName().trim());
        lambdaQueryWrapper.eq(CopyrightOwner::getOwnerType, copyrightOwner.getOwnerType().trim());
        final int count = this.copyrightOwnerService.count(lambdaQueryWrapper);
        if (count > 0) {
            return getFailResult("400", "名称已存在,请修改名称");
        }
        boolean result = copyrightOwnerService.save(copyrightOwner);

        final List<String> videoContentCatIdList = copyrightOwner.getVideoContentCatIdList();
        if (videoContentCatIdList != null && !videoContentCatIdList.isEmpty()) {
            List<CopyrightOwnerVideoContentCat> copyrightOwnerVideoContentCatList = new ArrayList<>();
            for (String videoContentCatId : videoContentCatIdList) {
                copyrightOwnerVideoContentCatList.add(CopyrightOwnerVideoContentCat.builder()
                        .videoContentCatId(videoContentCatId)
                        .copyrightOwnerId(copyrightOwner.getId())
                        .build());
            }
            this.copyrightOwnerVideoContentCatService.saveBatch(copyrightOwnerVideoContentCatList);
        }

        final List<String> boardCatIdList = copyrightOwner.getBoardCatIdList();
        if (boardCatIdList != null && !boardCatIdList.isEmpty()) {
            List<CopyrightOwnerBoardCat> copyrightOwnerBoardCatList = new ArrayList<>();
            for (String boardCatId : boardCatIdList) {
                copyrightOwnerBoardCatList.add(CopyrightOwnerBoardCat.builder()
                        .boardCatId(boardCatId)
                        .copyrightOwnerId(copyrightOwner.getId())
                        .build());
            }
            this.copyrightOwnerBoardCatService.saveBatch(copyrightOwnerBoardCatList);
        }

        // 返回操作结果
        if (result) {
            return getSuccessResult();
        } else {
            // 保存失败
            return getFailResult();
        }
    }

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("copyright:owner:update")
    @ApiOperation(value = "修改版权方信息", notes = "修改版权方信息")
    @MethodLog(operModule = OperModule.DISPLAYCOPYRIGHT, operType = OperType.UPDATE)
    public Map<String, Object> updateCopyrightOwner(@Validated(value = {Update.class}) CopyrightOwner copyrightOwner) {
        final LambdaQueryWrapper<CopyrightOwner> lambdaQueryWrapper = Wrappers.<CopyrightOwner>lambdaQuery().eq(CopyrightOwner::getName, copyrightOwner.getName().trim());
        lambdaQueryWrapper.eq(CopyrightOwner::getOwnerType, copyrightOwner.getOwnerType().trim());
        lambdaQueryWrapper.ne(CopyrightOwner::getId, copyrightOwner.getId());
        final int count = this.copyrightOwnerService.count(lambdaQueryWrapper);
        if (count > 0) {
            return getFailResult("400", "名称已存在,请修改名称");
        }
        boolean flag = copyrightOwnerService.updateById(copyrightOwner);

        final List<String> videoContentCatIdList = copyrightOwner.getVideoContentCatIdList();
        if (videoContentCatIdList != null && !videoContentCatIdList.isEmpty()) {
            LambdaUpdateWrapper<CopyrightOwnerVideoContentCat> updateWrapper = Wrappers.<CopyrightOwnerVideoContentCat>lambdaUpdate().eq(CopyrightOwnerVideoContentCat::getCopyrightOwnerId, copyrightOwner.getId());
            this.copyrightOwnerVideoContentCatService.remove(updateWrapper);

            List<CopyrightOwnerVideoContentCat> copyrightOwnerVideoContentCatList = new ArrayList<>();
            for (String videoContentCatId : videoContentCatIdList) {
                copyrightOwnerVideoContentCatList.add(CopyrightOwnerVideoContentCat.builder()
                        .videoContentCatId(videoContentCatId)
                        .copyrightOwnerId(copyrightOwner.getId())
                        .build());
            }
            this.copyrightOwnerVideoContentCatService.saveBatch(copyrightOwnerVideoContentCatList);
        }

        final List<String> boardCatIdList = copyrightOwner.getBoardCatIdList();
        if (boardCatIdList != null && !boardCatIdList.isEmpty()) {
            LambdaUpdateWrapper<CopyrightOwnerBoardCat> updateWrapper = Wrappers.<CopyrightOwnerBoardCat>lambdaUpdate().eq(CopyrightOwnerBoardCat::getCopyrightOwnerId, copyrightOwner.getId());
            this.copyrightOwnerBoardCatService.remove(updateWrapper);

            List<CopyrightOwnerBoardCat> copyrightOwnerBoardCatList = new ArrayList<>();
            for (String boardCatId : boardCatIdList) {
                copyrightOwnerBoardCatList.add(CopyrightOwnerBoardCat.builder()
                        .boardCatId(boardCatId)
                        .copyrightOwnerId(copyrightOwner.getId())
                        .build());
            }
            this.copyrightOwnerBoardCatService.saveBatch(copyrightOwnerBoardCatList);
        }

        if (flag) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "copyrightOwnerType", value = "版权方类型", paramType = "query", dataType = "String", required = true)
    })
    @GetMapping("/getList")
    @RequiresAuthentication  //@RequiresPermissions("copyright:owner:list")
    @ApiOperation(value = "获取版权方全部列表(无分页)", notes = "获取版权方全部列表(无分页)")
    @MethodLog(operModule = OperModule.DISPLAYCOPYRIGHT, operType = OperType.SELECT)
    public Map<String, Object> getCopyrightOwnerList(@RequestParam("copyrightOwnerType") CopyrightOwnerTypeEnum copyrightOwnerTypeEnum) {
        LambdaQueryWrapper<CopyrightOwner> lambdaQueryWrapper = Wrappers.<CopyrightOwner>lambdaQuery().eq(CopyrightOwner::getOwnerType, copyrightOwnerTypeEnum.name());
        lambdaQueryWrapper.le(CopyrightOwner::getExpireDateStart, TimeUtils.getDateTimeOfTimestamp(System.currentTimeMillis())).ge(CopyrightOwner::getExpireDateEnd, TimeUtils.getDateTimeOfTimestamp(System.currentTimeMillis()));
        lambdaQueryWrapper.orderByDesc(CopyrightOwner::getCreateTime);
        List<CopyrightOwner> copyrightOwnerList = copyrightOwnerService.list(lambdaQueryWrapper);
        return getResult(copyrightOwnerList);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "ownerType", value = "版权方类型", paramType = "query", dataType = "String", required = true, allowableValues = "VIDEO_CONTENT, EXHIBITION_BOARD"),
            @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("copyright:owner:page")
    @ApiOperation(value = "获取版权方分页列表", notes = "获取版权方分页列表")
    @MethodLog(operModule = OperModule.VIDEOCOPYRIGHT, operType = OperType.SELECT)
    public Map<String, Object> getCopyrightOwnerPageList(GenericPageParam genericPageParam) {
        LambdaQueryWrapper<CopyrightOwner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CopyrightOwner::getOwnerType, genericPageParam.getOwnerType());
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
            queryWrapper.like(CopyrightOwner::getName, genericPageParam.getNameOrCode());
        }
        // 根据创建时间区间检索
        if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
            queryWrapper.ge(CopyrightOwner::getExpireDateStart, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(CopyrightOwner::getExpireDateEnd, genericPageParam.getEndDate().atTime(23, 59, 59));
        }
        // 设置排序规则
        queryWrapper.orderByDesc(CopyrightOwner::getCreateTime);
        // 设置查询内容
        queryWrapper.select(
                CopyrightOwner::getId,
                CopyrightOwner::getName,
                CopyrightOwner::getOwnerType,
                CopyrightOwner::getExpireDateStart,
                CopyrightOwner::getExpireDateEnd,
                CopyrightOwner::getRemarks,
                CopyrightOwner::getCreateTime,
                CopyrightOwner::getUpdateTime);
        Page<CopyrightOwner> page = this.copyrightOwnerService.page(getPage(), queryWrapper);
        for (CopyrightOwner copyrightOwner : page.getRecords()) {
            if (CopyrightOwnerTypeEnum.VIDEO_CONTENT.name().equals(genericPageParam.getOwnerType())) {
                List<CopyrightOwnerVideoContentCat> copyrightOwnerVideoContentCatList = this.copyrightOwnerVideoContentCatService.list(Wrappers.<CopyrightOwnerVideoContentCat>lambdaQuery().eq(CopyrightOwnerVideoContentCat::getCopyrightOwnerId, copyrightOwner.getId()));
                if (!copyrightOwnerVideoContentCatList.isEmpty()) {
                    final List<String> idList = copyrightOwnerVideoContentCatList.stream().map(CopyrightOwnerVideoContentCat::getVideoContentCatId).distinct().collect(Collectors.toList());
                    List<VideoContentCat> videoContentCatList = this.videoContentCatService.listByIds(idList);
                    String videoContentCatNames = videoContentCatList.stream().map(VideoContentCat::getName).collect(Collectors.joining("、"));
                    copyrightOwner.setVideoContentCatNames(videoContentCatNames);
                }
            } else if (CopyrightOwnerTypeEnum.EXHIBITION_BOARD.name().equals(genericPageParam.getOwnerType())) {
                final List<CopyrightOwnerBoardCat> copyrightOwnerBoardCatList = this.copyrightOwnerBoardCatService.list(Wrappers.<CopyrightOwnerBoardCat>lambdaQuery().eq(CopyrightOwnerBoardCat::getCopyrightOwnerId, copyrightOwner.getId()));
                if (!copyrightOwnerBoardCatList.isEmpty()) {
                    List<String> idList = copyrightOwnerBoardCatList.stream().map(CopyrightOwnerBoardCat::getBoardCatId).distinct().collect(Collectors.toList());
                    final List<ExhibitionBoardCat> exhibitionBoardCatList = this.exhibitionBoardCatService.listByIds(idList);
                    final String exhibitionBoardCatNames = exhibitionBoardCatList.stream().map(ExhibitionBoardCat::getName).collect(Collectors.joining("、"));
                    copyrightOwner.setBoardCatNames(exhibitionBoardCatNames);
                }
            }
        }
        return getResult(page);
    }

    @ApiOperation(value = "获取版权方详情", notes = "获取版权方详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/get/{id}")
    @RequiresAuthentication  //@RequiresPermissions("copyright:owner:get:id")
    @MethodLog(operModule = OperModule.DISPLAYCOPYRIGHT, operType = OperType.DETAILS)
    public Map<String, Object> getById(@PathVariable("id") String id) {
        CopyrightOwner copyrightOwner = copyrightOwnerService.getById(id);
        String ownerType = copyrightOwner.getOwnerType();
        if (CopyrightOwnerTypeEnum.VIDEO_CONTENT.name().equals(ownerType)) {
            LambdaQueryWrapper<CopyrightOwnerVideoContentCat> lambdaQueryWrapper = Wrappers.<CopyrightOwnerVideoContentCat>lambdaQuery().eq(CopyrightOwnerVideoContentCat::getCopyrightOwnerId, id);
            final List<CopyrightOwnerVideoContentCat> copyrightOwnerVideoContentCatList = this.copyrightOwnerVideoContentCatService.list(lambdaQueryWrapper);
            if (!copyrightOwnerVideoContentCatList.isEmpty()) {
                List<String> videoContentCatIdList = copyrightOwnerVideoContentCatList.stream().map(CopyrightOwnerVideoContentCat::getVideoContentCatId).distinct().collect(Collectors.toList());
                copyrightOwner.setVideoContentCatIdList(videoContentCatIdList);
                final List<VideoContentCat> videoContentCatList = this.videoContentCatService.listByIds(videoContentCatIdList);
                if (!videoContentCatList.isEmpty()) {
                    final List<String> videoContentCatNameList = videoContentCatList.stream().map(VideoContentCat::getName).collect(Collectors.toList());
                    copyrightOwner.setVideoContentCatNameList(videoContentCatNameList);
                }
            }
        }
        if (CopyrightOwnerTypeEnum.EXHIBITION_BOARD.name().equals(ownerType)) {
            final List<CopyrightOwnerBoardCat> copyrightOwnerBoardCatList = this.copyrightOwnerBoardCatService.list(Wrappers.<CopyrightOwnerBoardCat>lambdaQuery().eq(CopyrightOwnerBoardCat::getCopyrightOwnerId, id));
            if (!copyrightOwnerBoardCatList.isEmpty()) {
                final List<String> boardCatIdList = copyrightOwnerBoardCatList.stream().map(CopyrightOwnerBoardCat::getBoardCatId).distinct().collect(Collectors.toList());
                copyrightOwner.setBoardCatIdList(boardCatIdList);
                final List<ExhibitionBoardCat> exhibitionBoardCatList = this.exhibitionBoardCatService.listByIds(boardCatIdList);
                if (!exhibitionBoardCatList.isEmpty()) {
                    final List<String> exhibitionBoardCatNameList = exhibitionBoardCatList.stream().map(ExhibitionBoardCat::getName).collect(Collectors.toList());
                    copyrightOwner.setBoardCatNameList(exhibitionBoardCatNameList);
                }
            }
        }

        return getResult(copyrightOwner);
    }

    @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.DISPLAYCOPYRIGHT, operType = OperType.DELETE)
    public Map<String, Object> deleteCopyrightOwner(@PathVariable("id") String id) {
        this.copyrightOwnerService.removeById(id);

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

        final LambdaQueryWrapper<LearningContentCopyrightOwner> learningContentCopyrightOwnerLambdaQueryWrapper = Wrappers.<LearningContentCopyrightOwner>lambdaQuery().eq(LearningContentCopyrightOwner::getCopyrightOwnerId, id);
        final List<LearningContentCopyrightOwner> learningContentCopyrightOwnerList = this.learningContentCopyrightOwnerService.list(learningContentCopyrightOwnerLambdaQueryWrapper);
        if (learningContentCopyrightOwnerList != null && !learningContentCopyrightOwnerList.isEmpty()) {
            LambdaUpdateWrapper<LearningContentCopyrightOwner> deleteWrapper2 = Wrappers.<LearningContentCopyrightOwner>lambdaUpdate().eq(LearningContentCopyrightOwner::getCopyrightOwnerId, id);
            this.learningContentCopyrightOwnerService.remove(deleteWrapper2);

            if (learningContentCopyrightOwnerList.size() == 1) {
                this.learningContentService.removeById(learningContentCopyrightOwnerList.get(0).getLearningContentId());
            }
        }

        return getSuccessResult();
    }

}