package com.webchat.controller.client;

import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import com.webchat.common.constants.WebConstant;
import com.webchat.common.enums.ClickEvent;
import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.enums.RoleCodeEnum;
import com.webchat.common.helper.SessionHelper;
import com.webchat.common.util.AvatarUtil;
import com.webchat.config.annotation.SafeClick;
import com.webchat.config.annotation.ValidateLogin;
import com.webchat.config.annotation.ValidatePermission;
import com.webchat.domain.vo.request.CreateGroupRequestVO;
import com.webchat.domain.vo.request.CreatePublicAccountRequestVO;
import com.webchat.domain.vo.request.CreateRobotRequestVO;
import com.webchat.domain.vo.request.UpdateUserInfoRequestVO;
import com.webchat.domain.vo.request.UserLoginInfoRequestVO;
import com.webchat.domain.vo.request.UserRegistryInfoRequestVO;
import com.webchat.domain.vo.response.GroupResponseInfoVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.service.SlideVerificationService;
import com.webchat.service.UserService;
import com.webchat.service.ValidCodeService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 用户服务API
 */
@Api(tags = "【客户端】基础用户/账号服务接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ValidCodeService validCodeService;
    @Autowired
    private SlideVerificationService slideVerificationService;

    /**
     * 取当前登录用户信息
     * @return
     */
    @ValidateLogin
    @GetMapping("/getCurrentUserInfo")
    public APIResponseBean<UserBaseResponseInfoVO> getCurrentUserInfo() {
        return APIResponseBeanUtil.success(userService.getCurrentUserInfo());
    }

    @GetMapping("/getUserInfo")
    public APIResponseBean<UserBaseResponseInfoVO> getCurrentUserInfo(@RequestParam(value = "userId") String userId) {
        return APIResponseBeanUtil.success(userService.getUserInfoByUserId(userId));
    }


    /**
     * 用户资料信息标记
     *
     * @param updateUserInfoRequest
     * @return
     */
    @ValidateLogin
    @PostMapping("/update")
    public APIResponseBean<Boolean> updateInfo(@RequestBody UpdateUserInfoRequestVO updateUserInfoRequest ) {
        Assert.isTrue(StringUtils.isNotBlank(updateUserInfoRequest.getPhoto()) ||
                                StringUtils.isNotBlank(updateUserInfoRequest.getUserName()), "信息编辑失败：参数为空！");
        // 取当前登录用户信息
        String userId = SessionHelper.getCurrentUserId();
        updateUserInfoRequest.setUserId(userId);
        // 更新用户信息，数据库 + redis
        boolean updateResult = userService.updateUserInfo(updateUserInfoRequest);
        return APIResponseBeanUtil.success(updateResult);
    }

    /**
     * 用户登录
     * @param request
     * @return
     */
    @PostMapping("/login")
    public APIResponseBean login(@RequestBody UserLoginInfoRequestVO request) {
        Assert.isTrue(request != null, "登录参数为空！");
        String mobile = request.getMobile();
        String password = request.getPassword();
        String solidTokenId = request.getSolidTokenId();
        Assert.isTrue(StringUtils.isNotBlank(mobile), "手机号为空！");
        Assert.isTrue(StringUtils.isNotBlank(password), "密码为空！");
        Assert.isTrue(StringUtils.isNotBlank(solidTokenId), "滑块验证失败！");
        // 滑块验证
        slideVerificationService.validateTokenResult(solidTokenId);
        return APIResponseBeanUtil.success(userService.login(mobile, password));
    }

    /**
     * 微信小程序登录
     *
     * @param request
     * @return
     */
    @PostMapping("/wx/login")
    public APIResponseBean<String> wxLogin(@RequestBody UserLoginInfoRequestVO request) {
        Assert.isTrue(request != null, "登录参数为空！");
        String mobile = request.getMobile();
        String password = request.getPassword();
        Assert.isTrue(StringUtils.isNotBlank(mobile), "手机号为空！");
        Assert.isTrue(StringUtils.isNotBlank(password), "密码为空！");
        UserBaseResponseInfoVO userBaseResponseInfoVO = userService.login(mobile, password);
        return APIResponseBeanUtil.success(userService.getUserLoginCookie(userBaseResponseInfoVO.getUserId()));
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public APIResponseBean logout() {
        userService.logout();
        return APIResponseBeanUtil.success("OK");
    }

    /**
     * 用户注册
     * @param request
     * @return
     */
    @PostMapping("/registry")
    public APIResponseBean registry(@RequestBody UserRegistryInfoRequestVO request) {
        // 数字验证码核验
        validCodeService.validCode(request.getPicCheckCode());
        String photo = AvatarUtil.getRandomAvatar();
        userService.registry(photo, request.getUserName(), request.getMobile(), request.getPassword());
        return APIResponseBeanUtil.success("注册成功");
    }


    /**
     * 创建机器人
     *
     * @return
     */
    @PostMapping("/createRobot")
    public APIResponseBean createRobot(@RequestBody CreateRobotRequestVO requestPram) {

        String userId = SessionHelper.getCurrentUserId();
        requestPram.setCreateUserId(userId);
        userService.createRobot(requestPram);
        return APIResponseBeanUtil.success("机器人创建成功");
    }

    /**
     * 创建公众号
     * 默认只有管理员可以创建公众号
     *
     * @return
     */
    @ValidatePermission(role = RoleCodeEnum.ADMIN)
    @PostMapping("/createPublicAccount")
    public APIResponseBean createPublicAccount(@RequestBody CreatePublicAccountRequestVO requestPram) {
        String userId = SessionHelper.getCurrentUserId();
        requestPram.setCreateUserId(userId);
        userService.createPublicAccount(requestPram);
        return APIResponseBeanUtil.success("公众号创建成功");
    }

    /**
     * 创建群组
     *
     * @return
     */

    @ValidateLogin
    @SafeClick(event = ClickEvent.CREATE_GROUP, time = 2000, message = "群聊创建中")
    @PostMapping("/createChatGroup")
    public APIResponseBean createChatGroup(@RequestBody CreateGroupRequestVO requestPram) {

        String userId = SessionHelper.getCurrentUserId();
        requestPram.setCreateUserId(userId);
        userService.createChatGroup(requestPram);
        return APIResponseBeanUtil.success("群组创建成功");
    }

    /**
     * 查询群组下所有用户
     *
     * @param groupId
     * @return
     */
    @GetMapping("/listGroupUsers/{groupId}")
    public APIResponseBean<List<UserBaseResponseInfoVO>> listGroupUsers(@PathVariable String groupId) {
        String userId = SessionHelper.getCurrentUserId();
        return APIResponseBeanUtil.success(userService.getGroupUsersFromCache(groupId, userId));
    }

    /**
     * 查询当前登录用户加入的所有群聊
     *
     * @return
     */
    @GetMapping("/listGroups")
    public APIResponseBean<List<GroupResponseInfoVO>> listGroups() {
        String userId = SessionHelper.getCurrentUserId();
        return APIResponseBeanUtil.success(userService.listUserAttendGroupsFromCache(userId));
    }

    /**
     * 手机号检索
     * @param mobile
     * @return
     */
    @GetMapping("/search/{mobile}")
    public APIResponseBean<UserBaseResponseInfoVO> queryByMobile(@PathVariable String mobile) {

        return APIResponseBeanUtil.success(userService.queryByMobile(mobile));
    }
}
