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

import cn.wisenergy.chnmuseum.party.common.enums.CopyrightOwnerTypeEnum;
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.CopyrightOwner;
import cn.wisenergy.chnmuseum.party.model.CopyrightOwnerVideoContentCat;
import cn.wisenergy.chnmuseum.party.model.ExhibitionBoard;
import cn.wisenergy.chnmuseum.party.model.VideoContentCat;
import cn.wisenergy.chnmuseum.party.service.CopyrightOwnerService;
import cn.wisenergy.chnmuseum.party.service.CopyrightOwnerVideoContentCatService;
import cn.wisenergy.chnmuseum.party.service.ExhibitionBoardService;
import cn.wisenergy.chnmuseum.party.service.VideoContentCatService;
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.Set;
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 CopyrightOwnerVideoContentCatService copyrightOwnerVideoContentCatService;

    @Resource
    private ExhibitionBoardService exhibitionBoardService;

    @PostMapping("/save")
    @RequiresAuthentication  //@RequiresPermissions("copyright:owner:save")
    @ApiOperation(value = "添加版权方", notes = "添加版权方")
    public Map<String, Object> saveCopyrightOwner(@Validated(value = {Add.class}) CopyrightOwner copyrightOwner) {
        // 保存业务节点信息
        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);
        }

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

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("copyright:owner:update")
    @ApiOperation(value = "修改版权方信息", notes = "修改版权方信息")
    public Map<String, Object> updateCopyrightOwner(@Validated(value = {Update.class}) CopyrightOwner copyrightOwner) {
        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);
        }
        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 = "获取版权方全部列表(无分页)")
    public Map<String, Object> getCopyrightOwnerList(@RequestParam("copyrightOwnerType") CopyrightOwnerTypeEnum copyrightOwnerTypeEnum) {
        LambdaQueryWrapper<CopyrightOwner> lambdaQueryWrapper = Wrappers.<CopyrightOwner>lambdaQuery().eq(CopyrightOwner::getOwnerType, copyrightOwnerTypeEnum.name());
        lambdaQueryWrapper.eq(CopyrightOwner::getDeleted, false);
        lambdaQueryWrapper.le(CopyrightOwner::getExpireDateStart, TimeUtils.getDateTimeOfTimestamp(System.currentTimeMillis()))
                .ge(CopyrightOwner::getExpireDateEnd, TimeUtils.getDateTimeOfTimestamp(System.currentTimeMillis()));
        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 = "获取版权方分页列表")
    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::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(CopyrightOwner::getCreateTime, 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()) {
                    Set<String> idList = copyrightOwnerVideoContentCatList.stream().map(CopyrightOwnerVideoContentCat::getVideoContentCatId).collect(Collectors.toSet());
                    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())) {
                LambdaQueryWrapper<ExhibitionBoard> lambdaQueryWrapper = Wrappers.<ExhibitionBoard>lambdaQuery().eq(ExhibitionBoard::getBoardCopyrightOwnerId, copyrightOwner.getId());
                List<ExhibitionBoard> exhibitionBoardList = this.exhibitionBoardService.list(lambdaQueryWrapper);
                if (!exhibitionBoardList.isEmpty()) {
                    Set<String> videoContentCatIdList = exhibitionBoardList.stream().map(ExhibitionBoard::getVideoContentCatId).collect(Collectors.toSet());
                    List<VideoContentCat> videoContentCatList = this.videoContentCatService.listByIds(videoContentCatIdList);
                    String videoContentCatNames = videoContentCatList.stream().map(VideoContentCat::getName).collect(Collectors.joining("、"));
                    copyrightOwner.setVideoContentCatNames(videoContentCatNames);
                }
            }
        }
        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")
    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);
                }
            }
        }

        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")
    })
    public Map<String, Object> deleteCopyrightOwner(@PathVariable("id") String id) {
        this.copyrightOwnerService.removeById(id);
        return getSuccessResult();
    }

}