// utils/message-sender.js
const app = getApp();
import { formatDate } from '../static/lib/utils';
import request from './request.js';
import { getLocalImUserId } from './im-user.js';
import { resolveAvatarUrl } from './avatar.js';

function sendGroupMessage(options) {
  const { msgData, onSuccess, onSendStart } = options;
  const { type, currentUser, groupId, orderId, isCross, groupName, groupAvatar } = msgData;

  const localMsg = buildLocalMessage(msgData);
  if (onSendStart) onSendStart(localMsg);

  // 只有 isCross 明确为 0 才走前端 SDK，其余一律走后端
  if (isCross === 0) {
    sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross, groupName, groupAvatar);
    return;
  }
  sendViaBackend(localMsg, currentUser, groupId, orderId, onSuccess);
}

function buildLocalMessage(data) {
  const { type, text, filePath, orderPayload, currentUser, groupId } = data;
  const now = Date.now();
  const base = {
    messageId: `${type}-${now}`,
    timestamp: now,
    senderId: currentUser.id,
    groupId: groupId,
    senderData: {
      name: currentUser.name,
      avatar: currentUser.avatar
    },
    status: 'sending',
    formattedTime: formatDate(now)
  };

  if (type === 'text') return { ...base, type: 'text', payload: { text } };
  if (type === 'image') return { ...base, type: 'image', payload: { url: filePath } };
  if (type === 'order') return { ...base, type: 'order', payload: orderPayload };
  return base;
}

function sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross, groupName, groupAvatar) {
  const toData = {
    name: groupName || '订单群聊',
    avatar: groupAvatar || currentUser.avatar
  };
  if (orderId) toData.orderId = orderId;
  toData.isCross = isCross || 0;

  const to = {
    type: wx.GoEasy.IM_SCENE.GROUP,
    id: groupId,
    data: toData
  };

  let message;
  if (localMsg.type === 'text') {
    message = wx.goEasy.im.createTextMessage({ text: localMsg.payload.text, to });
  } else if (localMsg.type === 'image') {
    message = wx.goEasy.im.createImageMessage({ file: localMsg.payload.url, to });
  } else if (localMsg.type === 'order') {
    message = wx.goEasy.im.createCustomMessage({ type: 'order', payload: localMsg.payload, to });
  }

  wx.goEasy.im.sendMessage({
    message,
    onSuccess: () => { if (onSuccess) onSuccess(localMsg.messageId, 'success'); },
    onFailed: () => { if (onSuccess) onSuccess(localMsg.messageId, 'failed'); }
  });
}

function sendViaBackend(localMsg, currentUser, groupId, orderId, onSuccess) {
  const apiUrl = '/dingdan/kptxxfs';

  // 🔥 实时获取当前身份，不再依赖外部传入的 currentUser.id
  const uid = wx.getStorageSync('uid');
  const role = app.globalData.currentRole || 'normal';
  const identityType = role === 'dashou' ? 'dashou' : (role === 'shangjia' ? 'shangjia' : 'boss');
  const senderId = getLocalImUserId(app) || ('Boss' + uid);

  const params = {
    orderId: orderId,
    groupId: groupId,
    identityType: identityType,    // 告诉后端当前是什么身份
    senderId: senderId,
    senderName: currentUser.name || ('用户' + uid),
    senderAvatar: resolveAvatarUrl(currentUser.avatar, app),
    messageType: localMsg.type,
    messageId: localMsg.messageId,
    timestamp: localMsg.timestamp
  };

  if (localMsg.type === 'text' || localMsg.type === 'order') {
    if (localMsg.type === 'text') {
      params.text = localMsg.payload.text;
    } else {
      params.orderPayload = localMsg.payload;
    }
    request({
      url: apiUrl,
      method: 'POST',
      data: params
    }).then((res) => {
      if (res && res.data && res.data.code === 200) {
        if (onSuccess) onSuccess(localMsg.messageId, 'success');
      } else {
        if (onSuccess) onSuccess(localMsg.messageId, 'failed');
      }
    }).catch(() => {
      if (onSuccess) onSuccess(localMsg.messageId, 'failed');
    });
    return;
  }

  // 图片消息
  if (localMsg.type === 'image') {
    const token = wx.getStorageSync('token');
    const formData = {
      ...params,
      senderInfo: JSON.stringify({ id: senderId, name: params.senderName, avatar: params.senderAvatar })
    };
    wx.uploadFile({
      url: app.globalData.apiBaseUrl + apiUrl,
      filePath: localMsg.payload.url,
      name: 'file',
      formData: formData,
      header: {
        'Authorization': 'Bearer ' + (token || '')
      },
      success(res) {
        try {
          const data = JSON.parse(res.data);
          if (data.code === 200) {
            if (onSuccess) onSuccess(localMsg.messageId, 'success');
          } else {
            if (onSuccess) onSuccess(localMsg.messageId, 'failed');
          }
        } catch (e) {
          if (onSuccess) onSuccess(localMsg.messageId, 'failed');
        }
      },
      fail() {
        if (onSuccess) onSuccess(localMsg.messageId, 'failed');
      }
    });
  }
}

module.exports = { sendGroupMessage };