package com.bcxin.identify.api.yehuo.service;

import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.OutputCreateUser;
import cn.wildfirechat.pojos.OutputGetIMTokenData;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.identify.api.yehuo.dto.request.YehuoGetUserTokenRequest;
import com.bcxin.identify.api.yehuo.dto.response.YehuoGetUserTokenResponse;
import com.bcxin.identify.util.HttpUtil;
import com.bcxin.identify.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * description：野火服务层
 * author：linchunpeng
 * date：2023/10/16
 */
@Service
@Slf4j
public class YehuoService {


    @Value("${ye-huo.app-server.url}")
    private String appServerUrl;

    /**
     * description：获取用户token
     * author：linchunpeng
     * date：2023/10/16
     */
    public Result getToken(YehuoGetUserTokenRequest request) {
        try {
            IMResult<InputOutputUserInfo> userResult = UserAdmin.getUserByUserId(request.getUserId());
            InputOutputUserInfo userInfo = userResult.getResult();
            String displayName = StringUtils.isNotBlank(request.getDisplayName()) ? request.getDisplayName() : request.getIdNumber();
            if (userInfo == null) {
                log.info("用户：{}，不存在，创建一个", JSONObject.toJSONString(request));
                InputOutputUserInfo user = new InputOutputUserInfo();
                user.setUserId(request.getUserId());
                user.setName(request.getIdNumber());
                user.setDisplayName(displayName);
                user.setMobile(request.getMobile());
                IMResult<OutputCreateUser> createUserResult = UserAdmin.createUser(user);
                if (createUserResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                    log.info("用户：{}，创建成功", request.getUserId());
                } else {
                    log.info("用户：{}，创建失败，msg：{}", request.getUserId(), createUserResult.getErrorCode().getMsg());
                }
            } else {
                if (!userInfo.getName().equals(request.getIdNumber())) {
                    userInfo.setName(request.getIdNumber());
                    UserAdmin.updateUserInfo(userInfo, ProtoConstants.UpdateUserInfoMask.Update_User_Name);
                }
                if (!userInfo.getDisplayName().equals(displayName)) {
                    userInfo.setDisplayName(displayName);
                    UserAdmin.updateUserInfo(userInfo, ProtoConstants.UpdateUserInfoMask.Update_User_DisplayName);
                }
                if (!userInfo.getMobile().equals(request.getMobile())) {
                    userInfo.setMobile(request.getMobile());
                    UserAdmin.updateUserInfo(userInfo, ProtoConstants.UpdateUserInfoMask.Update_User_Mobile);
                }
            }

            IMResult<OutputGetIMTokenData> tokenResult = UserAdmin.getUserToken(request.getUserId(), request.getClientId(), request.getPlatform());
            if (tokenResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
                log.error("用户：{}，获取token失败，msg：{}", request.getUserId(), tokenResult.getErrorCode().getMsg());
                return Result.fail(tokenResult.getErrorCode().getMsg());
            }
            YehuoGetUserTokenResponse response = new YehuoGetUserTokenResponse();
            response.setToken(tokenResult.getResult().getToken());

            String appServerResult = HttpUtil.post(appServerUrl + "/login_user_id", JSONObject.toJSONString(request));
            if (!"fail".equals(appServerResult)) {
                JSONObject jsonObject = JSONObject.parseObject(appServerResult);
                Integer code = jsonObject.getInteger("code");
                if (code != null && code == 0) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    if (result != null) {
                        response.setAuthToken(result.getString("token"));
                    }
                }
            }

            return Result.success("success", response);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

}
