package com.wecloud.im.controller;

import com.wecloud.im.friend.entity.ImFriend;
import com.wecloud.im.friend.service.ImFriendService;
import com.wecloud.utils.SnowflakeUtil;
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 java.util.ArrayList;
import java.util.Date;
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.im.entity.ImApplication;
import com.wecloud.im.entity.ImClient;
import com.wecloud.im.param.ClientInfoParam;
import com.wecloud.im.param.ClientRelationVo;
import com.wecloud.im.param.GetClientInfoParam;
import com.wecloud.im.param.GetClientRelationParam;
import com.wecloud.im.param.GetOnlineStatusParam;
import com.wecloud.im.param.LogoutParam;
import com.wecloud.im.param.ModifyUserAttributesParam;
import com.wecloud.im.param.RegisterClientParam;
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.vo.RegisterClientResponse;
import com.wecloud.im.ws.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;

    @Autowired
    private ImFriendService imFriendService;

    /**
     * 查询我的信息
     */
    @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(@Validated @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()));
    }

    @PostMapping("/testUser")
    @ApiOperation(value = "testUser")
    public ApiResult<Boolean> testUser() {
        Long begin = 300000000000000003L;
        Long end =   300000000000000203L;

        int a = 3;
        for (long i= begin; i <= end; i++) {
            try {
                ImClient imClient = new ImClient();
                imClient.setId(i);
                imClient.setCreateTime(new Date());
                imClient.setLastOfflineTime(new Date());
                imClient.setUpdateTime(new Date());
                imClient.setFkAppid(1L);
                imClient.setAttributes(null);
                imClient.setClientId(i + "");
                imClient.setHeadPortrait(null);
                imClient.setNickname("阿萨姆" + a);
                a++;
                imClientService.save(imClient);
            } catch (Exception e) {
                log.info("e", e);
            }

            try {

                ImFriend imFriend1 = new ImFriend();
                imFriend1.setId(SnowflakeUtil.getId());
                imFriend1.setClientId(i + "");
                imFriend1.setClientIdFriend("1588082807551512576");
                imFriend1.setClientIdClaimer("1588082807551512576");
                imFriend1.setFriendName("");
                imFriend1.setRejectRemark("");
                imFriend1.setRequestRemark("");
                imFriend1.setState(2);
                imFriend1.setCreateTime(new Date());
                imFriend1.setUpdateTime(new Date());
                imFriendService.save(imFriend1);
            } catch (Exception e) {
                log.info("e", e);
            }

            try {
                ImFriend imFriend2 = new ImFriend();
                imFriend2.setId(SnowflakeUtil.getId());
                imFriend2.setClientId("1588082807551512576");
                imFriend2.setClientIdFriend(i + "");
                imFriend2.setClientIdClaimer("1588082807551512576");
                imFriend2.setFriendName("");
                imFriend2.setRejectRemark("");
                imFriend2.setRequestRemark("");
                imFriend2.setState(2);
                imFriend2.setCreateTime(new Date());
                imFriend2.setUpdateTime(new Date());
                imFriendService.save(imFriend2);
            }catch (Exception e) {
                log.info("e", e);
            }
        }

        return ApiResult.ok(Boolean.TRUE);
    }

}

