package com.ai.da.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.context.UserContext;
import com.ai.da.common.response.PageBaseResponse;
import com.ai.da.common.response.Response;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.TDesignPythonOutfitMapper;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.Library;
import com.ai.da.mapper.primary.entity.TDesignPythonOutfit;
import com.ai.da.mapper.primary.entity.UserLikeGroup;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.*;
import com.ai.da.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Function;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;


@Api(tags = "History模块(saved Collection)")
@Slf4j
@RestController
@RequestMapping("/api/history")
public class SavedCollectionController {
    @Resource
    private UserLikeGroupService userLikeGroupService;
    @Resource
    private UserLikeService userLikeService;
    @Resource
    private AccountService accountService;
    @Resource
    private TDesignPythonOutfitMapper designPythonOutfitMapper;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private ClassificationService classificationService;

    @ApiOperation(value = "History用户分页分组列表")
    @PostMapping("/queryUserGroup")
    public Response<PageBaseResponse<UserLikeGroupVO>> queryUserGroup(@Valid @RequestBody QueryHistoryPageDTO query) {
        AuthPrincipalVo authPrincipalVo = UserContext.getUserHolder();
        // 分页数据
        QueryWrapper<UserLikeGroup> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("account_id", authPrincipalVo.getId());
        if (!StringUtils.isEmpty(query.getCollectionName())) {
            queryWrapper.like("name", query.getCollectionName());
        }
        if (Objects.nonNull(query.getStartDate())) {
            queryWrapper.ge("update_date", new Date(query.getStartDate()));
        }
        if (Objects.nonNull(query.getEndDate())) {
            queryWrapper.le("update_date", new Date(query.getEndDate()));
        }
        // 新增分类过滤
        if (CollectionUtil.isNotEmpty(query.getClassificationIdList())) {
            List<Long> historyIdList = new ArrayList<>();
            if (query.getIntersection() == 0) {
                for (Long classificationId : query.getClassificationIdList()) {
                    historyIdList.addAll(classificationService.getLibraryIdListByClassificationId(classificationId));
                }
                if (CollectionUtil.isNotEmpty(historyIdList)) {
                    queryWrapper.in("id", historyIdList);
                }else {
                    return Response.success(PageBaseResponse.success(new Page<>()));
                }
            }else {
                for (int i = 0; i < query.getClassificationIdList().size(); i++) {
                    List<Long> historyIdListByClassificationId = classificationService.getLibraryIdListByClassificationId(query.getClassificationIdList().get(i));
                    if (i == 0) {
                        historyIdList.addAll(historyIdListByClassificationId);
                    }else {
                        historyIdList.retainAll(historyIdListByClassificationId);
                    }
                    if (CollectionUtil.isEmpty(historyIdList)) {
                        return Response.success(PageBaseResponse.success(new Page<>()));
                    }
                }
                queryWrapper.in("id", historyIdList);
            }
        }
        queryWrapper.orderByDesc("update_date");
        IPage<UserLikeGroup> page = userLikeGroupService.getBaseMapper().selectPage(
                new Page<>(query.getPage(), query.getSize()), queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return Response.success(PageBaseResponse.success(new Page<>()));
        }
        List<Long> groupIds = page.getRecords().stream().map(UserLikeGroup::getId).collect(Collectors.toList());
        List<UserLikeVO> groupDetails = userLikeService.getGroupDetails(groupIds);
        if (CollectionUtils.isEmpty(groupDetails)) {
            throw new BusinessException("groupDetails.not.found");
        }
        Map<Long, List<UserLikeVO>> groupDetailMap = groupDetails.stream()
                .collect(Collectors.groupingBy(UserLikeVO::getUserLikeGroupId));

        Account account = accountService.getById(authPrincipalVo.getId());
        IPage<UserLikeGroupVO> convert = page.convert((Function<UserLikeGroup, UserLikeGroupVO>) group -> {
            if (group != null) {
                UserLikeGroupVO userLikeGroupVO = CopyUtil.copyObject(group, UserLikeGroupVO.class);
                userLikeGroupVO.setUpdateDate(group.getUpdateDate().getTime());
                userLikeGroupVO.setAuthor(account.getUserName());
                //count 和detail
                List<UserLikeVO> details = groupDetailMap.get(group.getId());
                for (UserLikeVO detail : details) {
                    TDesignPythonOutfit tDesignPythonOutfit = designPythonOutfitMapper.selectById(detail.getDesignOutfitId());
                    detail.setUrl(minioUtil.getPresignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
                }
                userLikeGroupVO.setGroupDetails(details);
                userLikeGroupVO.setSketchCount(CollectionUtils.isEmpty(details) ? 0 : details.size());
                return userLikeGroupVO;
            }
            return null;
        });
        return Response.success(PageBaseResponse.success(convert));
    }

    @ApiOperation(value = "History用户分组详情,目前弃用 ")
    @GetMapping("/getUserGroupDetail")
    public Response<List<UserLikeVO>> getUserGroupDetail(
            @ApiParam("用户分组id") @RequestParam("userGroupId") Long userGroupId) {
        return Response.success(userLikeService.getGroupDetail(userGroupId));
    }

    @ApiOperation(value = "History修改用户分组名")
    @PostMapping("/updateUserGroupName")
    public Response<HistoryUpdateVO> updateUserGroupName(@Valid @RequestBody HistoryUpdateDTO historyUpdateDTO) {
        return Response.success(userLikeGroupService.updateUserGroupName(historyUpdateDTO.getUserGroupId()
                , historyUpdateDTO.getUserGroupName(), historyUpdateDTO.getTimeZone()));
    }

    @ApiOperation(value = "History删除用户分组")
    @PostMapping("/deleteUserGroup")
    public Response<Boolean> deleteUserGroup(@Valid @RequestBody HistoryDeleteDTO deleteDTO) {
        userLikeGroupService.deleteUserGroup(deleteDTO.getUserGroupId());
        userLikeService.deleteByUserGroupId(deleteDTO.getUserGroupId());
        return Response.success(Boolean.TRUE);
    }

    @ApiOperation(value = "History choose")
    @GetMapping("/choose")
    public Response<UserLikeChooseVO> choose(
            @ApiParam("用户分组id") @RequestParam("userGroupId") Long userGroupId) {
        return Response.success(userLikeGroupService.choose(userGroupId));
    }

}
