const app = getApp();
import { formatDate, normalizeChatMessage, getChatImageUrl } from '../../static/lib/utils';
import { showConfirmByScene } from '../../utils/scriptService.js';
import { sendGoEasyImage } from '../../utils/chatImageSend.js';

Page({
  data: {
    toUserId: '', toName: '', toAvatar: '',
    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) {
    if (options.data) {
      try {
        const p = JSON.parse(decodeURIComponent(options.data));
        const toId = p.toUserId || (p.to && p.to.id) || '';
        const toName = p.toName || (p.to && p.to.name) || '聊天';
        const toAvatar = p.toAvatar || (p.to && p.to.avatar) || '';
        this.setData({ toUserId: toId, toName, toAvatar });
      } catch (e) {}
    }
    wx.setNavigationBarTitle({ title: this.data.toName });
    this.initCurrentUser();
  },

  onShow() {
    app.globalData.pageState.isInChatPage = true;
    app.globalData.pageState.currentChatId = this.data.toUserId;
    this.autoConnect();
  },

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

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

    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.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: currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
      },
      onSuccess: () => {
        this.setupAllListeners();
        this.loadHistory(true);
      },
      onFailed: (error) => {
        if (error.code === 408) {
          this.setupAllListeners();
          this.loadHistory(true);
        } else {
          wx.showToast({ title: '连接失败，请重试', icon: 'none' });
        }
      }
    });
  },

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

  clearAllListeners() {
    if (this._msgHandler) { wx.goEasy.im.off(wx.GoEasy.IM_EVENT.PRIVATE_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; }
    if (this._readHandler) { wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_READ, this._readHandler); this._readHandler = null; }
  },

  initCurrentUser() {
    const uid = wx.getStorageSync('uid');
    const role = app.globalData.currentRole || 'normal';
    const prefix = { normal:'Boss', dashou:'Ds', shangjia:'Sj', guanshi:'Gs', zuzhang:'Zz',kaoheguan:'Kh' }[role] || 'Boss';
    this.setData({ currentUser: {
      id: prefix + uid,
      name: app.globalData.currentUser?.name || `用户${uid}`,
      avatar: this.fixAvatar(wx.getStorageSync('touxiang'))
    }});
  },
  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 { toUserId, lastTimestamp } = this.data;
      const ts = refresh ? null : lastTimestamp;
      wx.goEasy.im.history({
        type: wx.GoEasy.IM_SCENE.PRIVATE, id: toUserId, lastTimestamp: ts, limit: 20,
        onSuccess: (res) => {
          let list = res.content || [];
          list.sort((a, b) => a.timestamp - b.timestamp);
          list.forEach((m, idx) => {
            normalizeChatMessage(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.senderId === this.data.currentUser.id) {
              m.senderData = { name: this.data.currentUser.name, avatar: this.data.currentUser.avatar };
            } else {
              m.senderData = { name: this.data.toName, avatar: this.data.toAvatar };
            }
          });
          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.PRIVATE_MESSAGE_RECEIVED, this._msgHandler);
    this._msgHandler = (msg) => {
      if (msg.receiverId !== this.data.currentUser.id && msg.senderId !== this.data.toUserId) return;
      normalizeChatMessage(msg);
      msg.formattedTime = formatDate(msg.timestamp);
      if (msg.senderId === this.data.currentUser.id) {
        msg.senderData = { name: this.data.currentUser.name, avatar: this.data.currentUser.avatar };
      } else {
        msg.senderData = { name: this.data.toName, avatar: this.data.toAvatar };
      }
      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.markPrivateMessageAsRead();
    };
    wx.goEasy.im.on(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this._msgHandler);
  },

  markPrivateMessageAsRead() {
    if (!this.data.toUserId) return;
    wx.goEasy.im.markMessageAsRead({
      type: wx.GoEasy.IM_SCENE.PRIVATE,
      id: this.data.toUserId
    });
  },

  listenRead() {
    if (this._readHandler) wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_READ, this._readHandler);
    this._readHandler = (msgs) => {
      if (!msgs || !msgs.length) return;
      const ids = new Set(msgs.map(m => m.messageId));
      const newMsgs = this.data.messages.map(m => ids.has(m.messageId) ? { ...m, read: true } : m);
      this.setData({ messages: newMsgs });
    };
    wx.goEasy.im.on(wx.GoEasy.IM_EVENT.MESSAGE_READ, this._readHandler);
  },

  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;
    const onPick = (file) => {
      if (!file) return;
      const path = typeof file === 'string' ? file : (file.tempFilePath || file.path);
      if (!path) return;
      that.setData({
        pendingImage: path,
        pendingImageFile: typeof file === 'string' ? { tempFilePath: path, path } : file,
        showPlusPanel: false,
      });
    };
    if (wx.chooseMedia) {
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
        success(res) { onPick(res.tempFiles[0]); }
      });
      return;
    }
    wx.chooseImage({
      count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'],
      success(res) {
        const p = res.tempFilePaths[0];
        onPick(res.tempFiles && res.tempFiles[0] || { tempFilePath: p, path: p });
      }
    });
  },
  clearPendingImage() { this.setData({ pendingImage: '', pendingImageFile: null }); },
  sendMessage() {
    if (this.data.pendingImage) {
      const file = this.data.pendingImageFile || this.data.pendingImage;
      showConfirmByScene('chat_image_confirm', () => {
        this.sendImageMsg(file);
        this.setData({ pendingImage: '', pendingImageFile: null });
      });
      return;
    }
    const text = this.data.inputText.trim();
    if (!text) return;
    this.sendText(text);
    this.setData({ inputText: '' });
  },

  sendText(text) {
    const { currentUser, toUserId } = this.data;
    if (!toUserId || !currentUser) return;
    const id = 'local-'+Date.now();
    const local = {
      messageId:id, type:'text', timestamp:Date.now(),
      senderId:currentUser.id, receiverId:toUserId,
      senderData: { name: currentUser.name, avatar: currentUser.avatar },
      payload:{text}, status:'sending', read:false,
      formattedTime:formatDate(Date.now()), showTime:this.needShow(Date.now())
    };
    this.setData({ messages: [...this.data.messages, local], scrollToView: 'msg-bottom' });
    const msg = wx.goEasy.im.createTextMessage({
      text,
      to:{ type:wx.GoEasy.IM_SCENE.PRIVATE, id:toUserId, data:{ avatar:currentUser.avatar, name:currentUser.name } }
    });
    wx.goEasy.im.sendMessage({
      message:msg,
      onSuccess:() => this.updateMsg(id, 'success'),
      onFailed:() => this.updateMsg(id, 'failed')
    });
  },
  sendImageMsg(file) {
    const { currentUser, toUserId } = this.data;
    if (!toUserId || !currentUser) return;
    const preview = typeof file === 'string' ? file : (file.tempFilePath || file.path);
    const id = 'img-'+Date.now();
    const local = {
      messageId:id, type:'image', timestamp:Date.now(),
      senderId:currentUser.id, receiverId:toUserId,
      senderData: { name: currentUser.name, avatar: currentUser.avatar },
      payload:{url:preview}, imageUrl:preview, status:'sending', read:false,
      formattedTime:formatDate(Date.now()), showTime:this.needShow(Date.now())
    };
    this.setData({ messages: [...this.data.messages, local], scrollToView: 'msg-bottom' });
    const to = { type: wx.GoEasy.IM_SCENE.PRIVATE, id: toUserId, data: { avatar: currentUser.avatar, name: currentUser.name } };
    sendGoEasyImage({
      file,
      to,
      onSuccess: (sentMsg) => this.onImageSendSuccess(id, sentMsg, preview),
      onFailed: () => this.updateMsg(id, 'failed'),
    });
  },
  onImageSendSuccess(localId, sentMsg, localFile) {
    const normalized = normalizeChatMessage(sentMsg || {});
    const url = getChatImageUrl(normalized) || localFile;
    this.setData({
      messages: this.data.messages.map(m => {
        if (m.messageId !== localId) return m;
        return {
          ...m,
          ...normalized,
          messageId: normalized.messageId || m.messageId,
          payload: { ...(m.payload || {}), url },
          imageUrl: url,
          status: 'success'
        };
      })
    });
  },
  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)) {
      itemList.push('撤回');
    }
    wx.showActionSheet({
      itemList,
      success: (res) => {
        if (itemList[res.tapIndex] === '复制') { if (msg.type === 'text') wx.setClipboardData({ data: msg.payload.text }); }
        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) {
          const newMsgs = this.data.messages.map(m => {
            if (m.messageId === msg.messageId) return { ...m, type:'text', payload:{text:'你撤回了一条消息'}, recalled:true };
            return m;
          });
          this.setData({ messages: newMsgs });
          wx.goEasy.im.recallMessage({ messages: [msg], onFailed:()=>{} });
        }
      }
    });
  },

  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    if (!url) return;
    const urls = this.data.messages
      .filter(m => m.type === 'image')
      .map(m => m.imageUrl || getChatImageUrl(m))
      .filter(Boolean);
    wx.previewImage({ urls: urls.length ? urls : [url], current: 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 text = `[订单]${order.dingdan_id}\n${order.jieshao}\n¥${order.jine}`;
    this.setData({ inputText: text });
    this.sendMessage();
  },

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