Page({
  data: {
    message: '',
    chatMessages: [],
    typeList: ['primary'],
    scrollToView: '', // 用于 scroll-into-view 的 id
    scrollTop: 0,    // 用于 scroll-top 的值
  },

  onLoad() {
    // 在页面加载时，添加AI机器人的初始消息
    let botAvatar = 'https://bpic.588ku.com/element_origin_min_pic/19/04/27/578456f43714d36fffc68ecc6f8c46e5.jpg'; // 机器人头像URL
    let initialMessage = { type: 'bot', content: '请问有什么可以帮到您？', avatar: botAvatar };

    this.setData({
      chatMessages: [initialMessage]
    });
    my.getStorage({
      key: 'userInfo',
      success: (res) => {
        const userInfo = res.data;
        this.setData({
          id: userInfo.id, // 获取 id
          avatarUrl:userInfo.avatarUrl
        });
      }
    });
  },

  onMessageInput(e) {
    this.setData({
      message: e.detail.value
    });
  },
  
  onKeyUp(e) { 
      this.onSubmit();
  },

  onSubmit() {
    let that = this;
    let currentMessage = this.data.message;
    let userAvatar = this.data.avatarUrl; // 用户头像URL
    let botAvatar = 'https://bpic.588ku.com/element_origin_min_pic/19/04/27/578456f43714d36fffc68ecc6f8c46e5.jpg'; // 机器人头像URL

    if (!currentMessage.trim()) return; // 防止发送空消息

    // 添加用户消息到 chatMessages
    this.setData({
      chatMessages: [...this.data.chatMessages, { type: 'user', content: currentMessage, avatar: userAvatar }],
      message: '',
      scrollToView: `user-${Date.now()}` // 滚动到用户消息
    });

    // 添加“加载中”消息
    let loadingMessage = { type: 'bot', content: '加载中...', avatar: botAvatar, id: `loading-${Date.now()}` };
    this.setData({
      chatMessages: [...this.data.chatMessages, loadingMessage]
    });

    // 模拟API请求获取机器人回复
    my.getStorage({
      key: 'openId',
      success: (res) => {
        my.request({
          url: 'http://localhost:5657/chat',
          method: 'POST',
          data: {
            openId: res.data.openId,
            requestBody: currentMessage
          },
          headers: {
            'content-type': 'application/json'
          },
          success: function (res) {
            let count = res.data.count;  // 假设后端返回的 count 字段
            let responseMessage = count >= 10
              ? { type: 'bot', content: '免费次数已用完', avatar: botAvatar, id: `response-${Date.now()}` }
              : { type: 'bot', content: res.data.data, avatar: botAvatar, id: `response-${Date.now()}` };

            // 替换“加载中”消息为机器人回复
            that.setData({
              chatMessages: that.data.chatMessages.map(msg =>
                msg.id === loadingMessage.id ? responseMessage : msg
              ),
              scrollToView: responseMessage.id // 滚动到最新回复
            });
          },
          fail: function (error) {
            console.error('fail: ', JSON.stringify(error));
            // 如果请求失败，替换“加载中”消息为错误消息
            that.setData({
              chatMessages: that.data.chatMessages.map(msg =>
                msg.id === loadingMessage.id ? { type: 'bot', content: '请求失败，请稍后再试', avatar: botAvatar, id: `response-${Date.now()}` } : msg
              ),
              scrollToView: `response-${Date.now()}` // 滚动到最新错误消息
            });
          }
        });
      }
    });
  },

  handleTapLink() {
    my.alert({
      title: '提示', // 可选，弹窗标题
      content: '别点了，再点也是10次', // 主要内容
      buttonText: '确定', // 可选，按钮文字
    });
  },
});
