package com.yonge.cooleshow.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.admin.io.request.TenantAlbumCategoryVo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.TenantAlbumCategory;
import com.yonge.cooleshow.biz.dal.entity.TenantAlbumCategoryDetail;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.service.TenantAlbumCategoryDetailService;
import com.yonge.cooleshow.biz.dal.service.TenantAlbumCategoryService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumCategoryWrapper;
import com.yonge.toolset.base.exception.BizException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@Validated
@RestController
@RequestMapping("/tenantAlbumCategory")
@Api(tags = "机构专辑分类")
public class TenantAlbumCategoryController {

    @Autowired
    private TenantAlbumCategoryService tenantAlbumCategoryService;

    @Autowired
    private TenantAlbumCategoryDetailService tenantAlbumCategoryDetailService;

    @Resource
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "详情", notes = "机构专辑分类-根据详情ID查询单条, 传入id")
    @PreAuthorize("@pcs.hasPermissions('tenantAlbumCategory/detail', {'BACKEND'})")
    @GetMapping("/detail/{id}")
    public R<TenantAlbumCategoryWrapper.TenantAlbumCategory> detail(@PathVariable("id") Long id) {
        return R.from(tenantAlbumCategoryService.detail(id));
    }

    @ApiOperation(value = "查询分页", notes = "机构专辑分类- 传入 TenantAlbumCategoryVo.TenantAlbumCategoryQuery")
    @PreAuthorize("@pcs.hasPermissions('tenantAlbumCategory/page', {'BACKEND'})")
    @PostMapping("/page")
    public R<PageInfo<TenantAlbumCategoryVo.TenantAlbumCategory>> page(@RequestBody TenantAlbumCategoryWrapper.TenantAlbumCategoryQuery query) {

        // 查询数据
        IPage<TenantAlbumCategoryWrapper.TenantAlbumCategory> pages =
                tenantAlbumCategoryService.selectPage(QueryInfo.getPage(query), query);
        // 数据类型转换
        List<TenantAlbumCategoryVo.TenantAlbumCategory> records = JSON.parseArray(JSON.toJSONString(pages.getRecords()),
                TenantAlbumCategoryVo.TenantAlbumCategory.class);

        if (CollectionUtils.isNotEmpty(records)) {
            List<Long> updateUserIds =
                    records.stream().map(TenantAlbumCategoryVo.TenantAlbumCategory::getUpdateBy).distinct().collect(Collectors.toList());
            Map<Long, com.yonge.cooleshow.biz.dal.entity.SysUser> mapByIds = sysUserService.getMapByIds(updateUserIds);
            records.forEach(next -> {
                com.yonge.cooleshow.biz.dal.entity.SysUser sysUser = mapByIds.get(next.getUpdateBy());
                next.setUpdateUserName(sysUser == null ? "" : sysUser.getUsername());

                List<String> values = next.getValues().stream().map(TenantAlbumCategoryDetail::getValue)
                        .filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                next.setTenantAlbumCategoryContent(String.join(",",values));
            });
        }

        return R.from(QueryInfo.pageInfo(pages, records));
    }

    @ApiOperation(value = "新增", notes = "机构专辑分类- 传入 TenantAlbumCategoryVo.TenantAlbumCategory")
    @PreAuthorize("@pcs.hasPermissions('tenantAlbumCategory/save', {'BACKEND'})")
    @PostMapping("/save")
    public R<JSONObject> add(@Validated @RequestBody TenantAlbumCategoryVo.TenantAlbumCategory tenantAlbumCategoryVo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        // 新增数据
        TenantAlbumCategoryWrapper.TenantAlbumCategory albumCategory =
                JSON.parseObject(tenantAlbumCategoryVo.jsonString(),
                        TenantAlbumCategoryWrapper.TenantAlbumCategory.class);
        albumCategory.setCreateBy(sysUser.getId());
        albumCategory.setUpdateBy(sysUser.getId());
        tenantAlbumCategoryService.add(albumCategory);

        return R.defaultR();
    }

    @ApiOperation(value = "修改", notes = "机构专辑分类- 传入 TenantAlbumCategoryVo.TenantAlbumCategory")
    @PreAuthorize("@pcs.hasPermissions('tenantAlbumCategory/update', {'BACKEND'})")
    @PostMapping("/update")
    public R<JSONObject> update(@Validated @RequestBody TenantAlbumCategoryVo.TenantAlbumCategory tenantAlbumCategoryVo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        // 更新数据
        TenantAlbumCategoryWrapper.TenantAlbumCategory albumCategory =
                JSON.parseObject(tenantAlbumCategoryVo.jsonString(),
                        TenantAlbumCategoryWrapper.TenantAlbumCategory.class);
        albumCategory.setUpdateBy(sysUser.getId());
        tenantAlbumCategoryService.update(albumCategory);

        return R.defaultR();
    }

    @ApiOperation(value = "删除", notes = "机构专辑分类- 传入id")
    @PreAuthorize("@pcs.hasPermissions('tenantAlbumCategory/remove', {'BACKEND'})")
    @PostMapping("/remove")
    public R<Boolean> remove(@RequestParam Long id) {

        return R.from(tenantAlbumCategoryService.delete(id));
    }

    @ApiOperation(value = "获取专辑分类值列表")
    @PreAuthorize("@pcs.hasPermissions('tenantAlbumCategory/queryCategoryValue', {'BACKEND'})")
    @GetMapping("/queryCategoryValue")
    public R<List<TenantAlbumCategoryDetail>> queryCategoryValue(@RequestParam("id") Long id) {
        TenantAlbumCategory albumCategory = tenantAlbumCategoryService.getById(id);
        if (albumCategory == null) {
            throw new BizException("专辑分类不存在");
        }
        List<TenantAlbumCategoryDetail> detailList = tenantAlbumCategoryDetailService.lambdaQuery()
                .eq(TenantAlbumCategoryDetail::getTenantAlbumCategoryId, id)
                .list();
        return R.from(detailList);
    }
}