package com.gxwebsoft.shop.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.love.socketio.cache.ClientCache;
import com.gxwebsoft.shop.entity.UserLike;
import com.gxwebsoft.shop.param.UserLikeParam;
import com.gxwebsoft.shop.service.UserLikeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 点赞记录表控制器
 *
 * @author 科技小王子
 * @since 2023-07-06 17:51:04
 */
@Api(tags = "点赞记录表管理")
@RestController
@RequestMapping("/api/shop/user-like")
public class UserLikeController extends BaseController {
    @Resource
    private UserLikeService userLikeService;
    @Resource
    private UserService userService;

    @Resource
    private ClientCache clientCache;

    @PreAuthorize("hasAuthority('shop:userLike:list')")
    @OperationLog
    @ApiOperation("分页查询点赞记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<UserLike>> page(UserLikeParam param) {
        User loginUser = getLoginUser();
        if(loginUser != null){
            param.setLoginUserId(getLoginUserId());
        }

        PageResult<UserLike> result = userLikeService.pageRel(param);
        // 标记已读
        if(param.getToUserId() != null && param.getToUserId().equals(loginUser.getUserId())){
            Set<Integer> logIds = result.getList().stream().map(UserLike::getLogId).collect(Collectors.toSet());
            if(!CollectionUtils.isEmpty(logIds)){
                LambdaUpdateWrapper<UserLike> updateWrapper = new LambdaUpdateWrapper<UserLike>()
                        .in(UserLike::getLogId, logIds)
                        .set(UserLike::getStatus, 1);
                userLikeService.getBaseMapper().update(null, updateWrapper);
            }
        }
        // 使用关联查询
        return success(result);
    }

    @PreAuthorize("hasAuthority('shop:userLike:list')")
    @OperationLog
    @ApiOperation("查询全部点赞记录表")
    @GetMapping()
    public ApiResult<List<UserLike>> list(UserLikeParam param) {
        // 使用关联查询
        return success(userLikeService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:userLike:list')")
    @OperationLog
    @ApiOperation("根据id查询点赞记录表")
    @GetMapping("/{id}")
    public ApiResult<UserLike> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(userLikeService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:userLike:save')")
    @Transactional(rollbackFor = {Exception.class})
    @ApiOperation("添加点赞记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody UserLike userLike) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          userLike.setUserId(loginUser.getUserId());
          final UserLikeParam param = new UserLikeParam();
          param.setUserId(loginUser.getUserId());
          param.setToUserId(userLike.getToUserId());
          final List<UserLike> userLikes = userLikeService.listRel(param);
          System.out.println("userLikes = " + userLikes.size());

          // 点赞操作
          if (userLikes.size() == 0) {
            final UserLike add = new UserLike();
            add.setUserId(loginUser.getUserId());
            add.setToUserId(userLike.getToUserId());
            userLikeService.save(add);
            // 更新点赞数量
            final User modify = userService.getById(userLike.getToUserId());
            modify.setLikes(modify.getLikes() + 1);
            userService.updateById(modify);
            clientCache.sendUserEvent(userLike.getToUserId() + "","likeme", 1);
            return success("已喜欢", modify.getLikes());
          }

          // 取消点赞
          final UserLike like = userLikes.get(0);
          userLikeService.removeById(like.getLogId());
          // 更新点赞数量
          final User modify = userService.getById(userLike.getToUserId());
          modify.setLikes(modify.getLikes() - 1);
          userService.updateById(modify);
          clientCache.sendUserEvent(userLike.getToUserId() + "","likeme", -1);
          return success("取消喜欢",modify.getLikes());
        }
       return fail("操作失败");
    }

    @PreAuthorize("hasAuthority('shop:userLike:update')")
    @OperationLog
    @ApiOperation("修改点赞记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody UserLike userLike) {
        if (userLikeService.updateById(userLike)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:userLike:remove')")
    @OperationLog
    @ApiOperation("删除点赞记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (userLikeService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:userLike:save')")
    @OperationLog
    @ApiOperation("批量添加点赞记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<UserLike> list) {
        if (userLikeService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:userLike:update')")
    @OperationLog
    @ApiOperation("批量修改点赞记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<UserLike> batchParam) {
        if (batchParam.update(userLikeService, "log_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:userLike:remove')")
    @OperationLog
    @ApiOperation("批量删除点赞记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (userLikeService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
