/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.yami.shop.bean.app.dto.ProductDto;
import com.yami.shop.bean.app.dto.UserCollectionDto;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.UserCollection;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.BasketService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.UserCollectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/p/user/collection")
@Api(tags = "商品收藏接口")
@AllArgsConstructor
public class UserCollectionController {

    private final UserCollectionService userCollectionService;

    private final BasketService basketService;

    private final ProductService productService;

    @GetMapping("/page")
    @ApiOperation(value = "分页返回收藏数据", notes = "根据用户id获取")
    public ResponseEntity<IPage<UserCollectionDto>> getUserCollectionDtoPageByUserId(PageParam page,String prodName,Integer prodType) {
        return ResponseEntity.ok(userCollectionService.getUserCollectionDtoPageByUserId(page, SecurityUtils.getUser().getUserId(),prodName,prodType));
    }

    @GetMapping("isCollection")
    @ApiOperation(value = "根据商品id获取该商品是否在收藏夹中", notes = "传入收藏商品id")
    public ResponseEntity<Boolean> isCollection(Long prodId) {
        if (productService.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getProdId, prodId)) < 1) {
            throw new GlobalException("该商品不存在");
        }
        return ResponseEntity.ok(userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
                .eq(UserCollection::getProdId, prodId)
                .eq(UserCollection::getUserId, SecurityUtils.getUser().getUserId())) > 0);
    }

    @PostMapping("/addOrCancel")
    @ApiOperation(value = "添加/取消收藏", notes = "传入收藏商品id,如果商品未收藏则收藏商品，已收藏则取消收藏")
    @ApiImplicitParam(name = "prodId", value = "商品id", required = true, dataType = "Long")
    public ResponseEntity<Boolean> addOrCancel(@RequestBody Long prodId) {
        if (Objects.isNull(productService.getProductByProdId(prodId))) {
            throw new GlobalException("该商品不存在");
        }
        Boolean isAdd = false;
        String userId = SecurityUtils.getUser().getUserId();
        //pc端收藏商品时，清除购物车缓存
        basketService.removeShopCartItemsCacheByUserId(userId);
        if (userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
                .eq(UserCollection::getProdId, prodId)
                .eq(UserCollection::getUserId, userId)) > 0) {
            userCollectionService.remove(new LambdaQueryWrapper<UserCollection>()
                    .eq(UserCollection::getProdId, prodId)
                    .eq(UserCollection::getUserId, userId));
        } else {
            UserCollection userCollection = new UserCollection();
            userCollection.setCreateTime(new Date());
            userCollection.setUserId(userId);
            userCollection.setProdId(prodId);
            userCollectionService.save(userCollection);
            isAdd = true;
        }
        return ResponseEntity.ok(isAdd);
    }

    @PostMapping("/batachCancel")
    @ApiOperation(value = "批量取消收藏", notes = "传入收藏商品id")
    @ApiImplicitParam(name = "prodId", value = "商品id", required = true, dataType = "Long")
    public ResponseEntity<Boolean> batachCancel(@RequestBody List<Long> prodIds) {
        String userId = SecurityUtils.getUser().getUserId();
        if (CollectionUtils.isEmpty(prodIds)){
            return ResponseEntity.ok(false);
        }
        boolean remove = false;
        for (Long prodId : prodIds) {
          if (Objects.isNull(productService.getProductByProdId(prodId))) {
              continue;
          }
          int count = userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
                  .eq(UserCollection::getProdId, prodId)
                  .eq(UserCollection::getUserId, userId));
          if (count <= 0) {
              continue;
          }
          remove = userCollectionService.remove(new LambdaQueryWrapper<UserCollection>()
                    .eq(UserCollection::getProdId, prodId)
                    .eq(UserCollection::getUserId, userId));
        }
        return ResponseEntity.ok(remove);
    }


    /**
     * 查询用户收藏商品数量
     */
    @GetMapping("count")
    @ApiOperation(value = "查询用户收藏商品数量", notes = "查询用户收藏商品数量")
    public int findUserCollectionCount() {
        String userId = SecurityUtils.getUser().getUserId();
        return userCollectionService.count(new LambdaQueryWrapper<UserCollection>().eq(UserCollection::getUserId, userId));
    }

    @GetMapping("/prods")
    @ApiOperation(value = "获取用户收藏商品列表", notes = "获取用户收藏商品列表")
    public ResponseEntity<IPage<ProductDto>> collectionProds(PageParam page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<ProductDto> productDtoIPage = productService.collectionProds(page, userId);
        return ResponseEntity.ok(productDtoIPage);
    }

    @PostMapping("/orderProdCollectionAll")
    @ApiOperation(value = "订单商品收藏", notes = "传入商品id拼接字符串")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "prodIds", value = "商品id", required = true, dataType = "Long"),
    })
    public ResponseEntity<Boolean> orderProdCollectionAll(@RequestBody String prodIds) {
        String userId = SecurityUtils.getUser().getUserId();
        List<String> prodIdList = Arrays.asList(prodIds.split(","));
        //去重
        HashSet hashSet = new HashSet(prodIdList);
        prodIdList = Lists.newArrayList();
        prodIdList.addAll(hashSet);
        userCollectionService.orderProdCollectionAll(prodIdList,userId);
        return ResponseEntity.ok().build();
    }

}
