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

Page({
  data: {
    groupId: '',
    groupName: '',
    groupAvatar: '',
    orderId: '',
    isCross: 0,
    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: '',
    pendingImageFile: null,
    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 });
    if (p.currentUserId) {
      this.setData({
        currentUser: {
          id: p.currentUserId,
          name: p.currentUserName || `用户${p.currentUserId.replace(/^[A-Za-z]+/,'')}`,
          avatar: resolveAvatarUrl(p.currentUserAvatar, app)
        }
      });
    } else {
      this.initCurrentUser();
    }
  },
  
  initCurrentUser() {
    const imId = getLocalImUserId(app);
    const uid = wx.getStorageSync('uid');
    this.setData({
      currentUser: {
        id: imId || ('Boss' + uid),
        name: app.globalData.currentUser?.name || `用户${uid}`,
        avatar: resolveAvatarUrl(wx.getStorageSync('touxiang'), app),
      },
    });
  },

  buildImageFile(tempPath, size) {
    return {
      path: tempPath,
      tempFilePath: tempPath,
      size: size || 0,
    };
  },

  normalizeMessage(msg) {
    if (!msg) return msg;
    if (!msg.payload) msg.payload = {};
    if (msg.type === 'image') {
      const p = msg.payload;
      if (!p.url) p.url = p.thumbnail || p.thumb || p.imageUrl || '';
    }
    return msg;
  },

  mergeSentMessage(localId, sent) {
    if (!sent) {
      this.updateMsg(localId, 'success');
      return;
    }
    const msgs = this.data.messages.map((m) => {
      if (m.messageId !== localId) return m;
      return this.normalizeMessage({
        ...m,
        ...sent,
        status: 'success',
        messageId: sent.messageId || m.messageId,
        payload: sent.payload || m.payload,
        senderData: m.senderData || sent.senderData,
      });
    });
    this.setData({ messages: msgs });
  },

  onShow() {
    this.autoConnect();
  },

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

  autoConnect() {
    const targetUserId = getLocalImUserId(app);
    if (!targetUserId) return;

    const status = wx.goEasy.getConnectionStatus ? wx.goEasy.getConnectionStatus() : 'disconnected';
    if (status === 'connected' || status === 'reconnected') {
      const currentUserId = wx.goEasy.im ? wx.goEasy.im.userId : null;
      if (currentUserId === targetUserId) {
        this.subscribeGroupIfNeeded();
        this.setupAllListeners();
        this.loadHistory(true);
        return;
      } else {
        wx.goEasy.disconnect();
      }
    }
    this.connectGoEasy(targetUserId);
  },

  connectGoEasy(userId) {
    const { currentUser } = this.data;
    if (!currentUser) return;
    wx.goEasy.connect({
      id: userId,
      data: {
        name: currentUser.name,
        avatar: resolveAvatarUrl(currentUser.avatar, app),
      },
      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: () => {},
      onFailed: () => {}
    });
  },

  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; }
  },

  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) => {
            m = this.normalizeMessage(m);
            list[idx] = 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: '' };
          });
          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;
      if (msg.senderId === this.data.currentUser.id) return;
      msg = this.normalizeMessage(msg);
      msg.formattedTime = formatDate(msg.timestamp);
      const msgs = this.data.messages;
      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.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const file = (res.tempFiles && res.tempFiles[0]) || null;
        if (!file || !file.tempFilePath) return;
        that.setData({
          pendingImage: file.tempFilePath,
          pendingImageFile: that.buildImageFile(file.tempFilePath, file.size),
        });
      },
      fail() {
        wx.showToast({ title: '选择图片失败', icon: 'none' });
      },
    });
  },

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

  sendMessage() {
    if (this.data.pendingImage) {
      this.sendImageMsg(this.data.pendingImage, this.data.pendingImageFile);
      this.setData({ pendingImage: '', pendingImageFile: null });
      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) => {
        that.updateMsg(messageId, status);
      }
    });
  },

  sendImageMsg(filePath, fileObj) {
    const that = this;
    const { currentUser, groupId, orderId, isCross, groupName, groupAvatar } = that.data;
    if (!filePath || !currentUser || !groupId) return;

    if (isCross === 0) {
      if (!wx.goEasy || !wx.goEasy.im) {
        wx.showToast({ title: '聊天未连接', icon: 'none' });
        return;
      }
      const avatar = resolveAvatarUrl(currentUser.avatar, app);
      const name = currentUser.name || '用户';
      const localId = `image-${Date.now()}`;
      const imageFile = fileObj || this.buildImageFile(filePath, 0);
      const localMsg = {
        messageId: localId,
        type: 'image',
        timestamp: Date.now(),
        senderId: currentUser.id,
        groupId,
        senderData: { name, avatar },
        payload: { url: filePath },
        status: 'sending',
        formattedTime: formatDate(Date.now()),
        showTime: this.needShow(Date.now()),
      };
      that.setData({ messages: [...that.data.messages, localMsg], scrollToView: 'msg-bottom' });
      const toData = { name: groupName || '订单群聊', avatar: groupAvatar || avatar, isCross: 0 };
      if (orderId) toData.orderId = orderId;
      const imgMsg = wx.goEasy.im.createImageMessage({
        file: imageFile,
        to: { type: wx.GoEasy.IM_SCENE.GROUP, id: groupId, data: toData },
      });
      wx.goEasy.im.sendMessage({
        message: imgMsg,
        onSuccess: (sent) => that.mergeSentMessage(localId, sent),
        onFailed: (error) => {
          console.error('[群聊] 图片发送失败', error);
          that.updateMsg(localId, 'failed');
          wx.showToast({ title: '图片发送失败', icon: 'none' });
        },
      });
      return;
    }

    sendGroupMessage({
      msgData: {
        type: 'image',
        filePath,
        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);
        if (status === 'failed') {
          wx.showToast({ title: '图片发送失败', icon: 'none' });
        }
      }
    });
  },

  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 || 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 }); }
});