package com.gxwebsoft.love.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.entity.UserProfile;
import com.gxwebsoft.love.param.UserProfileParam;
import com.gxwebsoft.love.service.UserProfileService;
import com.gxwebsoft.love.socketio.cache.ClientCache;
import com.gxwebsoft.shop.entity.UserLook;
import com.gxwebsoft.shop.service.UserLookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 会员资料表控制器
 *
 * @author 科技小王子
 * @since 2023-06-09 21:42:26
 */
@Api(tags = "会员资料表管理")
@RestController
@RequestMapping("/api/love/user-profile")
public class UserProfileController extends BaseController {
    @Resource
    private UserProfileService userProfileService;
    @Resource
    private UserService userService;
    @Resource
    private UserLookService userLookService;

    @Resource
    private ClientCache clientCache;

    @PreAuthorize("hasAuthority('love:userProfile:list')")
    @ApiOperation("分页查询会员资料表")
    @GetMapping("/page")
    public ApiResult<PageResult<UserProfile>> page(UserProfileParam param) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
          param.setLoginUserId(loginUser.getUserId());
          param.setCityMate(loginUser.getCity());
          // 推荐异性
          if (loginUser.getSex() != null && param.getScene() != null && (param.getScene().equals("recommend") || param.getScene().equals("intraCity"))) {
            if (loginUser.getSex().equals("1")) {
              param.setSex("2");
            }else {
              param.setSex("1");
            }
          }
        }
        final PageResult<UserProfile> result = userProfileService.pageRel(param);
        return success(result);
    }

    @PreAuthorize("hasAuthority('love:userProfile:list')")
    @ApiOperation("查询全部会员资料表")
    @GetMapping()
    public ApiResult<List<UserProfile>> list(UserProfileParam param) {
        // 使用关联查询
        return success(userProfileService.listRel(param));
    }

    @PreAuthorize("hasAuthority('sys:auth:user')")
    @OperationLog
    @ApiOperation("根据会员id查询详细资料")
    @GetMapping("/{id}")
    public ApiResult<UserProfile> get(@PathVariable("id") Integer id) {
      final User loginUser = getLoginUser();
      final UserProfileParam userProfileParam = new UserProfileParam();
      userProfileParam.setUserId(loginUser.getUserId());
      userProfileParam.setShowFollow(true);
      final PageResult<UserProfile> result = userProfileService.pageRel(userProfileParam);
      if (result.getList().isEmpty()) {
        final UserProfile profile = new UserProfile();
        profile.setUserId(loginUser.getUserId());
        profile.setImages("[]");
        userProfileService.save(profile);
        profile.setUserInfo(loginUser);
        return fail("添加成功",profile);
      }
      final UserProfile userProfile = result.getList().get(0);
      userProfile.setUserInfo(getLoginUser());
      return success(userProfile);
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @OperationLog
    @ApiOperation("添加会员资料表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody UserProfile userProfile) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          userProfile.setUserId(loginUser.getUserId());
        }
        if (userProfileService.save(userProfile)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @OperationLog
    @ApiOperation("修改会员资料表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody UserProfile userProfile) {
        if (userProfileService.updateById(userProfile)) {
            userService.updateById(userProfile.getUserInfo());
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('love:userProfile:remove')")
    @OperationLog
    @ApiOperation("删除会员资料表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (userProfileService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('love:userProfile:save')")
    @OperationLog
    @ApiOperation("批量添加会员资料表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<UserProfile> list) {
        if (userProfileService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('love:userProfile:update')")
    @OperationLog
    @ApiOperation("批量修改会员资料表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<UserProfile> batchParam) {
        if (batchParam.update(userProfileService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('love:userProfile:remove')")
    @OperationLog
    @ApiOperation("批量删除会员资料表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (userProfileService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('love:userProfile:list')")
    @OperationLog
    @ApiOperation("根据会员id查询详细资料")
    @GetMapping("/detail/{id}")
    public ApiResult<UserProfile> detail(@PathVariable("id") Integer id) {
      final UserProfileParam param = new UserProfileParam();
      param.setShowFollow(true);
      param.setLoginUserId(getLoginUserId());
      param.setUserId(id);
      final PageResult<UserProfile> result = userProfileService.pageRel(param);
      if (result.getCount() > 0) {
        final UserProfile profile = result.getList().get(0);
        profile.setUserInfo(userService.getById(id));
        // 添加访客查看记录
        addUserLook(id);
        return success(profile);
      }
      return fail("用户不存在",null);
    }

    @Async
    public void addUserLook(Integer toUserId) {
      User loginUser = getLoginUser();
      if (loginUser != null && !loginUser.getUserId().equals(toUserId)) {
          boolean noLog = userLookService.count(new LambdaQueryWrapper<UserLook>().eq(UserLook::getUserId, loginUser.getUserId()).eq(UserLook::getToUserId, toUserId)) == 0;
          if (noLog) {
          final UserLook userLook = new UserLook();
          userLook.setUserId(getLoginUserId());
          userLook.setToUserId(toUserId);
          userLookService.save(userLook);
          clientCache.sendUserEvent(userLook.getToUserId() + "","look", 1);
        }
      }
    }

}
