const app = getApp()
import request from '../../utils/request'
import { scrollToID, keyWordsEnum } from '../../utils/util'
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()
const record = wx.getRecorderManager()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    chatList: [],
    saysContentLength: 50,
    message: "",
    isResponing: false,
    isLoading: false,
    chatOver: false,
    messageFlag: true,
    istouching: false,
    isHolding: false,
    scrollTop: 0,
    timer: null,
    clearTimer: null,
    interval: null,
    promotContentCount: 0,
    completionContentCount: 0,
    noticeText: '',
    inputMode: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.socketLink()
    this.chatLimit()
    this.setData({
      promotContentCount: wx.getStorageSync('promotContentCount'),
      completionContentCount: wx.getStorageSync('completionContentCount'),
      noticeText: app.globalData.noticeText ? app.globalData.noticeText : ''
    })
  },

  // 敏感词检测
  msgSecCheck(message) {
    const that = this
    return new Promise((resolve, reject) => {
      const data = {
        appId: 'wxedb9fb309728a9f1',
        message
      }
      request.post({
        url: '/api/chat/msgSecCheck', data
      }).then(res => {
        console.log(res, 'msgSecCheck');
        if (res.code == 200) {
          resolve()
        } else {
          reject()
          wx.showToast({
            title: `文本涉及敏感词！`,
          })
        }
      }).catch(err => {
        console.log(err, 'err');
        reject()
        wx.showToast({
          title: `文本涉及敏感词！`,
          icon: 'error'
        })
      })
    })
  },

  // 跳转至联系我们页面
  goToProductDetail() {
    wx.navigateTo({
      url: '/pages/ContactUs/ContactUs',
    })
  },

  chatLimit() {
    request.get({
      url: '/api/chat/limit',
    }).then(res => {
      console.log(res, 'chatLimit');
      this.setData({
        saysContentLength: res.data.saysContentLength * 1
      })
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  input(e) {
    const msg = e.detail.value
    const limit = this.data.saysContentLength
    if (msg.length > limit) {
      wx.showToast({
        title: `单条最长可输入字数为${limit}字！`,
        icon: 'none'
      })
    }
    this.setData({
      message: msg
    })
  },

  preMessageSend(message) {
    const promotContentCount = this.data.promotContentCount
    const completionContentCount = this.data.completionContentCount
    let chatList = JSON.parse(JSON.stringify(this.data.chatList))
    chatList.shift()
    console.log(chatList, 'chatListIII');
    const len = chatList.length
    const msg = []

    if (len == 0) {
      const obj = {
        role: 'user',
        content: message
      }
      msg.push(obj)
    } else if (len <= promotContentCount + completionContentCount) {
      let tempObj = null
      chatList.forEach(item => {
        tempObj = {
          role: 'user',
          content: item.message
        }
        msg.push(tempObj)
      })
    } else if (len > promotContentCount + completionContentCount) {
      const index = promotContentCount + completionContentCount
      let tempObj = null
      const arr = chatList.slice(-1 * index)
      arr.forEach(item => {
        tempObj = {
          role: 'user',
          content: item.message
        }
        msg.push(tempObj)
      })
    }

    console.log(JSON.stringify(msg), 'msg');
    this.socketSend(JSON.stringify(msg))
  },

  // 向socket连接端发送数据
  send() {
    if (!this.data.message) return

    this.msgSecCheck(this.data.message)
      .then(() => {
        console.log('非敏感词，放行');
        // 当socket连接被关闭时，重新连接socket
        if (this.data.reLoadSocket) {
          this.socketLink(this.data.message)
        }

        const data = {
          message: this.data.message,
          id: 1 // 带id为用户发送的讯息，不带则为服务器返回的讯息
        }

        const arr = this.data.chatList
        arr.push(data)

        // 非重载状态下向服务器发送讯息
        if (!this.data.reLoadSocket) {
          this.setData({
            isLoading: true
          })
          this.preMessageSend(this.data.message)
        }

        this.setData({
          chatList: arr,
          message: '',
          messageFlag: true
        })
        console.log(this.data.chatList, 'chatList');
      }).catch((err) => {
        console.log('触发敏感词！', err);
      })
  },

  // 打招呼信息
  sayHello(message) {
    const messageArr = message.split('，')
    const len = messageArr.length
    let msg = ''
    let i = 0;
    let timer = setInterval(() => {
      const arr = this.data.chatList
      arr.splice(arr.length - 1, '1')
      msg += i + 1 == len ? messageArr[i] : messageArr[i] + '，';
      const data = {
        message: msg
      }
      arr.push(data)
      this.setData({
        chatList: arr,
      })
      if (i + 1 == len) {
        clearInterval(timer);
      } else {
        i++;
      }
    }, 150);
  },

  // 插入的信息，高频触发，每一次返回插入一条信息
  messageIn(message) {
    // 第一次触发
    const tempArr = this.data.chatList
    if (this.data.messageFlag) {
      const data = { message }
      tempArr.push(data)
      this.setData({
        chatList: tempArr,
        messageFlag: false
      })
    } else {
      tempArr[tempArr.length - 1].message += message
      this.setData({
        chatList: tempArr
      })
    }
  },

  // 进行socket连接
  socketLink(waitingMessage) {
    console.log('Link Start!');
    const that = this
    wx.connectSocket({
      url: 'wss://gptsocket.malls.iformall.com:8010',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log('Link Successed!');
        console.log(res)
        if (!waitingMessage) {
          that.sayHello('Hello，我是小闲聊，你可以和我聊天，😘😘😘')
        }

        if (waitingMessage) {
          console.log('reLoadSocket,waitingMessage!');
          setTimeout(() => {
            that.preMessageSend(waitingMessage)
          }, 2000);
          that.setData({
            reLoadSocket: false,
            isLoading: true
          })
        }

        wx.onSocketClose(() => {
          console.log('Link Over!');
          that.scrollToBottom('scrollSingel')
          that.setData({
            reLoadSocket: true
          })
        })
      },
      fail: function (err) {
        console.log('Link fialed!');
        console.log(err)
      },
      complete: function (info) {
        // console.log(info)
      }
    })
  },

  socketSend(data) {
    const that = this
    const msgArr = []
    clearInterval(that.data.interval)
    wx.sendSocketMessage({
      data: data,
      success: function (res) {
        // 返回成功后清除轮询
        clearInterval(that.data.interval)
        console.log(res)
        wx.onSocketMessage(data => {
          const msgBack = data.data
          console.log(msgBack);
          if (msgBack == '___talk_end___') {
            that.setData({
              isResponing: false,
              isLoading: false
            })
            // setTimeout(() => {
            //   console.log('10s');
            // }, 10000);
          } else {
            that.messageIn(msgBack)
            that.scrollToBottom('scrollSingel')
            that.setData({
              isResponing: true
            })
          }
        })
      },
      fail: function (err) {
        console.log(err)
        // 若socket连接尚未建立，则2s发一次轮询
        that.setData({
          interval: setInterval(() => {
            that.socketSend(data)
          }, 2000)
        })
      },
      complete: function (info) {
        console.log(info)
      }
    })
  },

  /* 滚动到选定dom的底部 */
  scrollToBottom(id) {
    const that = this
    wx.createSelectorQuery().select('#' + id).boundingClientRect(function (rect) {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      that.setData({
        scrollTop: rect.height - that.data.scrollTop
      });
    }).exec();
  },

  // 2023-4-28，由于给text标签添加了user-select属性，弃用自定义复制按钮，以下注释代码即为
  // 点击开始，在触发messageTouchEnd之前即为长按
  messageTouchStart(e) {
    // const timer = this.data.timer
    // const clearTimer = this.data.clearTimer
    // clearTimeout(timer)
    // clearTimeout(clearTimer)
    // this.setData({
    //   timer: null,
    //   clearTimer: null,
    // })

    this.setData({
      istouching: true,
      istouchingIndex: e.currentTarget.dataset.index,
      // timer: setTimeout(() => {
      //   this.setData({
      //     isHolding: true
      //   })
      // }, 200)
    })
  },

  // 点击结束
  messageTouchEnd(e) {
    this.setData({
      istouching: false,
      istouchingIndex: e.currentTarget.dataset.index,
      // clearTimer: setTimeout(() => {
      //   this.setData({
      //     isHolding: false
      //   })
      // }, 4000)
    })
    // const timer = this.data.timer
    // clearTimeout(timer)
  },

  // 复制信息
  // copyMessage(e) {
  //   if (!this.data.isHolding) return
  //   const message = e.currentTarget.dataset.message
  //   this.setData({
  //     isHolding: false
  //   })
  //   const timer = this.data.timer
  //   clearTimeout(timer)

  //   this.setClipboardData(message)
  // },

  // 监听聊天区域点击事件
  contentWatch(e) {
    console.log(e);
  },

  /* 复制内容到剪贴板*/
  setClipboardData(data) {
    wx.setClipboardData({
      data,
      success(res) {
        // console.log(res)
      }
    })
  },

  voiceMode() {
    manager.start({ duration: 100, lang: "zh_CN" })
    manager.onStop(res => {
      console.log('已获取麦克风调用权限！');
    })
    const inputMode = this.data.inputMode
    this.setData({
      inputMode: !inputMode
    })
  },

  speakStart() {
    console.log('按下');
    wx.showLoading({
      title: '请说话'
    })
    manager.start({ duration: 30000, lang: "zh_CN" })
    manager.onStart = function (res) {
      console.log("成功开始录音识别", res)
    }
  },

  speakEnd() {
    console.log('抬起');
    wx.hideLoading()
    // wx.showLoading({
    //   title: '正在识别',
    //   mask: true
    // })
    manager.stop()
  },

  initVoiceManager() {
    manager.onRecognize = function (res) {
      console.log("current result", res.result)
    }

    manager.onStop = function (res) {
      console.log(res.tempFilePath, 'res');
      console.log(res.result, 'result');
      wx.hideLoading()
    }

    manager.onError = function (res) {
      console.error("error msg", res.msg)
      wx.showToast({
        title: '太短了，请描述长一点',
        icon: 'none'
      })
    }
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initVoiceManager()
  },

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

  },

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

  },

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

  },

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

  },

  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '小闲聊'
        })
      }, 500)
    })
    return {
      title: '小闲聊',
      promise
    }
  },
  onShareTimeline() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '小闲聊'
        })
      }, 500)
    })
    return {
      title: '小闲聊',
      promise
    }
  }
})