import dayjs from "dayjs";
import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";

// module/chats/pages/index/index.ts
interface ScrollIntoViewEvent {
  detail: string;
}
interface HandleEvent {
  detail: { component: 'guide' | 'questionnaire', scroll?: boolean }
}
interface Message extends Omit<HandleEvent['detail'], 'scroll'> {
  id: string;
}

function getScrollcontext(this: any) {
  return this as {
    scroll: WechatMiniprogram.ScrollViewContext,
    timer: number;
  }
}

Component({
  behaviors: [PageContainerBehavior],
  lifetimes: {
    attached() {
      this.setData({
        date: dayjs().format('MM-DD HH:mm:ss'),
      })
      const component = this.data.component as 'guide' | 'questionnaire'
      this.handle({ detail: { component, scroll: true } });
    },
    ready() {
      wx.createSelectorQuery().select('#scrollview').node().exec((res) => {
        getScrollcontext.call(this).scroll = res[0].node;
      })
    }
  },
  properties: {
    component: { type: String, value: 'guide' }
  },
  data: {
    date: '',
    messages: {} as Record<number, Message>,
    lastId: '',
  },
  observers: {
    'messages.**'(messages) {
      const message = Object.values(messages).pop() as Message;
      this.setData({ lastId: message?.id });
    }
  },
  methods: {
    handle(event: HandleEvent) {
      const index = Object.keys(this.data.messages).length;
      this.setData({
        [`messages.${index}`]: <Message>{
          id: `${this.is.replace(/\//g, '_')}-${index}`,
          component: event.detail?.component,
        }
      });
      if (event.detail?.scroll) this.scrollIntoView()
    },
    scrollIntoView(event?: ScrollIntoViewEvent) {
      clearTimeout(getScrollcontext.call(this).timer);
      const id = event?.detail ?? this.data.lastId;
      getScrollcontext.call(this).timer = setTimeout(() => {
        getScrollcontext.call(this).scroll?.scrollIntoView(`#${id}`, { alignment: 'end' });
      }, 300)
    },
  }
})