package com.ruoyi.xq.im;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.manager.ImManager;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.yunxin.client.ImUserClient;
import com.ruoyi.yunxin.req.CreateUserReq;
import com.ruoyi.yunxin.req.UpdateTokenReq;
import com.ruoyi.yunxin.resp.YxCommonR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ImOp {

    @Autowired
    private UserService userService;

    @Autowired
    private ImUserClient imUserClient;

    @Autowired
    private ImManager imManager;


    public void refreshImToken(String usercode){
        User user = userService.getByUsercode(usercode);
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        String imToken = IdUtil.simpleUUID();
        userService.update(Wrappers.lambdaUpdate(User.class).eq(User::getId,user.getId()).set(User::getImToken, imToken));
        this.register(user.getId(),imToken,user.getNickname());
        imManager.updateImInfo(user.getId(),user.getAvatar(),user.getNickname(),user.getGender());
        LoginHelper.logoutApp(user.getId());
    }

    public void refreshImNoSaveToken(){
        List<User> list = userService.list();
        for (User user : list) {
            this.register(user.getId(),user.getImToken(),user.getNickname());
            imManager.updateImInfo(user.getId(),user.getAvatar(),user.getNickname(),user.getGender());
        }
    }


    public void refreshIm(boolean loginOut){
        List<User> list = userService.list();
        for (User user : list) {
            String imToken = IdUtil.simpleUUID();
            userService.update(Wrappers.lambdaUpdate(User.class).eq(User::getId,user.getId()).set(User::getImToken, imToken));
            this.register(user.getId(),imToken,user.getNickname());
            imManager.updateImInfo(user.getId(),user.getAvatar(),user.getNickname(),user.getGender());
            if(loginOut){
                LoginHelper.logoutApp(user.getId());
            }
        }
    }

    public void register(Long userId,String token,String nickname){
        CreateUserReq req = new CreateUserReq();
        req.setAccid(userId+"");
        req.setToken(token);
        req.setName(nickname);
        YxCommonR r = imUserClient.createUser(req);
        if(!r.isSuccess()){
            if(r.getCode() == 414){
                UpdateTokenReq req1 = new UpdateTokenReq();
                req1.setAccid(userId+"");
                req1.setToken(token);
                YxCommonR commonR = imUserClient.updateToken(req1);
                if(!commonR.isSuccess()){
                    log.error("刷新云token失败,{}", JSON.toJSONString(commonR));
                    throw new ServiceException("注册失败，云信异常");
                }
            }else{
                log.error("创建云信账号失败,{}", JSON.toJSONString(r));
                throw new ServiceException("注册失败，云信异常");
            }
        }
    }
}
