package com.wecloud.im.biz.module.message.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.wecloud.can.core.base.controller.BaseController;
import com.wecloud.can.core.enums.ApiCode;
import com.wecloud.can.core.util.ApiResult;
import com.wecloud.can.core.validator.groups.Add;
import com.wecloud.can.security.jwt.JwtToken;
import com.wecloud.can.security.util.JwtUtil;
import com.wecloud.im.biz.module.message.controller.param.ClientInfoParam;
import com.wecloud.im.biz.module.message.controller.param.ClientRelationVo;
import com.wecloud.im.biz.module.message.controller.param.GetClientInfoParam;
import com.wecloud.im.biz.module.message.controller.param.GetClientRelationParam;
import com.wecloud.im.biz.module.message.controller.param.GetOnlineStatusParam;
import com.wecloud.im.biz.module.message.controller.param.LogoutParam;
import com.wecloud.im.biz.module.message.controller.param.ModifyUserAttributesParam;
import com.wecloud.im.biz.module.message.controller.param.RegisterClientParam;
import com.wecloud.im.biz.module.message.controller.param.add.ClientDeviceUpdateParam;
import com.wecloud.im.biz.module.message.controller.param.add.ImClientHeadPortraitAdd;
import com.wecloud.im.biz.module.message.controller.param.add.ImClientHeadPortraitAndNicknameUpdate;
import com.wecloud.im.biz.module.message.controller.param.add.ImClientNicknameAdd;
import com.wecloud.im.biz.module.message.controller.vo.ClientInfoVo;
import com.wecloud.im.biz.module.message.controller.vo.GetInfoListVo;
import com.wecloud.im.biz.module.message.controller.vo.ImOnlineStatusVo;
import com.wecloud.im.biz.module.message.controller.vo.MyInfoVo;
import com.wecloud.im.biz.module.message.controller.vo.RegisterClientResponse;
import com.wecloud.im.biz.module.message.entity.ImApplication;
import com.wecloud.im.biz.module.message.entity.ImClient;
import com.wecloud.im.biz.module.message.service.ImApplicationService;
import com.wecloud.im.biz.module.message.service.ImClientService;
import com.wecloud.im.server.cache.UserStateCacheManager;

/**
 * 终端表 控制器
 *
 * @author wei
 * @since 2021-04-27
 */
@Slf4j
@RestController
@RequestMapping("/imClient")
@Api(value = "终端", tags = {"终端"})
public class ImClientController extends BaseController {

    @Autowired
    private ImClientService imClientService;

    @Autowired
    private UserStateCacheManager userStateCacheManager;

    @Autowired
    private ImApplicationService imApplicationService;

    /**
     * 查询我的信息
     */
    @PostMapping("/myInfo")
    @ApiOperation(value = "查询我的信息")
    public ApiResult<MyInfoVo> myInfo() {
        MyInfoVo myInfo = imClientService.getMyInfo();
        return ApiResult.ok(myInfo);
    }


    @PostMapping("/infoList")
    @ApiOperation(value = "根据id获取Client的头像昵称")
    public ApiResult<List<GetInfoListVo>> getInfoList(@Validated(Add.class) @RequestBody GetClientInfoParam getClientInfoParam) throws Exception {
        return ApiResult.ok(imClientService.getInfoList(getClientInfoParam));
    }

    /**
     * 查询用户信息 用户可能是好友、陌生人、被拉黑名单的人
     */
    @PostMapping("/clientInfo")
    @ApiOperation(value = "查询用户信息 用户可能是好友、陌生人、被拉黑名单的人")
    public ApiResult<ClientInfoVo> getClientInfo(@RequestBody ClientInfoParam param) {
        if (param == null) {
            return ApiResult.fail(ApiCode.PARAMETER_EXCEPTION, null);
        }
        ClientInfoVo clientInfoVo = imClientService.getClientInfo(param);
        return ApiResult.ok(clientInfoVo);
    }


    /**
     * 添加或修改推送设备信息
     */
    @PostMapping("/addDeviceInfo")
    @ApiOperation(value = "添加或修改推送设备信息(每次请求都会覆盖之前的数据)")
    public ApiResult<Boolean> addDeviceInfo(@Validated(Add.class) @RequestBody ClientDeviceUpdateParam param) throws Exception {
        log.info("添加或修改推送设备信息入参 {}", JSON.toJSONString(param));
        boolean flag = imClientService.updateDeviceInfo(param);
        return ApiResult.result(flag);
    }


