const { request } = require('../../utils/request')

Page({
  data: {
    question: '',
    answer: '',
    provider: 'fastgpt',
    mode: 'auto',
    hits: [],
    adviceType: 'general',
    loading: false,
    providerOptions: ['fastgpt', 'dify', 'local'],
    modeOptions: ['auto', 'local', 'llm'],
    adviceOptions: ['general', 'gain_muscle', 'lose_fat', 'keto', 'nutritionist']
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [field]: e.detail.value })
  },

  onPickerChange(e) {
    const field = e.currentTarget.dataset.field
    const options = this.data[`${field}Options`]
    this.setData({ [field]: options[e.detail.value] })
  },

  async askQuestion() {
    if (!this.data.question.trim()) {
      wx.showToast({ title: '请输入问题', icon: 'none' })
      return
    }
    this.setData({ loading: true })

    try {
      const provider = this.data.provider === 'local' ? 'fastgpt' : this.data.provider
      const mode = this.data.provider === 'local' ? 'local' : this.data.mode
      const data = await request({
        url: '/qa/ask',
        method: 'POST',
        data: {
          question: this.data.question,
          provider,
          mode
        }
      })
      this.setData({ answer: data.answer, hits: data.items || [] })
    } catch (err) {
      // handled
    } finally {
      this.setData({ loading: false })
    }
  },

  async getAdvice() {
    this.setData({ loading: true })
    try {
      const provider = this.data.provider === 'local' ? 'dify' : this.data.provider
      const data = await request({
        url: '/qa/advice',
        method: 'POST',
        data: {
          advice_type: this.data.adviceType,
          question: this.data.question || '请给我本周饮食建议',
          provider
        }
      })
      this.setData({ answer: data.answer, hits: data.knowledge_hits || [] })
    } catch (err) {
      // handled
    } finally {
      this.setData({ loading: false })
    }
  }
})
