// pages/aiBot/aiBot.js

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUserInfo: {
      nickName: '',
      avatarUrl: 'https://profile-avatar.csdnimg.cn/8bea3d4b0c56486691de8f54fb649fa4_qq_38870145.jpg!1',
    },
    saveKey: 'aiBot',
    baseCloudUrl: app.remoteConfig.baseCloudUrl,
    password: "U2FsdGVkX1+jfEkF2OXTQ5iIG4mrYc5/TLOiIntyENU=",
    username: "1575057249@qq.com",
    token: '',
    currenTime: '',
    isLoading: false,
    searchOpenAiText: '画一只猫',
    chatObjConfig: {
      option: [
        //   {
        //   question: '',
        //   answer: '',
        //   isEdit: true,
        //   createTime: ''
        // }
      ],
      currentIndex: 0,
      errorMsg: 'openai的服务器异常！'
    },
    layoutConfig: {
      showPasteBtn: false,
      showTopBtn: false,
      introduceText: 'api介绍',
      useText: '使用',
      returnText: '返回介绍',
      sendText: '发送',
      searchText: '请输入关键词进行对话',
      reportText: '复制数据',
      copyText: '复制',
      pasteText: '粘贴',
      upText: "↑",
      downText: "↓",
      errorMsg: 'bot ai服务器异常！',
      emptyText: '欢迎使用aibot',
      storageKey: 'openAiOptionsConfig',
      permissionTitle: '很抱歉您没有权限！',
      permissionContent: '请联系微信号：cse-yma16\r\n 需要1元开通权限\r\n1元可支持100条消息！',
      wxInfoImg: 'https://yongma16.xyz/staticFile/common/img/userInfo.png',
      limitMsgCount: 10,
      confirmText: '添加微信',
      cancelText: '返回'
    },
    aiConfig: {
      avatarUrl: 'https://yongma16.xyz/staticFile/common/img/aiTop.jpg',
      bgUrl: 'https://yongma16.xyz/staticFile/common/img/aiBg.jpg',
      nickName: 'openai',
    },
  },
  getUserToken() {
    const that = this
    wx.showLoading({
      title: 'gen token loading',
    });
    wx.request({
      url: this.data.baseCloudUrl + 'token/gen',
      method: 'POST',
      data: {
        username: this.data.username,
        password: this.data.password
      },
      success: (res => {
        that.setData({
          token: res.data.token
        })
        wx.hideLoading()
      }),
      fail: r => {
        console.log('cloud r', r)
        wx.hideLoading()
      }
    })
  },
  getCurrentTime() {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth()
    const date = now.getDate()
    const hour = now.getHours()
    const minutes = now.getMinutes()
    const second = now.getSeconds()
    const formatNum = (n) => {
      return n > 9 ? n.toString() : '0' + n
    }
    return `${year}-${formatNum(month + 1)}-${formatNum(date)} ${formatNum(hour)}:${formatNum(minutes)}:${formatNum(second)}`
  },
  bindKeyInput(e) {
    console.log('e.detail.value', e.detail.value)
    this.setData({
      searchOpenAiText: e.detail.value
    })
  },
  scrollToBottom() {
    const index = this.data.chatObjConfig.option.length - 1
    this.setData({
      toView: `chat-mode${index}`
    })
  },

  saveStore() {

  },

  search(e) {
    this.scrollToBottom()
    if (this.data.isLoading) {
      wx.showModal({
        cancelColor: 'cancelColor',
        title: '正在响应中，请稍等...'
      })
      return
    }
    if (!this.data.searchOpenAiText) {
      wx.showModal({
        cancelColor: 'cancelColor',
        title: '请输入！'
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      isLoading: true
    })
    const that = this

    return new Promise((resolve, reject) => {
      wx.request({
        url: that.data.baseCloudUrl + '/chat/bot',
        method: 'POST',
        header: {
          Authorization: `bearer ${that.data.token}`
        },
        data: {
          user: 'qwerqwre',
          query: that.data.searchOpenAiText
        },
        success: (res) => {
          console.log(res, 'res')
          const data = res.data.data
          const option = that.data.chatObjConfig.option
          console.log('data', data)
          const choices = data.messages?.[2]
          const answer = choices?.content || that.data.layoutConfig.errorMsg
          option.push({
            question: that.data.searchOpenAiText,
            answer: answer,
            answerMarkdown: app.changeMrkdownText(answer),
            createTime: that.getCurrentTime(),
            isEdit: false,
          })
          const chatObjConfig = {
            option: option
          }

          that.setData({
            isLoading: false,
            searchOpenAiText: '',
            chatObjConfig: chatObjConfig
          })
          wx.hideLoading()
          that.scrollToBottom()
          resolve(res)
          console.log('that.data.chatObjConfig.option', that.data.chatObjConfig.option)
          that.saveStore()
        },
        fail: error => {
          
          that.setData({
            isLoading: false
          })
          wx.hideLoading()
          wx.showModal({
            cancelColor: 'cancelColor',
            title: '网络波动失败...'
          })
        }
      });
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const aiBotConfig = app.wxProgramConfig.aiBotConfig
    console.log('aiBotConfig', aiBotConfig)
    this.setData({
      saveKey: aiBotConfig.saveKey,
      searchOpenAiText: aiBotConfig.searchOpenAiText,
      password: aiBotConfig.cloudPwd || "U2FsdGVkX1+jfEkF2OXTQ5iIG4mrYc5/TLOiIntyENU=",
      username: aiBotConfig.cloudEmail || "1575057249@qq.com",
    })


    this.getUserToken()
    this.setData({
      currenTime: this.getCurrentTime()
    })

    const currentUserInfo = wx.getStorageSync('currentUserInfo')
    if (currentUserInfo && currentUserInfo.nickName) {
      console.log('currentUserInfo', currentUserInfo)
      this.setData({
        currentUserInfo: currentUserInfo
      })
    }

    // 缓存
    const chatObjConfig = wx.getStorageSync(this.data.saveKey)

    if (chatObjConfig) {
      this.setData({
        chatObjConfig: chatObjConfig,
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 缓存

    if (this.data.chatObjConfig) {
      wx.setStorageSync(app.wxProgramConfig.aiBotConfig.saveKey, this.data.chatObjConfig)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})