    @PostMapping("/updateHeadAndNickname")
    @ApiOperation(value = "添加或修改头像和昵称")
    public ApiResult<Boolean> updateHeadAndNickname(@Validated(Add.class) @RequestBody ImClientHeadPortraitAndNicknameUpdate imClientHeadPortraitAndNicknameUpdate) throws Exception {
        log.info("添加或修改头像和昵称入参 {}", JSON.toJSONString(imClientHeadPortraitAndNicknameUpdate));
        boolean flag = imClientService.updateHeadAndNickname(imClientHeadPortraitAndNicknameUpdate);
        return ApiResult.result(flag);
    }


    @PostMapping("/updateHeadPortrait")
    @ApiOperation(value = "添加或修改头像")
    public ApiResult<Boolean> updateHeadPortrait(@Validated(Add.class) @RequestBody ImClientHeadPortraitAdd imClientHeadPortraitAdd) throws Exception {
        log.info("添加或修改头像入参 {}", JSON.toJSONString(imClientHeadPortraitAdd));
        boolean flag = imClientService.updateHeadPortrait(imClientHeadPortraitAdd);
        return ApiResult.result(flag);
    }

    @PostMapping("/updateNickname")
    @ApiOperation(value = "添加或修改主昵称")
    public ApiResult<Boolean> updateNickname(@Validated(Add.class) @RequestBody ImClientNicknameAdd imClientNicknameAdd) throws Exception {
        log.info("添加或修改主昵称入参 {}", JSON.toJSONString(imClientNicknameAdd));
        boolean flag = imClientService.updateNickname(imClientNicknameAdd);
        return ApiResult.result(flag);
    }


    /**
     * 退出登陆
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登陆 清除推送token等")
    public ApiResult<Boolean> logout(@RequestBody @Validated LogoutParam param) {
        log.info("退出登陆入参 {}", JSON.toJSONString(param));
        boolean flag = imClientService.logout(param);
        return ApiResult.result(flag);
    }

    /**
     * 获取用户在线状态(批量)
     *
     * @return true:在线, false 不在线
     */
    @PostMapping("/onlineStatus")
    @ApiOperation(value = "获取用户在线状态(批量)")
    ApiResult<List<ImOnlineStatusVo>> getOnlineStatus(@RequestBody GetOnlineStatusParam getOnlineStatusParam) {
        // shiro线程中获取当前token
        JwtToken curentJwtToken = JwtUtil.getCurrentJwtToken();

        //  根据appKey查询appid
        ImApplication imApplication = imApplicationService.getCacheAppByAppKey(curentJwtToken.getAppKey());
        ArrayList<ImOnlineStatusVo> imOnlineStatusVos = new ArrayList<ImOnlineStatusVo>();
        for (String clientId : getOnlineStatusParam.getClientIds()) {

            ImOnlineStatusVo imOnlineStatusVo = new ImOnlineStatusVo();
            // todo 需要改成批量
            ImClient client = imClientService.getCacheImClient(imApplication.getId(), clientId);
            imOnlineStatusVo.setStatus(userStateCacheManager.isOnline(client.getId()));
            imOnlineStatusVo.setClientId(clientId);
            imOnlineStatusVos.add(imOnlineStatusVo);
        }
        return ApiResult.ok(imOnlineStatusVos);
    }

    @PostMapping("/registerClient")
    @ApiOperation(value = "注册客户端")
    ApiResult<RegisterClientResponse> registerClient(@RequestBody RegisterClientParam param) {
        Long clientId = imClientService.registerClient(param);
        RegisterClientResponse response = new RegisterClientResponse();
        response.setUserId(clientId);
        return ApiResult.ok(response);
    }

    /**
     * 查询两个客户端之间的关系
     * @Author luozh
     * @Date 2022年05月12日 06:52:00
     * @param
     * @Return 与朋友的关系 1 陌生人 2 好友 3 被我拉黑
     */
    @PostMapping("/getClientRelation")
    @ApiOperation(value = "查询两个客户端之间的关系")
    public ApiResult<ClientRelationVo> getClientRelation(@RequestBody GetClientRelationParam param) {
        return ApiResult.ok(imClientService.getClientRelation(param));
    }

    @PostMapping("/getUserAttributes")
    @ApiOperation(value = "查询两个客户端之间的关系")
    public ApiResult<Map<String, String>> getUserAttributes(@RequestParam("userId") String userId) {
        return ApiResult.ok(imClientService.getUserAttributes(userId));
    }

    @PostMapping("/modifyUserAttributes")
    @ApiOperation(value = "修改用户拓展字段")
    public ApiResult<Boolean> modifyUserAttributes(@Validated @RequestBody ModifyUserAttributesParam param) {
        return ApiResult.ok(imClientService.modifyUserAttributes(param.getUserId(), param.getAttributes()));
    }

}

