const app = getApp();
import { formatDate } from '../../static/lib/utils';
import { sendGroupMessage } from '../../utils/message-sender';
import { showConfirmByScene } from '../../utils/scriptService.js';
import { normalizeGroupMessage, getZhuangtaiText } from '../../utils/group-chat.js';
import { persistGroupMeta } from '../../utils/im-user.js';
import { getFreshImUser } from '../../utils/im-user.js';

Page({
  data: {
    groupId: '',
    groupName: '',
    groupAvatar: '',
    orderId: '',
    isCross: 0,
    orderZhuangtai: null,
    orderZhuangtaiText: '',
    orderJine: '',
    orderJieshao: '',
    currentUser: null,
    messages: [],
    inputText: '',
    showEmojiPanel: false,
    showPlusPanel: false,
    showOrderSender: false,
    loadingHistory: false,
    isRefreshing: false,
    lastTimestamp: null,
    hasMore: true,
    scrollToView: '',
    detailText: '',
    showDetailModal: false,
    lastTapTime: 0,
    lastTapMsgId: '',
    emojiList: ['😀','😁','😂','🤣','😃','😄','😅','😆','😉','😊','😋','😎','😍','😘','😗','😙','😚','🙂','🤗','🤩','🤔','🤨','😐','😑','😶','🙄','😏','😣','😥','😮','🤐','😯','😪','😫','😴','😌','😛','😜','😝','🤤','😒','😓','😔','😕','🙃','🤑','😲','☹','🙁','😖','😞','😟','😤','😢','😭','😦','😧','😨','😩','🤯','😬','😰','😱','🥵','🥶','😳','🤪','😵','😡','😠','🤬','😷','🤒','🤕','🤢','🤮','🤧','😇','🤠','🤡','🤥','🤫','🤭','🧐','🤓','😈','👿','👹','👺','💀','👻','👽','🤖','💩','😺','😸','😹','😻','😼','😽','🙀','😿','😾'],
    pendingImage: '',
    keyboardHeight: 0,
    bottomSafeHeight: 10
  },
  onLoad(options) {
    let p = { groupId: '', groupName: '订单群聊', groupAvatar: '', orderId: '', isCross: 0,
              currentUserId: '', currentUserName: '', currentUserAvatar: '' };
    if (options.data) {
      try {
        const d = JSON.parse(decodeURIComponent(options.data));
        p = { ...p, ...d };
      } catch (e) {}
    }
    this.setData({
      groupId: p.groupId,
      groupName: p.groupName,
      groupAvatar: p.groupAvatar,
      orderId: p.orderId,
      isCross: p.isCross
    });
    wx.setNavigationBarTitle({ title: this.data.groupName });
    // 如果有外部传入的 currentUser 信息，直接用，不再依赖全局状态
    if (p.currentUserId) {
      this.setData({
        currentUser: {
          id: p.currentUserId,
          name: p.currentUserName || `用户${p.currentUserId.replace(/^[A-Za-z]+/,'')}`,
          avatar: p.currentUserAvatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
        }
      });
    } else {
      this.initCurrentUser();
    }

    const meta = (app.globalData.groupInfoMap && app.globalData.groupInfoMap[p.groupId]) || {};
    const initZt = p.orderZhuangtai != null ? p.orderZhuangtai : meta.orderZhuangtai;
    if (initZt != null) {
      this.applyOrderStatus(initZt, {
        orderId: p.orderId || meta.orderId,
        jine: p.orderJine || meta.orderJine,
        jieshao: p.orderDesc || meta.orderDesc,
      });
    }
  },

  onShow() {
    app.globalData.pageState.isInChatPage = true;
    app.globalData.pageState.currentChatId = this.data.groupId;
    app.globalData.pageState.isInGroupChat = true;
    this.ensureChatConnection();
  },

  onHide() {
    app.globalData.pageState.isInChatPage = false;
    app.globalData.pageState.currentChatId = '';
    app.globalData.pageState.isInGroupChat = false;
    this.clearPageListeners();
  },

  applyOrderStatus(zhuangtai, extra) {
    if (zhuangtai == null && zhuangtai !== 0) return;
    const patch = {
      orderZhuangtai: zhuangtai,
      orderZhuangtaiText: getZhuangtaiText(zhuangtai),
    };
    if (extra) {
      if (extra.jine) patch.orderJine = extra.jine;
      if (extra.jieshao) patch.orderJieshao = extra.jieshao;
      if (extra.orderId) patch.orderId = extra.orderId;
    }
    this.setData(patch);

    const groupId = this.data.groupId;
    if (!groupId) return;
    if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
    const meta = { ...(app.globalData.groupInfoMap[groupId] || {}), orderZhuangtai: zhuangtai };
    if (extra && extra.orderId) meta.orderId = extra.orderId;
    app.globalData.groupInfoMap[groupId] = meta;
    persistGroupMeta(app, groupId, meta);
  },

  applyOrderCardPayload(payload) {
    if (!payload) return;
    const zt = payload.zhuangtai != null ? payload.zhuangtai : this.data.orderZhuangtai;
    payload.zhuangtaiText = getZhuangtaiText(zt);
    this.applyOrderStatus(zt, {
      orderId: payload.orderId || payload.dingdan_id || this.data.orderId,
      jine: payload.jine,
      jieshao: payload.jieshao,
    });
    this.updateOrderBubblesInList(payload);
  },

  updateOrderBubblesInList(payload) {
    if (!payload) return;
    const orderId = payload.orderId || payload.dingdan_id;
    if (!orderId) return;
    const messages = this.data.messages.map((m) => {
      if (m.type !== 'order' || !m.payload) return m;
      const oid = m.payload.orderId || m.payload.dingdan_id;
      if (oid !== orderId) return m;
      return { ...m, payload: { ...m.payload, ...payload, orderId: oid } };
    });
    this.setData({ messages });
  },

  mergeServerMessage(localId, status, serverMsg) {
    if (!serverMsg) {
      this.updateMsg(localId, status);
      return;
    }
    normalizeGroupMessage(serverMsg);
    serverMsg.formattedTime = formatDate(serverMsg.timestamp);
    if (serverMsg.type === 'order') {
      this.applyOrderCardPayload(serverMsg.payload);
    }
    const msgs = this.data.messages.map((m) => {
      if (m.messageId !== localId) return m;
      return {
        ...serverMsg,
        showTime: m.showTime,
        status: status || 'success',
        formattedTime: serverMsg.formattedTime || m.formattedTime,
      };
    });
    this.setData({ messages: msgs });
  },

  ensureChatConnection() {
    const role = app.globalData.currentRole || 'normal';
    const uid = wx.getStorageSync('uid');
    const prefixMap = { normal:'Boss', dashou:'Ds', shangjia:'Sj', guanshi:'Gs', zuzhang:'Zz' };
    const targetUserId = (prefixMap[role] || 'Boss') + uid;

    const onReady = () => {
      this.subscribeGroupIfNeeded();
      this.setupAllListeners();
      this.loadHistory(true).then(() => this.markGroupMessageAsRead());
    };

    const connectedId = app.globalData?.goEasyConnection?.userId || wx.goEasy?.im?.userId;
    const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
    const imOk = status === 'connected' || status === 'reconnected';

    if (imOk && connectedId === targetUserId) {
      onReady();
      return;
    }

    if (app.connectWithIdentity) {
      app.connectWithIdentity(role, targetUserId, true).then(onReady).catch(() => {
        const s = wx.goEasy?.getConnectionStatus?.();
        if (s === 'connected' || s === 'reconnected') onReady();
      });
    } else {
      this.connectGoEasy(targetUserId);
    }
  },

  clearPageListeners() {
    this.clearAllListeners();
  },

  connectGoEasy(userId) {
    const { currentUser } = this.data;
    if (!currentUser) return;
    wx.goEasy.connect({
      id: userId,
      data: {
        name: currentUser.name,
        avatar: currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
      },
      onSuccess: () => {
        this.subscribeGroupIfNeeded();
        this.setupAllListeners();
        this.loadHistory(true).then(() => this.markGroupMessageAsRead());
      },
      onFailed: (error) => {
        if (error.code === 408) {
          this.subscribeGroupIfNeeded();
          this.setupAllListeners();
          this.loadHistory(true);
        } else {
          wx.showToast({ title: '连接失败，请重试', icon: 'none' });
        }
      }
    });
  },

  subscribeGroupIfNeeded() {
    const { groupId } = this.data;
    if (!groupId) return;
    wx.goEasy.im.subscribeGroup({
      groupIds: [groupId],
      onSuccess: () => console.log(`[群聊页] 订阅成功: ${groupId}`),
      onFailed: (err) => console.error(`[群聊页] 订阅失败: ${groupId}`, err)
    });
  },

  setupAllListeners() {
    this.clearAllListeners();
    this.listenNewMsg();
    this.listenRecall();
    this.listenDelete();
  },

  clearAllListeners() {
    if (this._msgHandler) { wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this._msgHandler); this._msgHandler = null; }
    if (this._recallHandler) { wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_RECALLED, this._recallHandler); this._recallHandler = null; }
    if (this._deleteHandler) { wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_DELETED, this._deleteHandler); this._deleteHandler = null; }
  },

  initCurrentUser() {
    const uid = wx.getStorageSync('uid');
    const role = app.globalData.currentRole || 'normal';
    const fresh = getFreshImUser(app, role, uid);
    this.setData({ currentUser: {
      id: fresh.id,
      name: fresh.name,
      avatar: fresh.avatar,
    }});
  },

  fixAvatar(url) {
    if (!url) return app.globalData.ossImageUrl + app.globalData.morentouxiang;
    if (url.startsWith('http')) return url;
    return app.globalData.ossImageUrl + url;
  },

  isConnected() {
    const s = wx.goEasy.getConnectionStatus ? wx.goEasy.getConnectionStatus() : 'disconnected';
    return s === 'connected' || s === 'reconnected';
  },

  onPullDownRefresh() {
    if (this.data.loadingHistory) return;
    this.setData({ isRefreshing: true });
    this.loadHistory(false).finally(() => { this.setData({ isRefreshing: false }); wx.stopPullDownRefresh(); });
  },

  loadHistory(refresh) {
    if (!refresh && !this.data.hasMore) return Promise.resolve();
    return new Promise((resolve) => {
      this.setData({ loadingHistory: true });
      const { groupId, lastTimestamp } = this.data;
      const ts = refresh ? null : lastTimestamp;
      wx.goEasy.im.history({
        type: wx.GoEasy.IM_SCENE.GROUP,
        id: groupId,
        lastTimestamp: ts,
        limit: 20,
        onSuccess: (res) => {
          let list = res.content || [];
          list.sort((a, b) => a.timestamp - b.timestamp);
          list.forEach((m, idx) => {
            normalizeGroupMessage(m);
            m.formattedTime = formatDate(m.timestamp);
            if (idx === 0) m.showTime = true;
            else m.showTime = (m.timestamp - list[idx-1].timestamp) / 60000 > 5;
            if (!m.senderData) m.senderData = { name: '未知用户', avatar: '' };
            if (m.type === 'order' && m.payload) {
              this.applyOrderCardPayload(m.payload);
            }
          });
          let final = refresh ? list : [...list, ...this.data.messages];
          if (!refresh) {
            for (let i = 0; i < final.length; i++) {
              if (i === 0) final[i].showTime = true;
              else final[i].showTime = (final[i].timestamp - final[i-1].timestamp) / 60000 > 5;
            }
          }
          const ids = new Set();
          const unique = [];
          for (const m of final) { if (!ids.has(m.messageId)) { ids.add(m.messageId); unique.push(m); } }
          const update = {
            messages: unique,
            hasMore: list.length >= 20,
            lastTimestamp: unique.length ? unique[0].timestamp : lastTimestamp,
            loadingHistory: false
          };
          if (refresh) update.scrollToView = 'msg-bottom';
          this.setData(update);
          resolve();
        },
        onFailed: () => { this.setData({ loadingHistory: false }); resolve(); }
      });
    });
  },

  listenNewMsg() {
    if (this._msgHandler) wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this._msgHandler);
    this._msgHandler = (msg) => {
      if (msg.groupId !== this.data.groupId) return;
      normalizeGroupMessage(msg);
      if (msg.type === 'order' && msg.payload) {
        this.applyOrderCardPayload(msg.payload);
      }
      if (msg.senderId === this.data.currentUser.id && msg.type !== 'order') return;
      msg.formattedTime = formatDate(msg.timestamp);
      const msgs = this.data.messages;
      if (msgs.some((m) => m.messageId === msg.messageId)) return;
      const last = msgs.length ? msgs[msgs.length-1] : null;
      msg.showTime = last ? (msg.timestamp - last.timestamp) / 60000 > 5 : true;
      this.setData({ messages: [...msgs, msg], scrollToView: 'msg-bottom' });
      this.markGroupMessageAsRead();
    };
    wx.goEasy.im.on(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this._msgHandler);
    this.markGroupMessageAsRead(); // ← 收到新消息就标记已读
  },

  markGroupMessageAsRead() {
    if (!this.data.groupId) return;
    wx.goEasy.im.markMessageAsRead({
      type: wx.GoEasy.IM_SCENE.GROUP,
      id: this.data.groupId
    });
  },

  listenRecall() {
    if (this._recallHandler) wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_RECALLED, this._recallHandler);
    this._recallHandler = (msgs) => {
      if (!msgs || !msgs.length) return;
      const ids = new Set(msgs.map(m => m.messageId));
      this.setData({ messages: this.data.messages.filter(m => !ids.has(m.messageId)) });
    };
    wx.goEasy.im.on(wx.GoEasy.IM_EVENT.MESSAGE_RECALLED, this._recallHandler);
  },

  listenDelete() {
    if (this._deleteHandler) wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_DELETED, this._deleteHandler);
    this._deleteHandler = (msgs) => {
      if (!msgs || !msgs.length) return;
      const ids = new Set(msgs.map(m => m.messageId));
      this.setData({ messages: this.data.messages.filter(m => !ids.has(m.messageId)) });
    };
    wx.goEasy.im.on(wx.GoEasy.IM_EVENT.MESSAGE_DELETED, this._deleteHandler);
  },

  onInput(e) { this.setData({ inputText: e.detail.value }); },

  chooseImage() {
    const that = this;
    wx.chooseImage({
      count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'],
      success(res) { that.setData({ pendingImage: res.tempFilePaths[0] }); }
    });
  },

  clearPendingImage() { this.setData({ pendingImage: '' }); },

  sendMessage() {
    if (this.data.pendingImage) {
      const file = this.data.pendingImage;
      showConfirmByScene('chat_image_confirm', () => {
        this.sendImageMsg(file);
        this.setData({ pendingImage: '' });
      });
      return;
    }
    const text = this.data.inputText.trim();
    if (!text) return;
    this.sendText(text);
    this.setData({ inputText: '' });
  },

  sendText(text) {
    const that = this;
    sendGroupMessage({
      msgData: {
        type: 'text',
        text,
        currentUser: that.data.currentUser,
        groupId: that.data.groupId,
        orderId: that.data.orderId,
        isCross: that.data.isCross,
        groupName: that.data.groupName,
        groupAvatar: that.data.groupAvatar
      },
      onSendStart: (localMsg) => {
        const msgs = that.data.messages;
        if (msgs.length) {
          localMsg.showTime = (localMsg.timestamp - msgs[msgs.length-1].timestamp) / 60000 > 5;
        } else {
          localMsg.showTime = true;
        }
        that.setData({ messages: [...msgs, localMsg], scrollToView: 'msg-bottom' });
      },
      onSuccess: (messageId, status, serverMsg) => {
        that.mergeServerMessage(messageId, status, serverMsg);
      }
    });
  },

  sendImageMsg(file) {
    const that = this;
    sendGroupMessage({
      msgData: {
        type: 'image',
        filePath: file,
        currentUser: that.data.currentUser,
        groupId: that.data.groupId,
        orderId: that.data.orderId,
        isCross: that.data.isCross,
        groupName: that.data.groupName,
        groupAvatar: that.data.groupAvatar
      },
      onSendStart: (localMsg) => {
        const msgs = that.data.messages;
        if (msgs.length) {
          localMsg.showTime = (localMsg.timestamp - msgs[msgs.length-1].timestamp) / 60000 > 5;
        } else {
          localMsg.showTime = true;
        }
        that.setData({ messages: [...msgs, localMsg], scrollToView: 'msg-bottom' });
      },
      onSuccess: (messageId, status, serverMsg) => {
        that.mergeServerMessage(messageId, status, serverMsg);
      }
    });
  },

  updateMsg(id, status) {
    this.setData({ messages: this.data.messages.map(m => m.messageId === id ? { ...m, status } : m) });
  },

  needShow(ts) {
    const ms = this.data.messages;
    if (!ms.length) return true;
    const last = ms[ms.length-1];
    return (ts - last.timestamp) / 60000 > 5;
  },

  onBubbleTap(e) {
    const msgId = e.currentTarget.dataset.messageid;
    const text = e.currentTarget.dataset.text;
    const now = Date.now();
    if (msgId === this.data.lastTapMsgId && now - this.data.lastTapTime < 350) {
      this.setData({ detailText: text, showDetailModal: true, lastTapTime:0, lastTapMsgId:'' });
    } else {
      this.data.lastTapTime = now;
      this.data.lastTapMsgId = msgId;
    }
  },

  hideDetail() { this.setData({ showDetailModal: false }); },
  copyDetail() { wx.setClipboardData({ data: this.data.detailText }); },

  showAction(e) {
    const msgId = e.currentTarget.dataset.messageid;
    if (!msgId) return;
    const msg = this.data.messages.find(m => m.messageId === msgId);
    if (!msg || String(msg.messageId).startsWith('local-')) return;
    const itemList = ['复制'];
    if (msg.senderId === this.data.currentUser.id && (Date.now() - msg.timestamp < 120000) && !msg.recalled) {
      itemList.push('撤回');
    }
    itemList.push('删除');
    wx.showActionSheet({
      itemList,
      success: (res) => {
        if (itemList[res.tapIndex] === '复制') {
          if (msg.type === 'text') wx.setClipboardData({ data: msg.payload.text });
          else if (msg.type === 'order') wx.setClipboardData({ data: JSON.stringify(msg.payload) });
        } else if (itemList[res.tapIndex] === '删除') {
          this.deleteMsg(msg);
        } else if (itemList[res.tapIndex] === '撤回') {
          this.recallMsg(msg);
        }
      }
    });
  },

  deleteMsg(msg) {
    wx.showModal({
      title: '提示', content: '仅自己看不到',
      success: (res) => {
        if (res.confirm) {
          wx.goEasy.im.deleteMessage({
            messages: [msg],
            onSuccess: () => { this.setData({ messages: this.data.messages.filter(m => m.messageId !== msg.messageId) }); },
            onFailed: () => { this.setData({ messages: this.data.messages.filter(m => m.messageId !== msg.messageId) }); }
          });
        }
      }
    });
  },

  recallMsg(msg) {
    wx.showModal({
      title: '提示', content: '撤回后群内所有人都看不到该消息',
      success: (res) => {
        if (res.confirm) {
          this.setData({ messages: this.data.messages.filter(m => m.messageId !== msg.messageId) });
          wx.goEasy.im.recallMessage({ messages: [msg], onFailed:()=>{} });
        }
      }
    });
  },

  previewImage(e) { wx.previewImage({ urls: [e.currentTarget.dataset.url], current: e.currentTarget.dataset.url }); },

  togglePlusPanel() { this.setData({ showPlusPanel: !this.data.showPlusPanel, showEmojiPanel: false }); },
  closePlusPanel() { this.setData({ showPlusPanel: false }); },

  openEmojiFromPlus() { this.setData({ showPlusPanel: false, showEmojiPanel: true }); },
  toggleEmoji() { this.setData({ showEmojiPanel: !this.data.showEmojiPanel }); },
  insertEmoji(e) { this.setData({ inputText: this.data.inputText + e.currentTarget.dataset.emoji }); },
  closeEmojiPanel() { this.setData({ showEmojiPanel: false }); },

  openOrderSender() { this.setData({ showOrderSender: true, showPlusPanel: false }); },
  closeOrderSender() { this.setData({ showOrderSender: false }); },

  onSendOrder(e) {
    const order = e.detail.order;
    if (!order) return;
    const that = this;
    const payload = {
      orderId: order.dingdan_id,
      jieshao: order.jieshao,
      jine: order.jine,
      beizhu: order.beizhu
    };
    sendGroupMessage({
      msgData: {
        type: 'order',
        orderPayload: payload,
        currentUser: that.data.currentUser,
        groupId: that.data.groupId,
        orderId: that.data.orderId,
        isCross: that.data.isCross,
        groupName: that.data.groupName,
        groupAvatar: that.data.groupAvatar
      },
      onSendStart: (localMsg) => {
        const msgs = that.data.messages;
        if (msgs.length) {
          localMsg.showTime = (localMsg.timestamp - msgs[msgs.length-1].timestamp) / 60000 > 5;
        } else {
          localMsg.showTime = true;
        }
        that.setData({ messages: [...msgs, localMsg], scrollToView: 'msg-bottom' });
      },
      onSuccess: (messageId, status) => {
        that.updateMsg(messageId, status);
      }
    });
  },

  viewOrderDetail(e) {
    const payload = e.currentTarget.dataset.payload;
    if (!payload) return;
    const text = `订单ID: ${payload.orderId}\n内容: ${payload.jieshao}\n金额: ¥${payload.jine}\n备注: ${payload.beizhu}`;
    this.setData({ detailText: text, showDetailModal: true });
  },

  onKeyboardHeightChange(e) { this.setData({ keyboardHeight: e.detail.height }); }
});