// pages/main/smartchat/chat.js
var app = getApp();
var baseUrl = app.globalData.baseUrl;
Page({

  /**
   * Page initial data
   */
  data: {
    showModal: false,
    inputValue: "",
    comlist: [],
    com_id: "",
    choosed_index: 0,
    chat_idx:"Toview"+0,
    chatlist: []
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    this.getComList()
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {

  },

  getComList: function() {
    var that = this;
    var Authorization = app.globalData.Authorization;
    wx.request({
      url: baseUrl + 'uaa/v1/tenants',
      data: {
        all: "true"
      },
      header: {
        'content-type': 'application/json',
        "Authorization": Authorization
      },
      success: function(res) {
        if (res && res.data) {
          console.log("res", res)
          if (res.data.items && res.data.items.length > 0) {
            that.setData({
              showModal: true,
              com_id: res.data.items[0].id,
              comlist: res.data.items
            })
          }
        }
      }
    })
  },

  bindKeyInput(e) {
    console.log("bindKeyInput", e)
    this.setData({
      inputValue: e.detail.value
    })
  },

  sendMsg: function() {
    var that = this;
    if (this.data.inputValue == "" || this.data.inputValue.replace(/(^\s*)|(\s*$)/g, "") == "") {
      wx.showToast({
        title: '请输入内容',
      })
      return
    }
    var Authorization = app.globalData.Authorization;
    wx.request({
      url: baseUrl + 'chatbot/v1/chats',
      data: {
        text: that.data.inputValue
      },
      method: "POST",
      header: {
        'content-type': 'application/json',
        "Authorization": Authorization
      },
      success: function(res) {
        if (res && res.data) {
          console.log("res", res)
          var databean = {}
          databean.type = "1"
          databean.text = that.data.inputValue
          that.data.chatlist.push(databean)
          that.data.chatlist.push(res.data)
          that.setData({
            inputValue: "",
            chat_idx: "Toview"+that.data.chatlist.length,
            chatlist: that.data.chatlist
          })
          console.log("chatlist", that.data.chatlist)
          // that.getChatinfo()
          that.bottom()
        }
      }
    })
  },

  refreshToken: function() {
    var that = this;
    wx.request({
      url: baseUrl + 'uaa/v1/auth/tokens',
      data: {
        "grant_type": "refresh_token",
        "refresh_token": app.globalData.refresh_token,
        "scope": "global_access:end_user,tenant:" + that.data.com_id
      },
      method: "POST",
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        console.log("refreshToken", res.data)

        var user = res.data.user;
        var tenant = res.data.tenant;
        if (tenant) {
          app.globalData.tenant_id = tenant.id;
        }
        app.globalData.userInfo = res.data.user;
        app.globalData.wx_open_id = user.wx_open_id;
        app.globalData.Authorization = "Bearer " + res.data.access_token;
        app.globalData.refresh_token = res.data.refresh_token;

        app.configOssUrl();
        that.getChatinfo();
      }
    })
  },

  getChatinfo: function() {
    var that = this;
    var Authorization = app.globalData.Authorization;
    wx.request({
      url: baseUrl + 'chatbot/v1/chats',
      data: {},
      method: "GET",
      header: {
        'content-type': 'application/json',
        "Authorization": Authorization
      },
      success: function(res) {
        if (res && res.data) {
          console.log("getChatinfo", res)
          that.setData({
            chat_idx: "Toview"+res.data.items.length,
            chatlist: res.data.items.reverse()
          })
          that.bottom()
        }
      }
    })
  },


  cancel: function(e) {
    console.log("cancelhandle", e)
    this.setData({
      showModal: false
    })
    wx.navigateBack({
      delta: 1
    })
  },

  confirm: function(e) {
    console.log("confirmhandle", e)
    this.setData({
      showModal: false,
    })
    this.refreshToken();
  },

  bindChange: function(e) {
    console.log("goselect", e)
    var s = e.currentTarget.id
    // var s = e.detail.value
    this.setData({
      com_id: this.data.comlist[s].id,
      choosed_index: s
    })
  },

  //聊天消息始终显示最底端
  bottom: function () {
    var query = wx.createSelectorQuery()
    query.select('#flag').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      wx.pageScrollTo({
        scrollTop: res[0].bottom // #the-id节点的下边界坐标
      })
      res[1].scrollTop // 显示区域的竖直滚动位置
    })
    // var d = SmsListView.ActualHeight;
    // xxx.ScrollToVerticalOffset(d); 
  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function() {

  }
})