package com.wecloud.im.controller;

import com.alibaba.fastjson.JSON;
import com.wecloud.im.entity.ImApplication;
import com.wecloud.im.entity.ImClient;
import com.wecloud.im.param.ClientInfoParam;
import com.wecloud.im.param.GetClientInfoParam;
import com.wecloud.im.param.GetOnlineStatusParam;
import com.wecloud.im.param.LogoutParam;
import com.wecloud.im.param.add.ClientDeviceUpdateParam;
import com.wecloud.im.param.add.ImClientHeadPortraitAdd;
import com.wecloud.im.param.add.ImClientHeadPortraitAndNicknameUpdate;
import com.wecloud.im.param.add.ImClientNicknameAdd;
import com.wecloud.im.service.ImApplicationService;
import com.wecloud.im.service.ImClientService;
import com.wecloud.im.vo.ClientInfoVo;
import com.wecloud.im.vo.GetInfoListVo;
import com.wecloud.im.vo.ImOnlineStatusVo;
import com.wecloud.im.vo.MyInfoVo;
import com.wecloud.im.ws.cache.UserStateCacheManager;
import io.geekidea.springbootplus.framework.common.api.ApiCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.controller.BaseController;
import io.geekidea.springbootplus.framework.core.validator.groups.Add;
import io.geekidea.springbootplus.framework.shiro.jwt.JwtToken;
import io.geekidea.springbootplus.framework.shiro.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RestController;

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

/**
 * 终端表 控制器
 *
 * @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 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 {
        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 {
        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 {
        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) throws Exception {
        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);
    }

}

