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.love.socketio.cache.ClientCache;
import com.gxwebsoft.shop.entity.UserLook;
import com.gxwebsoft.shop.param.UserLookParam;
import com.gxwebsoft.shop.service.UserLookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
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-13 23:10:38
 */
@Api(tags = "访客记录表管理")
@RestController
@RequestMapping("/api/shop/user-look")
public class UserLookController extends BaseController {
    @Resource
    private UserLookService userLookService;

    @Resource
    private ClientCache clientCache;

    @PreAuthorize("hasAuthority('shop:userLook:list')")
    @OperationLog
    @ApiOperation("分页查询访客记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<UserLook>> page(UserLookParam param) {
        User loginUser = getLoginUser();
        if(loginUser != null){
            param.setLoginUserId(getLoginUserId());
        }
        PageResult<UserLook> result = userLookService.pageRel(param);
        // 标记已读
        if(param.getToUserId() != null && param.getToUserId().equals(loginUser.getUserId())){
            Set<Integer> logIds = result.getList().stream().map(UserLook::getLogId).collect(Collectors.toSet());
            if(!CollectionUtils.isEmpty(logIds)){
                LambdaUpdateWrapper<UserLook> updateWrapper = new LambdaUpdateWrapper<UserLook>()
                        .in(UserLook::getLogId, logIds)
                        .set(UserLook::getStatus, 1);
                userLookService.getBaseMapper().update(null, updateWrapper);

            }

        }
        // 使用关联查询
        return success(result);
    }

    @PreAuthorize("hasAuthority('shop:userLook:list')")
    @OperationLog
    @ApiOperation("查询全部访客记录表")
    @GetMapping()
    public ApiResult<List<UserLook>> list(UserLookParam param) {
        // 使用关联查询
        return success(userLookService.listRel(param));
    }

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

    @PreAuthorize("hasAuthority('shop:userLook:list')")
    @OperationLog
    @ApiOperation("添加访客记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody UserLook userLook) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          userLook.setUserId(loginUser.getUserId());
        }
        if(loginUser.getUserId().equals(userLook.getToUserId())){
            return success("无事发生");
        }
        if (userLookService.save(userLook)) {
            clientCache.sendUserEvent(userLook.getToUserId() + "","look", 1);
            return success("添加成功");

        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:userLook:list')")
    @OperationLog
    @ApiOperation("修改访客记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody UserLook userLook) {
        if (userLookService.updateById(userLook)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

    @PreAuthorize("hasAuthority('shop:userLook:list')")
    @OperationLog
    @ApiOperation("批量添加访客记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<UserLook> list) {
        if (userLookService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

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

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

}
