/**
 * 打手-商家/老板配对群：group_Ds{打手}_Sj{商家}
 */
export const ORDER_CARD_PREFIX = '[ORDER_CARD]';

const ZHUANGTAI_MAP = {
  1: '已下单', 2: '进行中', 3: '已完成', 4: '退款中',
  5: '已退款', 6: '退款失败', 7: '指定中', 8: '结算中',
};

export function getZhuangtaiText(zhuangtai) {
  if (zhuangtai == null || zhuangtai === '') return '';
  const n = Number(zhuangtai);
  return ZHUANGTAI_MAP[n] || ZHUANGTAI_MAP[zhuangtai] || '';
}

export function buildDashouShangjiaGroupId(dashouUid, shangjiaUid) {
  return `group_Ds${dashouUid}_Sj${shangjiaUid}`;
}

export function buildDashouBossGroupId(dashouUid, bossUid) {
  return `group_Ds${dashouUid}_Boss${bossUid}`;
}

export function resolveLocalGroupId(identityType, myUid, partnerUid, fadanPingtai, orderId, isCross) {
  const cross = isCross === 1 || isCross === true || String(isCross) === '1';
  if (cross && orderId) {
    return `group_${orderId}`;
  }
  if (!myUid) return orderId ? `group_${orderId}` : null;
  if (!partnerUid) return orderId ? `group_${orderId}` : null;
  if (identityType === 'shangjia') {
    return buildDashouShangjiaGroupId(partnerUid, myUid);
  }
  if (identityType === 'dashou') {
    if (fadanPingtai === 2 || String(fadanPingtai) === '2') {
      return buildDashouShangjiaGroupId(myUid, partnerUid);
    }
    return buildDashouBossGroupId(myUid, partnerUid);
  }
  return orderId ? `group_${orderId}` : null;
}

export function isPairGroupId(groupId) {
  return /^group_Ds\w+_(Sj|Boss)\w+$/.test(groupId || '');
}

export function parsePairGroupId(groupId) {
  if (!groupId) return null;
  let m = /^group_Ds(\w+)_Sj(\w+)$/.exec(groupId);
  if (m) return { dashouId: `Ds${m[1]}`, partnerId: `Sj${m[2]}`, partnerRole: 'shangjia' };
  m = /^group_Ds(\w+)_Boss(\w+)$/.exec(groupId);
  if (m) return { dashouId: `Ds${m[1]}`, partnerId: `Boss${m[2]}`, partnerRole: 'boss' };
  return null;
}

export function getCounterpartGoEasyId(groupId, myGoEasyId) {
  const parsed = parsePairGroupId(groupId);
  if (!parsed || !myGoEasyId) return null;
  if (myGoEasyId === parsed.dashouId) return parsed.partnerId;
  if (myGoEasyId === parsed.partnerId) return parsed.dashouId;
  return null;
}

