// pages/wiki/chat/history/index.js
import request from '../../../../utils/request';

Page({
  data: {
    list: [],
    total: 0,
    current: 1,
    pageSize: 15,
    loading: false,
    hasMore: true,
    showClearDialog: false,
  },

  onLoad() {
    this.fetchHistory(true);
  },

  fetchHistory(reset = false) {
    if (this.data.loading) return;
    if (!reset && !this.data.hasMore) return;

    const current = reset ? 1 : this.data.current;
    this.setData({ loading: true });

    request.post('/plant/chat/history', { current, pageSize: this.data.pageSize })
      .then(res => {
        const items = (res.list || []).map(item => ({
          ...item,
          answerPreview: (item.answer || '').substring(0, 80) + ((item.answer || '').length > 80 ? '...' : ''),
        }));
        const total = res.total || 0;

        if (reset) {
          this.setData({
            list: items,
            total,
            current: 2,
            hasMore: items.length < total,
            loading: false,
          });
        } else {
          const old = this.data.list;
          const update = {};
          items.forEach((item, i) => {
            update[`list[${old.length + i}]`] = item;
          });
          update.current = current + 1;
          update.hasMore = (old.length + items.length) < total;
          update.loading = false;
          update.total = total;
          this.setData(update);
        }
      })
      .catch(() => {
        this.setData({ loading: false });
      });
  },

  loadMore() {
    this.fetchHistory(false);
  },

  onTapItem(e) {
    const item = e.currentTarget.dataset.item;
    // Navigate to chat page with prefilled Q&A
    wx.navigateTo({
      url: '/pages/wiki/chat/index?fromHistory=1',
      success(res) {
        res.eventChannel.emit('historyData', {
          question: item.question,
          answer: item.answer,
        });
      },
    });
  },

  onDeleteItem(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '删除记录',
      content: '确定删除这条问答记录吗？',
      success: (res) => {
        if (res.confirm) {
          request.post('/plant/chat/history/delete', { ids: [id] }).then(() => {
            wx.showToast({ title: '已删除', icon: 'success' });
            this.fetchHistory(true);
          });
        }
      },
    });
  },

  onClearAll() {
    this.setData({ showClearDialog: true });
  },

  closeClearDialog() {
    this.setData({ showClearDialog: false });
  },

  doClearAll() {
    this.setData({ showClearDialog: false });
    request.post('/plant/chat/history/clear').then(() => {
      wx.showToast({ title: '已清空', icon: 'success' });
      this.setData({ list: [], total: 0, hasMore: false });
    });
  },

  goToChat() {
    wx.navigateBack();
  },
});
