package com.wzj.soopin.member.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.service.ITencentIMServicce;
import com.wzj.soopin.member.util.GenerateTestUserSig;
import com.wzj.soopin.member.util.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class TencentIMServiceImpl implements ITencentIMServicce {

    @Value("${tencent.im.administrator}")
    private String adminAccount;

    /**
     * 创建腾讯云IM账号
     */
    @Override
    public String createTencentIMAccount(Member member) {

        String phone=member.getPhoneHidden();
        try {

            //这里生成一个管理员签名，
            String adminSig=generateUserSig(adminAccount);
            String random = String.valueOf(System.currentTimeMillis());


            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("UserID", member.getId()+"");
            requestBody.put("Nick", member.getNickname());
            requestBody.put("FaceUrl", member.getAvatar());

            // 构建URL - 使用管理员账号(administrator)而不是用户ID来生成签名
            String urlString = String.format(
                "https://console.tim.qq.com/v4/im_open_login_svc/account_import" +
                    "?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
                GenerateTestUserSig.SDKAPPID,
                adminAccount, // 使用管理员账号
                adminSig, // 使用管理员的UserSig
                random);
//            return userSig;

            // 创建HTTP客户端
            OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

            // 发送请求
            Request request = new Request.Builder()
                .url(urlString)
                .post(RequestBody.create(MediaType.get("application/json; charset=utf-8"),
                    requestBody.toString()))
                .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.error("创建IM账号失败: {}, 状态码: {}",phone , response.code());
                    throw new ServiceException(String.format("创建IM账号异常: %s", phone));
                }

                String responseBody = response.body().string();
                JSONObject jsonResponse = new JSONObject(responseBody);
                int errorCode = jsonResponse.getInt("ErrorCode");

                if (errorCode == 0) {
                    log.info("创建IM账号成功: {}", phone);
                    // 生成用户的UserSig
                    return generateUserSig(member.getId()+"");
                } else {
                    log.error("创建IM账号失败: {}, 错误码: {}, 错误信息: {}",
                        phone, errorCode, jsonResponse.get("ErrorInfo"));
                    throw new ServiceException(String.format("创建IM账号异常: %s", phone));

                }
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("创建IM账号异常: %s", phone));
        }
    }


    /**
     * 更新用户角色
     */
    @Override
    public void updateMemberRole(Member member) {
        //调用腾讯云IM接口更新用户角色

        String phone=member.getPhoneHidden();
        try {

            //这里生成一个管理员签名，
            String adminSig=generateUserSig(adminAccount);
            String random = String.valueOf(System.currentTimeMillis());

            JSONObject object=new JSONObject();
            object.put("Tag","Tag_Profile_IM_Role");
            object.put("Value",member.getRole());

            JSONArray jsonArray = new JSONArray();
            jsonArray.add(object);
            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("From_Account", member.getId()+"");
            requestBody.put("ProfileItem", jsonArray);

            // 构建URL - 使用管理员账号(administrator)而不是用户ID来生成签名
            String urlString = String.format(
                "https://console.tim.qq.com/v4/profile/portrait_set" +
                    "?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
                GenerateTestUserSig.SDKAPPID,
                adminAccount, // 使用管理员账号
                adminSig, // 使用管理员的UserSig
                random);
//            return userSig;

            // 创建HTTP客户端
            OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

            // 发送请求
            Request request = new Request.Builder()
                .url(urlString)
                .post(RequestBody.create(MediaType.get("application/json; charset=utf-8"),
                    requestBody.toString()))
                .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.error("更新IM账号角色失败: {}, 状态码: {}",phone , response.code());
                    throw new ServiceException(String.format("创建IM账号异常: %s", phone));
                }

                String responseBody = response.body().string();
                JSONObject jsonResponse = new JSONObject(responseBody);
                int errorCode = jsonResponse.getInt("ErrorCode");

                if (errorCode == 0) {
                    log.info("更新IM账号角色成功: {}", phone);
                } else {
                    log.error("更新IM账号角色失败: {}, 错误码: {}, 错误信息: {}",
                        phone, errorCode, jsonResponse.get("ErrorInfo"));
                    throw new ServiceException(String.format("更新IM账号角色异常: %s", phone));

                }
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("更新IM账号角色异常: %s", phone));
        }
    }

    /**
     * 生成UserSig
     */
    private String generateUserSig(String userId) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(GenerateTestUserSig.SDKAPPID, GenerateTestUserSig.SECRETKEY);
        long expire = TimeUnit.DAYS.toSeconds(365 * 50); // 50年有效期
        return tlsSigAPIv2.genUserSig(userId, expire);
    }
}