function fixAvatarUrl(avatar, defaultAvatar, ossBase) {
  if (!avatar) return defaultAvatar;
  if (avatar.startsWith('http')) return avatar;
  return (ossBase || '') + avatar.replace(/^\//, '');
}

/** 根据群 to.data 与当前身份，解析对方/双方展示信息 */
export function applyPairMetaToConversation(item, myGoEasyId, defaultAvatar, ossBase) {
  if (!item || !item.data) return;
  const d = item.data;

  if (d.dashouGoEasyId && d.partnerGoEasyId) {
    const isDashou = myGoEasyId === d.dashouGoEasyId;
    const isPartner = myGoEasyId === d.partnerGoEasyId;
    d.dashouNicheng = d.dashouName || d.dashouNicheng || '';
    d.partnerNicheng = d.partnerName || d.partnerNicheng || '';
    d.dashouAvatar = fixAvatarUrl(d.dashouAvatar, defaultAvatar, ossBase);
    d.partnerAvatar = fixAvatarUrl(d.partnerAvatar, defaultAvatar, ossBase);

    if (isDashou) {
      d.counterpartId = d.partnerGoEasyId;
      d.counterpartYonghuid = d.partnerYonghuid || d.partnerGoEasyId.replace(/^(Sj|Boss)/, '');
      d.partnerRoleLabel = d.partnerGoEasyId.startsWith('Boss') ? '老板' : '商家';
      d.name = d.partnerNicheng || `${d.partnerRoleLabel}${d.counterpartYonghuid}`;
      d.avatar = d.partnerAvatar || defaultAvatar;
    } else if (isPartner) {
      d.counterpartId = d.dashouGoEasyId;
      d.counterpartYonghuid = d.dashouYonghuid || d.dashouGoEasyId.replace(/^Ds/, '');
      d.name = d.dashouNicheng || `打手${d.counterpartYonghuid}`;
      d.avatar = d.dashouAvatar || defaultAvatar;
    } else {
      const cpId = getCounterpartGoEasyId(item.groupId, myGoEasyId);
      if (cpId === d.partnerGoEasyId) {
        d.name = d.partnerNicheng;
        d.avatar = d.partnerAvatar || defaultAvatar;
      } else if (cpId === d.dashouGoEasyId) {
        d.name = d.dashouNicheng;
        d.avatar = d.dashouAvatar || defaultAvatar;
      }
    }
    return;
  }

  const counterpartId = getCounterpartGoEasyId(item.groupId, myGoEasyId);
  if (counterpartId) {
    d.counterpartId = counterpartId;
    d.counterpartYonghuid = counterpartId.replace(/^(Ds|Sj|Boss)/, '');
    if (!d.name || d.name === item.groupId) {
      d.name = `用户${d.counterpartYonghuid.slice(-6)}`;
    }
  }

  if (item.lastMessage && item.lastMessage.senderId && item.lastMessage.senderId !== myGoEasyId) {
    const sd = item.lastMessage.senderData || {};
    if (sd.avatar) d.avatar = fixAvatarUrl(sd.avatar, defaultAvatar, ossBase);
    if (sd.name) d.name = sd.name;
  }

  d.avatar = fixAvatarUrl(d.avatar, defaultAvatar, ossBase);
}

export function parseOrderCardText(text) {
  if (!text || !text.startsWith(ORDER_CARD_PREFIX)) return null;
  try {
    const data = JSON.parse(text.slice(ORDER_CARD_PREFIX.length));
    return {
      orderId: data.dingdan_id,
      jieshao: data.jieshao || '',
      jine: data.jine || '',
      beizhu: data.beizhu || '',
      zhuangtai: data.zhuangtai,
      nicheng: data.nicheng || '',
      create_time: data.create_time || '',
    };
  } catch (e) {
    return null;
  }
}

import { getChatImageUrl } from '../static/lib/utils.js';

export function normalizeGroupMessage(msg) {
  if (!msg) return msg;
  if (msg.type === 'text' && msg.payload && msg.payload.text) {
    const card = parseOrderCardText(msg.payload.text);
    if (card) {
      msg.type = 'order';
      msg.payload = card;
    }
  }
  if (msg.type === 'custom' && msg.payload) {
    const inner = msg.payload.payload || msg.payload;
    if (inner && (inner.orderId || inner.dingdan_id)) {
      msg.type = 'order';
      msg.payload = {
        orderId: inner.orderId || inner.dingdan_id,
        jieshao: inner.jieshao || '',
        jine: inner.jine || '',
        beizhu: inner.beizhu || '',
        zhuangtai: inner.zhuangtai,
        nicheng: inner.nicheng || '',
        create_time: inner.create_time || '',
      };
    }
  }
  if (msg.type === 'image') {
    const url = getChatImageUrl(msg);
    msg.payload = { ...(msg.payload || {}), url };
    msg.imageUrl = url;
  }
  return msg;
}

export function formatLastMessagePreview(msg) {
  if (!msg) return '';
  if (msg.type === 'text' && msg.payload && msg.payload.text) {
    const card = parseOrderCardText(msg.payload.text);
    if (card) return `[订单] ${card.jieshao || card.orderId}`;
    return msg.payload.text;
  }
  if (msg.type === 'order' && msg.payload) {
    return `[订单] ${msg.payload.jieshao || msg.payload.orderId || ''}`;
  }
  if (msg.type === 'image') return '[图片]';
  return '[消息]';
}

export function enrichGroupConversation(item, myGoEasyId, defaultAvatar, ossBase) {
  if (!item || item.type !== 'group') return item;
  if (!item.data) item.data = {};

  applyPairMetaToConversation(item, myGoEasyId, defaultAvatar, ossBase);

  if (item.data.orderZhuangtai != null) {
    item.data.orderZhuangtaiText = ZHUANGTAI_MAP[item.data.orderZhuangtai] || '';
  }

  item.displayLastMsg = formatLastMessagePreview(item.lastMessage);
  if (!item.data.avatar) item.data.avatar = defaultAvatar;
  return item;
}

export function isOrderGroupConversation(c) {
  if (!c || c.type !== 'group') return false;
  if (c.data && c.data.orderId) return true;
  if (c.data && c.data.dashouGoEasyId) return true;
  return isPairGroupId(c.groupId) || /^group_\w+$/.test(c.groupId || '');
}

export function getConversationSortTime(conversation, openTimes) {
  const id = conversation.groupId || conversation.userId || '';
  const msgTs = conversation.lastMessage?.timestamp || 0;
  const openTs = (openTimes && id && openTimes[id]) ? openTimes[id] : 0;
  return Math.max(msgTs, openTs);
}

export function sortConversations(list, openTimes) {
  return list.sort((a, b) => {
    if (a.top && !b.top) return -1;
    if (!a.top && b.top) return 1;
    if (a.unread > 0 && b.unread <= 0) return -1;
    if (a.unread <= 0 && b.unread > 0) return 1;
    const ta = getConversationSortTime(a, openTimes);
    const tb = getConversationSortTime(b, openTimes);
    return tb - ta;
  });
}

export function recordConversationOpen(conversation) {
  const id = conversation?.groupId || conversation?.userId;
  if (!id) return;
  try {
    const times = wx.getStorageSync('conversationOpenTimes') || {};
    times[id] = Date.now();
    wx.setStorageSync('conversationOpenTimes', times);
  } catch (e) {}
}
