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

import cn.wisenergy.chnmuseum.party.common.enums.CopyrightOwnerTypeEnum;
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.RequiresPermissions;
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 AssetService assetService;

    @Resource
    private AssetTypeService assetTypeService;

    @Resource
    private CopyrightOwnerAssetTypeService copyrightOwnerAssetTypeService;

    @Resource
    private ExhibitionBoardService exhibitionBoardService;

    @PostMapping("/save")
    @RequiresPermissions("copyright:owner:save")
    @ApiOperation(value = "添加版权方", notes = "添加版权方")
    public Map<String, Object> saveCopyrightOwner(@Validated(value = {Add.class}) CopyrightOwner copyrightOwner, @RequestParam("copyrightOwnerType") CopyrightOwnerTypeEnum copyrightOwnerTypeEnum) {
        copyrightOwner.setOwnerType(copyrightOwnerTypeEnum.name());
        // 保存业务节点信息
        boolean result = copyrightOwnerService.save(copyrightOwner);

        List<String> assetTypeIdList = copyrightOwner.getAssetTypeIdList();
        if (assetTypeIdList != null && !assetTypeIdList.isEmpty()) {
            List<CopyrightOwnerAssetType> copyrightOwnerAssetTypeList = new ArrayList<>();
            for (String assetTypeId : assetTypeIdList) {
                copyrightOwnerAssetTypeList.add(CopyrightOwnerAssetType.builder()
                        .assetTypeId(assetTypeId)
                        .copyrightOwnerId(copyrightOwner.getId())
                        .build());
            }
            this.copyrightOwnerAssetTypeService.saveBatch(copyrightOwnerAssetTypeList);
        }

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

    @PutMapping("/update")
    @RequiresPermissions("copyright:owner:update")
    @ApiOperation(value = "修改版权方信息", notes = "修改版权方信息")
    public Map<String, Object> updateCopyrightOwner(@Validated(value = {Update.class}) CopyrightOwner copyrightOwner, @RequestParam("copyrightOwnerType") CopyrightOwnerTypeEnum copyrightOwnerTypeEnum) {
        copyrightOwner.setOwnerType(copyrightOwnerTypeEnum.name());
        boolean flag = copyrightOwnerService.updateById(copyrightOwner);

        List<String> assetTypeIdList = copyrightOwner.getAssetTypeIdList();
        if (assetTypeIdList != null && !assetTypeIdList.isEmpty()) {
            LambdaUpdateWrapper<CopyrightOwnerAssetType> updateWrapper = Wrappers.<CopyrightOwnerAssetType>lambdaUpdate().eq(CopyrightOwnerAssetType::getCopyrightOwnerId, copyrightOwner.getId());
            this.copyrightOwnerAssetTypeService.remove(updateWrapper);

            List<CopyrightOwnerAssetType> copyrightOwnerAssetTypeList = new ArrayList<>();
            for (String assetTypeId : assetTypeIdList) {
                copyrightOwnerAssetTypeList.add(CopyrightOwnerAssetType.builder()
                        .assetTypeId(assetTypeId)
                        .copyrightOwnerId(copyrightOwner.getId())
                        .build());
            }
            this.copyrightOwnerAssetTypeService.saveBatch(copyrightOwnerAssetTypeList);
        }
        if (flag) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @DeleteMapping("/delete/{id}")
    @RequiresPermissions("copyright:owner: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) {
        LambdaUpdateWrapper<Asset> updateWrapper = Wrappers.<Asset>lambdaUpdate().eq(Asset::getAssetCopyrightOwnerId, id);
        updateWrapper.set(Asset::getAssetCopyrightOwnerId, null);
        boolean result1 = this.assetService.update(updateWrapper);

        LambdaUpdateWrapper<ExhibitionBoard> updateWrapper1 = Wrappers.<ExhibitionBoard>lambdaUpdate().eq(ExhibitionBoard::getCopyrightOwnerId, id);
        updateWrapper1.set(ExhibitionBoard::getCopyrightOwnerId, null);
        boolean result2 = this.exhibitionBoardService.update(updateWrapper1);

        LambdaUpdateWrapper<CopyrightOwnerAssetType> updateWrapper2 = Wrappers.<CopyrightOwnerAssetType>lambdaUpdate().eq(CopyrightOwnerAssetType::getCopyrightOwnerId, id);
        boolean result3 = this.copyrightOwnerAssetTypeService.remove(updateWrapper2);

        boolean result = this.copyrightOwnerService.removeById(id);
        if (result && result1 && result2 && result3) {
            return getSuccessResult();
        }
        return getFailResult();
    }

    @GetMapping("/getList")
    @RequiresPermissions("copyright:owner:list")
    @ApiOperation(value = "获取版权方全部列表(无分页)", notes = "获取版权方全部列表(无分页)")
    public Map<String, Object> getCopyrightOwnerList() {
        List<CopyrightOwner> copyrightOwnerList = copyrightOwnerService.list(Wrappers.<CopyrightOwner>lambdaQuery());
        return getResult(copyrightOwnerList);
    }

    @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")
    @RequiresPermissions("copyright:owner:page")
    @ApiOperation(value = "获取版权方分页列表", notes = "获取版权方分页列表")
    public Map<String, Object> getCopyrightOwnerPageList(GenericPageParam genericPageParam) {
        LambdaQueryWrapper<CopyrightOwner> queryWrapper = new LambdaQueryWrapper<>();
        // 对名称或编码模糊查询
        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::getCreateTime,
                CopyrightOwner::getUpdateTime);
        Page<CopyrightOwner> page = this.copyrightOwnerService.page(getPage(), queryWrapper);
        for (CopyrightOwner copyrightOwner : page.getRecords()) {
            final List<CopyrightOwnerAssetType> CopyrightOwnerAssetTypeList = this.copyrightOwnerAssetTypeService.list(Wrappers.<CopyrightOwnerAssetType>lambdaQuery().eq(CopyrightOwnerAssetType::getCopyrightOwnerId, copyrightOwner.getId()));
            final List<String> idList = CopyrightOwnerAssetTypeList.stream().map(CopyrightOwnerAssetType::getAssetTypeId).collect(Collectors.toList());
            List<AssetType> assetTypeList = this.assetTypeService.listByIds(idList);
            final String assetTypeNameList = assetTypeList.stream().map(AssetType::getName).collect(Collectors.joining("、"));
            copyrightOwner.setAssetTypeNames(assetTypeNameList);
        }
        return getResult(page);
    }

    @ApiOperation(value = "获取版权方详情", notes = "获取版权方详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识ID", dataType = "String", paramType = "path")
    })
    @GetMapping("/get/{id}")
    @RequiresPermissions("copyright:owner:get:id")
    public Map<String, Object> getById(@PathVariable("id") String id) {
        CopyrightOwner copyrightOwner = copyrightOwnerService.getById(id);
        return getResult(copyrightOwner);
    }

}