// pages/contact/contact.js
const app = getApp();
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;

/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';

  msgList = [{
    "role": "system",
    "content": "你是一个垃圾分类助手"
  }]
  that.setData({
    msgList,
    inputVal
  })
}

/**
 * 计算msg总高度
 */
// function calScrollHeight(that, keyHeight) {
//   var query = wx.createSelectorQuery();
//   query.select('.scrollMsg').boundingClientRect(function(rect) {
//   }).exec();
// }

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: '100vh',
    inputBottom: 0,
    image:'https://bpic.588ku.com/element_pic/20/07/01/4347f2eea4eebb9a4708ea61636893a7.jpg!/fw/253/quality/90/unsharp/true/compress/true'
    // image: 'https://tdesign.gtimg.com/mobile/demos/avatar1.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

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

  },

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

  },

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

  },

  /**
   * 获取聚焦
   */
  focus: function (e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: keyHeight + 'px'
    })
    //计算msg高度
    // calScrollHeight(this, keyHeight);

  },

  //失去聚焦(软键盘消失)
  blur: function (e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function (e) {
    var _that=this
    msgList.push({
      role: 'user',
      contentType: 'text',
      content: e.detail.value
    })
    inputVal = '';
    wx.request({
      url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', // 上传接口地址
      method: 'POST',
      data: {
        model: "qwen-plus",
        messages: msgList
      },
      header: {
        'Authorization': 'Bearer sk-3cd83de9f74b45b9b7da7c7507310222',
        'content-type': 'application/json' // 设置请求头为json格式
      },
      success(res) {
        const data = res.data;
        console.log(res)
        // 根据实际返回的数据格式处理返回结果

        msgList.push(
          data.choices[0].message
        )
        _that.setData({
          msgList,
          inputVal
        })
      },
      fail(err) {
        console.error('上传失败：', err);
        wx.showToast({
          title: '上传失败，请重试！',
          icon: 'none',
          duration: 2000
        });
      }
    });
    this.setData({
      msgList,
      inputVal
    });


  },

  /**
   * 退回上一页
   */
  toBackClick: function () {
    wx.navigateBack({})
  }

})