import { PluginUrl } from '@/constants/app';
import { CollectEventName } from '@/constants/event';
import { MessageActionStatus, MessageType } from '@/constants/message';
import { MessageSubscribeIds, SubscribeTempId } from '@/constants/subscribe';
import http from '@/http';
import { API } from '@/http/api';
import store from '@/store';
import { setMessageInfo } from '@/store/actions';
import {
  IChatMessage,
  MainMessage,
  IChatInfo,
  GetNewChatMessagesRequest,
  PostMessageRequest,
  PostConfirmActionRequest,
  IMessageStatus,
  PostActionDetailRequest,
  IChatActionDetail,
  ChatWatchRequest,
} from '@/types/message';
import { getRoleType } from '@/utils/app';
import { logWithPrefix, oncePromise } from '@/utils/common';
import { collectEvent } from '@/utils/event';
import { navigateTo } from '@/utils/route';
import { postSubscribe, subscribeMessage } from '@/utils/subscribe';
import { getUserId } from '@/utils/user';

const log = logWithPrefix('message-utils');

export const isTextMessage = (message: IChatMessage) => message.type === MessageType.Text;

export const isTimeMessage = (message: IChatMessage) => message.type === MessageType.Time;

export const isJobMessage = (message: IChatMessage) => message.type === MessageType.Job;

export const isMaterialMessage = (message: IChatMessage) => message.type === MessageType.Material;

export const isExchangeMessage = (message: IChatMessage) =>
  [MessageType.RequestAnchorContact, MessageType.RequestCompanyContact].includes(message.type);

export const isLocationMessage = (message: IChatMessage) => message.type === MessageType.Location;

export const requestRemainPushTime = oncePromise(() => {
  // if (isDev) {
  //   return Promise.resolve(32);
  // }
  return http.post<number>(API.MESSAGE_REMAIN_PUSH_TIMES);
});

export const requestUnreadMessageCount = oncePromise(async () => {
  const count = await http.post<number>(API.MESSAGE_UNREAD_COUNT);
  log('request unread message success, count:', count);
  store.dispatch(setMessageInfo({ count }));
  return count;
});

export const requestMessageList = oncePromise(async () => {
  const { data } = await http.post<{ data: MainMessage[] }>(API.MESSAGE_CHAT_LIST, { data: { userId: getUserId() } });
  return data;
});

export const requestChatDetail = (chatId: string) => {
  const data = { chatId, roleType: getRoleType() };
  return http.post<IChatInfo>(API.MESSAGE_CHAT, { data, contentType: 'application/x-www-form-urlencoded' });
};

export const requestNewChatMessages = (params: GetNewChatMessagesRequest) => {
  const data = { ...params, roleType: getRoleType() };
  return http.post<IChatMessage[]>(API.MESSAGE_CHAT_NEW, { data });
};

export const requestChatActionStatus = (actionId: string) => {
  return http.post<MessageActionStatus>(API.MESSAGE_GET_ACTION, {
    data: { actionId },
    contentType: 'application/x-www-form-urlencoded',
  });
};

export const requestActionDetail = (data: PostActionDetailRequest) => {
  return http.post<IChatActionDetail | null>(API.MESSAGE_GET_ACTION_DETAIL, { data });
};

export const requestMessageStatusList = async (chatId: string) => {
  return http.post<IMessageStatus[]>(API.MESSAGE_LIST_STATUS, {
    data: { chatId },
    contentType: 'application/x-www-form-urlencoded',
  });
};

export const requestChatWatch = (data: Omit<ChatWatchRequest, 'status'>) => {
  return http.post<boolean>(API.MESSAGE_CHAT_WATCH_GET, { data });
};

export const postAddMessageTimes = async (source: string) => {
  const result = await subscribeMessage(MessageSubscribeIds);
  const successIds: SubscribeTempId[] = [];
  MessageSubscribeIds.forEach(id => {
    result[id] === 'accept' && successIds.push(id);
  });
  collectEvent(CollectEventName.MESSAGE_DEV_LOG, { action: 'subscribe_new_message_reminder', source, successIds });
  await postSubscribe(MessageSubscribeIds, successIds);
};

export const postCreateChat = (toUserId: string) => {
  return http.post<IChatInfo>(API.MESSAGE_CREATE_CHAT, { data: { toUserId } });
};

export const postSendMessage = (data: PostMessageRequest) => {
  if (data.type === MessageType.Text) {
    return http.post(API.MESSAGE_SEND_TEXT, { data });
  }
  return http.post(API.MESSAGE_SEND_ACTION, { data });
};

export const posConfirmAction = (data: PostConfirmActionRequest) => {
  return http.post<IChatInfo>(API.MESSAGE_CONFIRM_ACTION, { data });
};

export const postChatRejectWatch = (data: ChatWatchRequest) => {
  return http.post<IChatInfo>(API.MESSAGE_CHAT_WATCH, { data });
};

export const isChatWithSelf = (toUserId: string) => {
  return getUserId() === toUserId;
};

export const openLocationSelect = () => {
  const key = 'UNCBZ-ZCSLZ-HRJX4-7P4XS-76G5H-6WF2Z';
  const referer = '播络';
  navigateTo(PluginUrl.LocationSelect, { key, referer });
};
