// pages/future/future.js
const app = getApp();
const baseUrl = app.remoteConfig.baseUrl;
const baseArticleId = app.wxProgramConfig.apiPageConfig.articleId;
const baseMode = app.wxProgramConfig.apiPageConfig.mode;
Component({
  /**
  * 继承父级样式
  */
  options: {
    addGlobalClass: true,
  },

  // 属性定义
  properties: {
    // 用户信息
    userInfo: {
      type: Object,
      value: () => {
        return {

        }
      },
    }
  },
  /**
   *组件的初始数据
   */
  data: {
    currenTime: "",
    scrollTop: 0,
    mode: baseMode,
    article: {},
    articleId: baseArticleId,
    isShowOenAi: true,
    baseUrl: 'https://yongma16.xyz/api/',
    baseCloudUrl: 'https://yongma16.xyz/cloudApi/',
    baseCloudAddRecordPath: 'openAiRecord/add',
    baseCloudUpdateUserPath: 'userModel/update',
    baseCloudgetUserPath: 'userModel/info',
    baseCloudGetRecordCountPath: 'openAiRecord/count',
    path: 'article/blog/',
    currentUserInfo: {
      nickName: '',
      avatarUrl: ''
    },
    aiConfig: {
      avatarUrl: 'https://yongma16.xyz/staticFile/common/img/aiTop.jpg',
      bgUrl: 'https://yongma16.xyz/staticFile/common/img/aiBg.jpg',
      nickName: 'openai',
    },
    searchOpenAiText: '',
    responseText: '',
    reportText: '',
    // questions，answer，index
    chatObjConfig: {
      option: [
        //   {
        //   question: '',
        //   answer: '',
        //   isEdit: true,
        //   createTime: ''
        // }
      ],
      currentIndex: 0,
      errorMsg: 'openai的服务器异常！'
    },
    layoutConfig: {
      introduceText: 'api介绍',
      useText: '使用',
      returnText: '返回介绍',
      sendText: '发送',
      searchText: '关键词查询',
      reportText: '复制数据',
      copyText: '复制',
      pasteText: '粘贴',
      upText: "↑",
      downText: "↓",
      errorMsg: 'openai的服务器异常！',
      emptyText: '欢迎',
      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:'返回'
    },
    msgCount: 0,
    isVip: false,
    modalVisible: false
  },
  observers: {
    mode: function (newVal, oldVal) {
      // 属性值变化时执行
      console.log(newVal, oldVal, 'change')
      wx.showLoading({
        title: '加载中',
      })
      // 在当前同步流程结束后，下一个时间片执行
      wx.nextTick(() => {
        wx.hideLoading({
          success: (res) => { },
        })
        // 触发父组件事件
        this.triggerEvent('updateBottomNavigation', newVal === 'introduce')
      })

    }
  },
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在 methods 段中定义的方法名
    attached: function () {

      this.getUserInfo()
      this.getRemoteArticle(this.data.articleId)
      this.setData({
        currenTime: this.getCurrentTime()
      })
      const key = app.wxProgramConfig.apiPageConfig.layoutConfig.storageKey
      const openAiOptionsConfig = wx.getStorageSync(key)

      if (openAiOptionsConfig) {
        // if (openAiOptionsConfig.option) {
        //   openAiOptionsConfig.option.forEach(item => {
        //     item.answerMarkdown = app.changeMrkdownText(item.answer)
        //   })
        // }
        const lauoutConfig=app.wxProgramConfig.apiPageConfig.layoutConfig
        this.setData(
          {
            chatObjConfig: openAiOptionsConfig,
            mode: app.wxProgramConfig.apiPageConfig.mode,
            layoutConfig:lauoutConfig,
            isShowOenAi:lauoutConfig.isShowOenAi
          }
        )
        this.refreshOptions()
      }


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

    },
    moved: function () { },
    // 销毁前
    detached: function () {
      const key = app.wxProgramConfig.apiPageConfig.layoutConfig.storageKey
      wx.setStorageSync(key, this.data.chatObjConfig)
      this.getUserReadCount()
    },
  },
  methods: {
    previewImage(e){
      console.log('click png',e)
      const url=e.target.dataset.url
      wx.previewImage({
        current: url, // 当前显示图片的http链接
        urls: [url] // 需要预览的图片http链接列表
      })
    },
    
    // 获取用户
    getUserInfo() {
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const openId = wx.getStorageSync('currentOpenid')
      const wxOpenId = openId && openId.openid
      const params = {
        wx_open_id: wxOpenId
      }
      const thisBack = this
      wx.request({
        url: this.data.baseCloudUrl + this.data.baseCloudgetUserPath,
        headers: headers,
        data: params,
        method: 'POST',
        success: (res => {
          console.log('cloud res userInfo', res)
          if (res && res.data && res.data) {
            console.log('res.data__________',res.data)
            thisBack.setData({
              // 默认十条消息
              msgCount: res.data.data.data[0].send_msg_count || 10,
              isVip: res.data.data.data[0].is_vip || 0
            })
          }
        }),
        fail: r => {
          console.log('cloud r', r)
        }
      })
    },
    // 更新用户使用信息
    updateUserInfo() {
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const openId = wx.getStorageSync('currentOpenid')
      const wxOpenId = openId && openId.openid
      const params = {
        wx_open_id: wxOpenId,
        send_msg_count: this.data.msgCount
      }
      const thisBack = this
      wx.request({
        url: this.data.baseCloudUrl + this.data.baseCloudUpdateUserPath,
        headers: headers,
        data: params,
        method: 'PUT',
        success: (res => {
          console.log('cloud res update', res)
        }),
        fail: r => {
          console.log('cloud r', r)
        }
      })
    },
    // 获取用户使用次数
    getUserReadCount() {
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const openId = wx.getStorageSync('currentOpenid')
      const wxOpenId = openId && openId.openid
      const params = {
        wx_open_id: wxOpenId
      }
      const thisBack = this
      wx.request({
        url: this.data.baseCloudUrl + this.data.baseCloudGetRecordCountPath,
        headers: headers,
        data: params,
        method: 'POST',
        success: (res => {
          console.log('cloud res count', res)
          if (res.data.code === 0) {
            // 0
            thisBack.setData({
              msgCount: 0
            })
          } else {
            thisBack.setData({
              msgCount: res.data.data[0].send_msg_count
            })
          }
          // 更新用户
          thisBack.updateUserInfo()
        }),
        fail: r => {
          console.log('cloud r', r)
        }
      })
    },
    upper(e) {
      console.log('upper e', e)
    },
    lower(e) {
      console.log('lower e', e)
    },
    scroll(e) {
      // console.log('scroll e', e)
    },
    createOpenRecord(params) {
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const openId = wx.getStorageSync('currentOpenid')
      const wxOpenId = openId && openId.openid
      params.wx_open_id = wxOpenId
      const thisBack=this
      wx.request({
        url: this.data.baseCloudUrl + this.data.baseCloudAddRecordPath,
        headers: headers,
        data: params,
        method: 'POST',
        success: (res => {
          console.log('cloud res', res)
          thisBack.getUserReadCount()
        }),
        fail: r => {
          console.log('cloud r', r)
        }
      })
    },
    upBtn() {
      const index = 0
      this.setData({
        toView: `chat-mode${index}`
      })
    },
    downBtn() {
      this.scrollToBottom()
    },
    scrollToBottom() {
      const index = this.data.chatObjConfig.option.length - 1
      this.setData({
        toView: `chat-mode${index}`
      })
    },
    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)}`
    },
    getRemoteArticle: function (id) {
      this.setData({
        isLoading: true
      })
      const baseUrl = this.data.baseUrl
      const path = this.data.path
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const that = this
      const params = {
        id: id
      }
      wx.request({
        url: baseUrl + path,
        headers: headers,
        data: params,
        method: 'POST',
        success: (res) => {
          const data = res.data
          const articleStr = data && data.article && data.article
          const markdownText = app.changeMrkdownText(articleStr);
          that.setData({
            isLoading: false,
            article: markdownText
          })
        }
      });
    },
    changeMode(e) {
      const { mode } = e.currentTarget.dataset
      console.log(mode, 'mode')
      this.setData({
        mode: mode
      })
    },

    refreshOptions() {
      const option = this.data.chatObjConfig.option
      const currentIndex = this.data.chatObjConfig.currentIndex
      while (option && option.length > 100) {
        option.shift()
      }

      const chatObjConfig = {
        option: option,
        currentIndex: currentIndex
      }

      this.setData(
        {
          chatObjConfig: chatObjConfig
        }
      )

    },

    bindKeyInput(e) {
      this.setData({
        searchOpenAiText: e.detail.value
      })
    },
    reportAnswerData() {
      const data = this.data.chatObjConfig.option
      wx.setClipboardData({
        data: JSON.stringify(data)
      })
      console.log(wx.getClipboardData({
        success: (option) => {
          console.log(option)
        },
      }))
    },

    copyBtn(e) {
      console.log('data', e)
      const response = e.target.dataset.response
      wx.setClipboardData({
        data: response
      })
      console.log(wx.getClipboardData({
        success: (option) => {
          console.log(option)
        },
      }))
    },
    pasteBtn(e) {
      const thisBack = this
      wx.getClipboardData({
        success: (option) => {
          console.log('option', option)
          thisBack.setData({
            searchOpenAiText: option.data
          })
        },
      })
    },
    clearBtn() {
      this.setData({
        searchOpenAiText: ''
      })
    },
    modalConfirm() {
      const url=this.data.layoutConfig.wxInfoImg
      wx.previewImage({
        current: url, // 当前显示图片的http链接
        urls: [url] // 需要预览的图片http链接列表
      })
    },
    modalCandel() {
      this.setData({
        modalVisible: false
      })
    },
    search(e) {
      if (this.data.layoutConfig.permissionStatus) {
        const isNotAllow = !(this.data.isVip || this.data.msgCount <= this.data.layoutConfig.limitMsgCount)
        console.log('this.data.isVip', this.data.isVip)
        console.log('this.data.msgCount', this.data.msgCount)
        console.log('isNotAllow', isNotAllow)
        if (isNotAllow) {
          return this.setData({
            modalVisible: true
          })
          // return wx.showModal({
          //   cancelColor: 'cancelColor',
          //   title: this.data.layoutConfig.permissionTitle,
          //   content: this.data.layoutConfig.permissionContent
          // })
        }

      }

      this.scrollToBottom()
      if (!this.data.searchOpenAiText) {
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '请输入！'
        })
        return
      }
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        isLoading: true
      })
      const path = '/common-api/searchOpenAiText/'
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const params = {
        "text": this.data.searchOpenAiText
      }
      const thisBack = this
      return new Promise((resolve, reject) => {
        wx.request({
          url: baseUrl + path,
          headers: headers,
          data: params,
          method: 'GET',
          success: (res) => {
            console.log(res, 'res')
            const data = res.data.data
            const option = thisBack.data.chatObjConfig.option
            const errorMsg = thisBack.data.layoutConfig.errorMsg
            const choices = data.choices
            const answer = choices ? choices.map(choicesItem => { return choicesItem.text }).join('\n') : errorMsg
            option.push({
              question: params.text,
              answer: answer,
              answerMarkdown: app.changeMrkdownText(answer),
              createTime: this.getCurrentTime(),
              isEdit: false,
            })
            const chatObjConfig = {
              option: option
            }

            thisBack.setData(
              {
                isLoading: false,
                searchOpenAiText: '',
                chatObjConfig: chatObjConfig
              }
            )
            wx.hideLoading()
            thisBack.scrollToBottom()
            resolve(res)
            setTimeout(() => {
              thisBack.createOpenRecord({
                wx_name: thisBack.data.currentUserInfo.nickName,
                wx_img: thisBack.data.currentUserInfo.avatarUrl,
                search_text: params.text,
                search_response: answer
              })
            }, 10)
            console.log('thisBack.data.chatObjConfig.option', thisBack.data.chatObjConfig.option)
            thisBack.refreshOptions()
          },
          fail: error => {
            thisBack.setData({
              isLoading: false
            })
            wx.hideLoading()
          }
        });
      })
    }
  }
})
