package com.sonic.pigeon.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.netease.nim.server.sdk.core.Result;
import com.netease.nim.server.sdk.core.exception.YunxinSdkException;
import com.netease.nim.server.sdk.im.v2.YunxinV2ApiServices;
import com.netease.nim.server.sdk.im.v2.account.request.CreateAccountRequestV2;
import com.netease.nim.server.sdk.im.v2.account.response.CreateAccountResponseV2;
import com.netease.nim.server.sdk.im.v2.users.request.GetUserRequestV2;
import com.netease.nim.server.sdk.im.v2.users.request.UpdateUserRequestV2;
import com.netease.nim.server.sdk.im.v2.users.response.GetUserResponseV2;
import com.netease.nim.server.sdk.im.v2.users.response.UpdateUserResponseV2;
import com.sonic.pigeon.domain.output.ImUserAccountOutput;
import com.sonic.pigeon.lib.enums.ImUserTypeEnum;
import com.sonic.pigeon.lib.input.CreateImUserInput;
import com.sonic.pigeon.lib.input.EditImUserInput;
import com.sonic.pigeon.service.ImUserService;
import com.sonic.pigeon.utils.ImGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ImUserServiceImpl implements ImUserService {

    @Autowired
    private YunxinV2ApiServices yunxinV2ApiServices;
    @Autowired
    private ImGenerator imGenerator;

    @Override
    public void createImUser(CreateImUserInput input) {
        CreateAccountRequestV2 request = new CreateAccountRequestV2();
        //生成账号用户ID
        request.setAccountId(imGenerator.genImAccountId(input.getUserId(), input.getImUserType()));
        //生成账号登录密码
        request.setToken(imGenerator.genImAccountToken(request.getAccountId()));

        //创建用户基础信息
        CreateAccountRequestV2.UserInformation userInformation = new CreateAccountRequestV2.UserInformation();
        userInformation.setName(input.getNickname());
        userInformation.setAvatar(input.getHeadImage());
        userInformation.setGender(input.getGender());
        userInformation.setBirthday(input.getBirthday());
        userInformation.setExtension(input.getExtension() == null ? null : JSONObject.toJSONString(input.getExtension()));

        request.setUserInformation(userInformation);

        try {
            Result<CreateAccountResponseV2> result = yunxinV2ApiServices.getAccountService().createAccount(request);
            if (result.isSuccess()) {
                CreateAccountResponseV2 response = result.getResponse();
                // 注册成功
                log.info("===> register success, response : {}, traceId : {}", JSONObject.toJSONString(response), result.getTraceId());
            } else {
                // 注册失败，如参数错误、重复注册等
                log.info("===> register fail, code : {}, msg : {}, traceId : {}", result.getCode(), result.getMsg(), result.getTraceId());
            }
        } catch (YunxinSdkException e) {
            // 超时等异常
            log.error("===> register error, endpoint : {}, traceId : {}", e.getContext().getEndpoint(), e.getTraceId());
        }
    }

    @Override
    public void editImUser(EditImUserInput input) {
        UpdateUserRequestV2 request = new UpdateUserRequestV2();
        //生成账号用户ID
        request.setAccountId(imGenerator.genImAccountId(input.getUserId(), input.getImUserType()));
        request.setName(input.getNickname());
        request.setAvatar(input.getHeadImage());
        request.setGender(input.getGender());
        request.setBirthday(input.getBirthday());
        request.setExtension(input.getExtension() == null ? null : JSONObject.toJSONString(input.getExtension()));
        try {
            Result<UpdateUserResponseV2> result = yunxinV2ApiServices.getUserService().updateUser(request);
            if (result.isSuccess()) {
                UpdateUserResponseV2 response = result.getResponse();
                // 更新成功
                log.info("===> update success, response : {}, traceId : {}", JSONObject.toJSONString(response), result.getTraceId());
            } else {
                // 更新失败，如参数错误等
                log.info("===> update fail, code : {}, msg : {}, traceId : {}", result.getCode(), result.getMsg(), result.getTraceId());
            }
        } catch (YunxinSdkException e) {
            // 超时等异常
            log.error("===> update error, endpoint : {}, traceId : {}", e.getContext().getEndpoint(), e.getTraceId());
        }
    }

    @Override
    public GetUserResponseV2 getImUser(Long userId, ImUserTypeEnum imUserType) {
        GetUserRequestV2 request = new GetUserRequestV2();
        //生成账号用户ID
        request.setAccountId(imGenerator.genImAccountId(userId, imUserType));
        try {
            Result<GetUserResponseV2> result = yunxinV2ApiServices.getUserService().getUser(request);
            GetUserResponseV2 response = result.getResponse();
            if (result.isSuccess()) {
                // 更新成功
                log.info("===> getImUser success, response : {}, traceId : {}", JSONObject.toJSONString(response), result.getTraceId());
            } else {
                // 更新失败，如参数错误等
                log.info("===> getImUser fail, code : {}, msg : {}, traceId : {}", result.getCode(), result.getMsg(), result.getTraceId());
            }
            return response;
        } catch (YunxinSdkException e) {
            // 超时等异常
            log.error("===> getImUser error, endpoint : {}, traceId : {}", e.getContext().getEndpoint(), e.getTraceId());
        }
        return null;
    }

    @Override
    public ImUserAccountOutput getImUserAccount(Long userId) {
        ImUserAccountOutput output = new ImUserAccountOutput();
        output.setAccountId(imGenerator.genImAccountId(userId, ImUserTypeEnum.u));
        output.setToken(imGenerator.genImAccountToken(output.getAccountId()));
        return output;
    }

}
