import { openCustomerServiceChat, resolveKefuIconUrl } from '../../utils/kefu-nav.js';

const CS_HOUR_START = 8;
const CS_HOUR_END = 23;

function getCsOnlineStatus() {
  const hour = new Date().getHours();
  const online = hour >= CS_HOUR_START && hour < CS_HOUR_END;
  return {
    csOnline: online,
    csHoursText: '8:00-23:00',
    csStatusText: online ? '在线' : '在线时间',
  };
}

Component({
  properties: {
    bottom: { type: String, value: '200rpx' },
  },

  data: {
    mode: 'full',
    sessionHidden: false,
    csUnread: 0,
    floatY: 520,
    iconUrl: '',
    csOnline: false,
    csHoursText: '8:00-23:00',
    csStatusText: '在线时间',
  },

  lifetimes: {
    attached() {
      const app = getApp();
      this._syncIcon();
      this._syncFromGlobal();
      this._initFloatY();
      this._convHandler = () => this.syncCsUnread();
      this._configHandler = () => this._syncIcon();
      if (app.on) {
        app.on('conversationsUpdated', this._convHandler);
        app.on('unreadCountChanged', this._convHandler);
        app.on('configApplied', this._configHandler);
      }
      this.syncCsUnread();
      this._syncOnlineStatus();
    },
    detached() {
      const app = getApp();
      if (app.off) {
        if (this._convHandler) {
          app.off('conversationsUpdated', this._convHandler);
          app.off('unreadCountChanged', this._convHandler);
        }
        if (this._configHandler) {
          app.off('configApplied', this._configHandler);
        }
      }
    },
  },

  pageLifetimes: {
    show() {
      this._syncIcon();
      this._syncFromGlobal();
      this.syncCsUnread();
      this._syncOnlineStatus();
    },
  },

  methods: {
    _syncOnlineStatus() {
      this.setData(getCsOnlineStatus());
    },
    _syncIcon() {
      const url = resolveKefuIconUrl(getApp());
      if (url && url !== this.data.iconUrl) {
        this.setData({ iconUrl: url });
      }
    },

    _initFloatY() {
      const app = getApp();
      if (app.globalData.kefuFloatY != null) {
        this.setData({ floatY: app.globalData.kefuFloatY });
        return;
      }
      try {
        const sys = wx.getSystemInfoSync();
        const defaultY = Math.floor((sys.windowHeight || 600) * 0.55);
        this.setData({ floatY: defaultY });
      } catch (e) {
        this.setData({ floatY: 520 });
      }
    },

    _syncFromGlobal() {
      const app = getApp();
      const sessionHidden = !!app.globalData.kefuFloatSessionHidden;
      const mode = app.globalData.kefuFloatMode || 'full';
      this.setData({ sessionHidden, mode });
    },

    onFloatMove(e) {
      const y = e.detail && e.detail.y;
      if (y == null) return;
      const app = getApp();
      app.globalData.kefuFloatY = y;
    },

    syncCsUnread() {
      if (this.data.sessionHidden) return;
      if (!wx.goEasy?.im?.latestConversations) return;
      wx.goEasy.im.latestConversations({
        onSuccess: (res) => {
          const list = res.content?.conversations || res.conversations || [];
          let unread = 0;
          list.forEach((c) => {
            if (c.type === 'cs' || c.teamId === 'support_team') {
              unread += c.unread || 0;
            }
          });
          if (unread !== this.data.csUnread) {
            this.setData({ csUnread: unread });
          }
        },
        onFailed: () => {},
      });
    },

    onIconError() {
      this._syncIcon();
    },

    onContact() {
      openCustomerServiceChat();
    },

    onHideTap(e) {
      if (e && e.stopPropagation) e.stopPropagation();
      const app = getApp();
      app.globalData.kefuFloatMode = 'mini';
      this.setData({ mode: 'mini' });
    },

    onExpand(e) {
      if (e && e.stopPropagation) e.stopPropagation();
      const app = getApp();
      app.globalData.kefuFloatMode = 'full';
      this.setData({ mode: 'full' });
    },

    onSessionDismiss(e) {
      if (e && e.stopPropagation) e.stopPropagation();
      wx.showModal({
        title: '隐藏联系客服',
        content: '本次使用期间不再显示此按钮。清空后台重新进入小程序后会再次出现。',
        confirmText: '确定隐藏',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            const app = getApp();
            app.globalData.kefuFloatSessionHidden = true;
            this.setData({ sessionHidden: true });
          }
        },
      });
    },
  },
});
