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

function isCrossPlatformOrder(isCross) {
  return isCross === 1 || isCross === true || String(isCross) === '1';
}

function sendGroupMessage(options) {
  const { msgData, onSuccess, onSendStart } = options;
  const role = app.globalData.currentRole || 'normal';
  const uid = wx.getStorageSync('uid');
  const freshUser = getFreshImUser(app, role, uid);
  msgData.currentUser = {
    ...msgData.currentUser,
    name: freshUser.name,
    avatar: freshUser.avatar,
  };

  const { type, currentUser, groupId, orderId, isCross, groupName, groupAvatar } = msgData;

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

  if (!isCrossPlatformOrder(isCross)) {
    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: `local-${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 }, imageUrl: filePath };
  if (type === 'order') return { ...base, type: 'order', payload: orderPayload };
  return base;
}

function sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross, groupName, groupAvatar) {
  const groupMeta = (app.globalData.groupInfoMap && app.globalData.groupInfoMap[groupId]) || {};
  const toData = {
    name: groupName || groupMeta.name || '订单群聊',
    avatar: groupAvatar || groupMeta.avatar || currentUser.avatar,
    orderId: orderId || groupMeta.orderId,
    isCross: isCross || 0,
    dashouGoEasyId: groupMeta.dashouGoEasyId,
    partnerGoEasyId: groupMeta.partnerGoEasyId,
    dashouYonghuid: groupMeta.dashouYonghuid,
    partnerYonghuid: groupMeta.partnerYonghuid,
    dashouName: groupMeta.dashouName,
    partnerName: groupMeta.partnerName,
    dashouAvatar: groupMeta.dashouAvatar,
    partnerAvatar: groupMeta.partnerAvatar,
    orderDesc: groupMeta.orderDesc,
    orderZhuangtai: groupMeta.orderZhuangtai,
  };

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

  if (localMsg.type === 'image') {
    sendGoEasyImage({
      file: localMsg.payload.url,
      to,
      onSuccess: (res) => {
        const serverMsg = res && res.content;
        if (serverMsg && onSuccess) {
          onSuccess(localMsg.messageId, 'success', serverMsg);
        } else if (onSuccess) {
          onSuccess(localMsg.messageId, 'success');
        }
      },
      onFailed: () => { if (onSuccess) onSuccess(localMsg.messageId, 'failed'); }
    });
    return;
  }

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

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

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

  const uid = wx.getStorageSync('uid');
  const role = app.globalData.currentRole || 'normal';
  const identityType = role === 'dashou' ? 'dashou' : (role === 'shangjia' ? 'shangjia' : 'boss');
  const prefixMap = { normal: 'Boss', dashou: 'Ds', shangjia: 'Sj', guanshi: 'Gs', zuzhang: 'Zz' };
  const prefix = prefixMap[role] || 'Boss';
  const senderId = prefix + uid;
  const freshUser = getFreshImUser(app, role, uid);
  const params = {
    orderId: orderId,
    groupId: groupId,
    identityType: identityType,
    senderId: senderId,
    senderName: freshUser.name || currentUser.name || ('用户' + uid),
    senderAvatar: freshUser.avatar || currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang),
    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 };
