package com.ruoyi.cai.controller.admin;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
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.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/cai/im")
@Slf4j
public class ImController {

    @Autowired
    private ImUserClient imUserClient;
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public R<Void> registerIm(Long userId){
        User user = userService.getById(userId);
        if(user == null){
            return R.fail("用户不存在");
        }
        register(user);
        return R.ok();
    }

    private void register(User user){
        CreateUserReq req = new CreateUserReq();
        req.setAccid(user.getId()+"");
        req.setToken(user.getImToken());
        req.setName(user.getNickname());
        YxCommonR r = imUserClient.createUser(req);
        if(!r.isSuccess()){
            if(r.getCode() == 414){
                UpdateTokenReq req1 = new UpdateTokenReq();
                req1.setAccid(user.getId()+"");
                req1.setToken(user.getImToken());
                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("注册失败，云信异常");
            }
        }
    }

    @GetMapping("/registerAll")
    public R<Void> registerAllIm(){
        int current = 0;
        int success = 0;
        int fail = 0;
        while (true){
            current++;
            Page<User> page = new Page<>(current,100);
            Page<User> data = userService.page(page);
            List<User> records = data.getRecords();
            if(records.isEmpty()){
                break;
            }
            for (User record : records) {
                try {
                    register(record);
                    success++;
                }catch (Exception e){
                    log.error("刷新token失败",e);
                    fail++;
                }
            }
        }
        return R.ok(String.format("总数：%s,成功数:%s,失败数：%s", success+fail,success,fail));
    }
}
