// packageA/chattingRecords/chattingRecords.js
const Service = require('../../utils/service.js');
const Util = require('../../utils/util.js');
const audioContext = wx.createInnerAudioContext();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    errorToptips: '',
    scrollHeight: "100%", //聊天内容显示
    keyHeight: 0,
    scrollTop: 0,
    iPhoneX: false,
    doctorunitid: '',
    t_unionid: '',
    orderId: '',
    graded: 0,
    cursor: 190,
    conversationID: '', //会话ID
    messageList: [], //会话消息列表
    audioSave: '', //当前播放音频路径
    scrollloading: false, //是否正在拉取历史消息
    avatarUrl: '',
    page:1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var data = wx.getStorageSync('data');
    that.setData({
      id: options.id,
      doctorimage: options.doctorimage,
      avatarUrl: data.headimgurl,
    })
    that.checkModal();
    that.getChatLog(1);
    that.scrollToBottom();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  //判断是否是iPhonex
  checkModal() {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        // iPhone X   iPhone XR  iPhone XS Max     iPhone XS
        if (/^iPhone X.*/i.test(res.model) || /^iPhone XR.*/i.test(res.model) || /^iPhone XS.*/i.test(res.model) || /^iPhone 11*/i.test(res.model) || /^iPhone 11 Pro Max*/i.test(res.model)) {
          that.setData({
            padding_bottom: 30,
            iPhoneX: true,
          })
        } else {
          that.setData({
            padding_bottom: 0,
            iPhoneX: false,
          })
        }
      }
    });
  },
  /**聊天记录请求
   * page	         int	    页码
   * id     	     string		服务id
   */
  getChatLog(page) {
    var that = this;
    var data = {};
    data.page = page;
    data.id = that.data.id;
    Service.getChatMsgLog(data).then((res) => {
      if (res.code == 1) {
        if(res.data.length<=0){
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 2500
          })
        }else{
          let msgList = Util.deepClone(res.data);
          let messageList = that.messageListParser(msgList);
          let list = that.data.messageList;
          that.setData({
            messageList: messageList.concat(list),
            page: that.data.page + 1
          })
        }
      }
    })
  },
  /**
   * 监听scroll-view下拉触顶动作
   */
  scrollPullDownRefresh: Util.debouce(function (e) {
    let that = this;
    console.log("%c监听scroll-view下拉触顶动作", "color:#04BE02", that.data.scrollloading)
    if (that.data.scrollloading) return;
    that.setData({
      scrollloading: true
    })
    that.getChatLog(that.data.page)
    //已经拉完所有消息
    setTimeout(() => {
      that.setData({
        scrollloading: false
      })
    }, 1000);
  }, 1000, true),
  //查看报告
  goReport(e) {
    let that = this
    let src = e.currentTarget.dataset.src;
    let is_type = e.currentTarget.dataset.istype;
    if (is_type == 0) {
      wx.showModal({
        title: '提示',
        content: '请联系咨询师进行下一步诊断！',
        showCancel: false
      }, 2000)
      return;
    }

    src = src.split(',');
    wx.navigateTo({
      url: '/pages/webview/webview?id=' + src[0] + '&lbname=' + src[1] + '&share=0&t_openid=0',
      success: function () {
        setTimeout(function () {
          that.setData({
            payInfo: true
          })
        }, 500)
      }
    })
  },
  /**
   * 图片预览
   */
  previewImage(e) {
    var src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
      current: src
    })
  },
  lookReport: Util.debouce(function (e) {
    let that = this;
    let src = e.currentTarget.dataset.src;
    let is_type = e.currentTarget.dataset.istype;
    if (is_type == 0) {}
    src = src.split(',');
    wx.navigateTo({
      url: '/packageB/webview/webview?id=' + src[0] + '&lbname=' + src[1] + '&share=0&t_openid=0',
    })
  }, 1000, true),
  scroll: function () {},
  /**
   * 解析自定义消息
   */
  messageListParser(messages) {
    let lastShowTimeStamp = 0;
    let data = wx.getStorageSync('data')
    let messageList = messages.map(item => {
      item.msg_content = JSON.parse(item.msg_content)
      if (item.msg_type == 'Prescription' || item.msg_type == 'UserDrug' || item.msg_type == 'Checkup' || item.msg_type == 'report') {
        item.msg_content.content = JSON.parse(item.msg_content.content);
      }
      if (Number(item.msg_timestamp - lastShowTimeStamp) >= 300) {
        lastShowTimeStamp = item.msg_timestamp;
        item.msg_timestamp = Util.timestampIM(item.msg_timestamp)
      } else {
        item.msg_timestamp = '';
      }
      item.flow = item.from_account != data.account_number ? 'in' : 'out';
      return item;
    })
    return messageList;
  },
  /**
   * 滚动页面到底部
   */
  scrollToBottom: Util.debouce(function () {
    this.setData({
      scrollTop: 99999
    })
  }, 1000, false),
  /**复制 */
  copy(e) {
    let cope = e.currentTarget.dataset.c;
    wx.setClipboardData({
      data: cope,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  /**
   * 播放语音消息
   */
  openAudio(e) {
    let that = this;
    wx.stopVoice();
    audioContext.src = e.currentTarget.dataset.voice;
    let uuid = e.currentTarget.dataset.voice;
    if (uuid == that.data.audioSave) {
      audioContext.stop();
      //初始化
      that.setData({
        audioSave: ''
      })
    } else {
      //不是同一个语音 直接播放其它，将此次语音记录
      audioContext.play();
      that.setData({
        audioSave: uuid
      })
    }

  },  /**
  * 查看处方
  * type 0 处方 1 用药建议
  * @param {} e 
  */
 viewRecipe(e) {
   let item = e.currentTarget.dataset.item;
   console.log("item", item)
   wx.navigateTo({
     url: '/packageA/recipeDetails/recipeDetails?id=' + item.payid + '&type=' + item.type,
   })
 },
})