import type { MessageReceiveOptType } from "@openim/wasm-client-sdk";

import { IMSDK } from "@/layout/MainContentWrap";

// 原 OpenIM chat 业务服务（:10008）已下线，用户信息相关接口全部改走 OpenIM SDK。
// 以下导出保持原有函数签名和返回形状（{ data: { users } } 等），调用处无需大改。

export interface BusinessUserInfo {
  userID: string;
  password: string;
  account: string;
  phoneNumber: string;
  areaCode: string;
  email: string;
  nickname: string;
  faceURL: string;
  gender: number;
  level: number;
  birth: number;
  allowAddFriend: BusinessAllowType;
  allowBeep: BusinessAllowType;
  allowVibration: BusinessAllowType;
  globalRecvMsgOpt: MessageReceiveOptType;
}

export enum BusinessAllowType {
  Allow = 1,
  NotAllow = 2,
}

// 批量获取用户信息（原 chat 服务 /user/find/full）
// SDK 只提供公开资料（userID/nickname/faceURL/ex），手机号、邮箱等原业务字段不再有值。
export const getBusinessUserInfo = async (userIDs: string[]) => {
  const { data } = await IMSDK.getUsersInfo(userIDs);
  return {
    data: {
      users: data as unknown as BusinessUserInfo[],
    },
  };
};

// 按工号精确查找用户（原 chat 服务 /user/search/full）
export const searchBusinessUserInfo = async (keyword: string) => {
  try {
    const { data } = await IMSDK.getUsersInfo([keyword]);
    return {
      data: {
        total: data.length,
        users: data as unknown as BusinessUserInfo[],
      },
    };
  } catch {
    // 查不到（用户不存在等）统一按无结果处理，由调用处提示“未搜索到相关结果”
    return {
      data: {
        total: 0,
        users: [] as BusinessUserInfo[],
      },
    };
  }
};

interface UpdateBusinessUserInfoParams {
  email: string;
  nickname: string;
  faceURL: string;
  gender: number;
  birth: number;
  allowAddFriend: number;
  allowBeep: number;
  allowVibration: number;
  globalRecvMsgOpt: number;
}

// 更新个人资料（原 chat 服务 /user/update）
// OpenIM 只支持同步昵称/头像等字段，邮箱、性别、生日等业务字段仅更新本地，不会落服务端。
export const updateBusinessUserInfo = async (
  params: Partial<UpdateBusinessUserInfoParams>,
) => {
  const imFields: { nickname?: string; faceURL?: string; globalRecvMsgOpt?: MessageReceiveOptType } =
    {};
  if (params.nickname !== undefined) imFields.nickname = params.nickname;
  if (params.faceURL !== undefined) imFields.faceURL = params.faceURL;
  if (params.globalRecvMsgOpt !== undefined) {
    imFields.globalRecvMsgOpt = params.globalRecvMsgOpt as MessageReceiveOptType;
  }
  await IMSDK.setSelfInfo(imFields);
  return { data: {} };
};
