// packageA/pages/chat/chat.js 聊天
const Tim = require('../../utils/tim.js');
const Service = require('../../utils/service.js');
const Util = require('../../utils/util.js');
import TIM from 'tim-wx-sdk';
const App = getApp();

// 获取全局唯一的录音管理器 RecorderManager
const recorderManager = wx.getRecorderManager();
const audioContext = wx.createInnerAudioContext();
// 录音部分参数
const recordOptions = {
  duration: 60000, // 录音的时长，单位 ms，最大值 60000（10 分钟）
  sampleRate: 44100, // 采样率
  numberOfChannels: 1, // 录音通道数
  encodeBitRate: 192000, // 编码码率
  format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和 Web）互通
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    errorToptips: '',
    noSrc: '/images/sqicon@2x.png',
    nav: true, //控制头部医师显示
    scrollHeight: "100%", //聊天内容显示
    adjust: true,
    keyHeight: 0,//输入框高度
    scrollTop: 0,
    reportShow: true, //发送报告内容框
    iPhoneX: false,
    doctorunitid: '',
    t_unionid: '',
    orderId: '',
    sendBtns: false, //消息内容框
    estimate: false, //服务评价模态框
    serviceEvaluation: true, //服务评价悬浮框
    graded: 0,
    estimateIssue: {
      issue1: false,
      issue2: false,
      issue3: false,
      issue4: false
    },
    cursor: 190,
    conversationID: '', //会话ID
    messageList: [], //会话消息列表
    unsentMessageList: [], //待发送消息列表
    msgContent: '', //默认消息文字
    isRecord: false, //录音显示
    isRecording: false, //是否正在录音
    isTouch:false,       //防止录音单次点击出现bug
    canSend: true,
    title: "正在录音",
    audioSave: '', //当前播放音频路径
    payFlag: false,
    sendBtns: true,
    scrollloading: false, //是否正在拉取历史消息
    lastShowTimeStamp: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log('chat/chat', options)
    // that.data.doctorunitid = Util.isEmpty(options.unitid) ? "" : options.unitid;
    that.data.t_unionid = options.t_unionid;
    that.data.conversationID = 'GROUP' + options.groupID; //会话id
    that.data.groupID = options.groupID; //群号
    let promise = Tim.getConversationProfile({
      conversationID: 'GROUP' + options.groupID
    });
    promise.then(function (imResponse) {
      // 获取成功
      console.log("%c会话资料", "color:#ff0000", imResponse.data.conversation); // 会话资料
      wx.setStorageSync('groupName', imResponse.data.conversation.groupProfile.name);
    }).catch(function (imError) {
      console.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
    });
    console.log("wx.getStorageSync('data').headimgurl", wx.getStorageSync('data').headimgurl)
    that.setData({
      orderId: Util.isEmpty(options.orderId) ? 0 : Number(options.orderId), //订单id、服务id
      avatarUrl: wx.getStorageSync('data').headimgurl,
      name: wx.getStorageSync('data').name ? wx.getStorageSync('data').name : wx.getStorageSync('data').nickname
    })
    that.getHeight(); //获取当前屏幕高度
    that.checkModal(); //检查是否是iphone
    that.getSetting(); //查询是否接收订阅消息
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onPause(() => {
      console.log('recorder pause')
    })
    recorderManager.onError(function (errMsg) {
      wx.
      console.warn('recorder error:', errMsg);
    });
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      wx.hideLoading()
      if (that.data.canSend) {
        if (res.duration < 1000) {
          that.setData({
            errorToptips: '说话时间太短'
          })
          return;
        } else {
          let message = {
            to: that.data.groupID,
            conversationType: TIM.TYPES.CONV_GROUP,
            payload: {
              file: res
            },
            type: 'TIMSoundElem',
            onProgress: (event) => {
              console.log('file uploading:', event)
            }
          }
          console.log("message", message)
          //待发送消息插入
          that.unsentMessageInsert(message)
          // 发送语音
          Tim.createAudioMessage(message).then((imResponse) => {
            console.log("%c语音发送成功", "color:#04BE02", imResponse)
            that.sendMessageSucceed(imResponse);
          }).catch(imError => {
            console.error("发送失败", imError)
          });
        }
      }
    })
    //语音监听
    audioContext.onPlay(() => {
      console.log("onPlay")
    });
    audioContext.onEnded(() => {
      console.log("onEnded")
      that.setData({
        audioSave: ''
      });
    });
    audioContext.onStop(() => {
      console.log("onStop")
    })
    audioContext.onError(() => {
      wx.showToast({
        title: "小程序暂不支持播放该音频格式",
        icon: "none",
        duration: 2000,
      })
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //定时上报任务
    let timer = setInterval(() => {
      if (App.globalData.isLogin) {
        clearInterval(timer);
        that.setMessageRead();
      }
    }, 600)
    // 群资料
    // let promise = Tim.getGroupProfile({
    //   groupID: that.data.groupID,
    //   groupCustomFieldFilter:[]
    // });
    // promise.then(function (imResponse) {
    //   // 获取成功
    //   console.log("%c群资料", "color:#ff0000", imResponse.data.group); // 群资料
    //   that.setData({
    //     introduction:imResponse.data.group.introduction
    //   })
    // }).catch(function (imError) {
    //   console.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
    // });
    // 登录
    // wx.login({
    //   success: function (msg) {
    //     Service.getOpenId(msg.code).then((res) => {
    //       wx.setStorageSync('user', res); //存储openid
    //       return Service.getUserData(res.openid)
    //     }).then((res) => {
    //       wx.setStorageSync('data', res)
    //       if (Util.isEmpty(res.unionid)) return Service.breakPromise();
    //       else return Service.getUserSig(res.unionid)
    //     }).then((res) => {
    //       return Tim.login(res.data.userid, res.data.sign)
    //     }).then(function (imResponse) {
    //       App.globalData.isLogin = true;
    //       console.log('%c登录成功', "color:#04BE02", imResponse.data.errorInfo);
    //       that.getMessageList(that.data.groupID);//打开某个会话时，第一次拉取消息列表和获取群信息
    //       if (imResponse.data.repeatLogin === true) {
    //         // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
    //         console.log('"%c本次登录操作为重复登录', "color:#ff0000", imResponse.data.errorInfo);
    //       }
    //     }).catch(function (imError) {
    //       console.log('"%c登录失败', "color:#ff0000", imError); // 登录失败
    //       console.warn('login error:', imError); // 登录失败的相关信息
    //     });
    //   }
    // })
    wx.login({
      success: function (msg) {
        Service.getOpenId(msg.code).then((res) => {
          wx.setStorageSync('user', res)
          return Service.getUserData(res.openid)
        }).then((res) => {
          console.log("res",res)
          let timers = setInterval(() => {
            console.log("App.globalData.isLogin", App.globalData.isLogin);
            if (App.globalData.isLogin) {
              clearInterval(timers);
              that.getMessageList(that.data.groupID); //打开某个会话时，第一次拉取消息列表和获取群信息
            }
          }, 500)
            wx.setStorageSync('data', res)
            that.setMessageRead();
        }).catch(error => {
          console.error("我的服务登录", error)
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面从前台变为后台时执行
   */
  onHide: function () {
    var that = this;
    // wx.stopVoice();
    // //删除当前页面消息上报定时器
    clearInterval(that.data.messageReadInterval);
    // //取消监听当前页面单聊消息
    Tim.tim.off(TIM.EVENT.MESSAGE_RECEIVED, that.onMessageReceived);
  },
  /**
   * 页面销毁时执行
   */
  onUnload: function () {
    var that = this;
    //删除当前页面消息上报定时器
    clearInterval(that.data.messageReadInterval);
    //取消监听当前页面单聊消息
    Tim.tim.off(TIM.EVENT.MESSAGE_RECEIVED, that.onMessageReceived);
    //停止播放音频
    if (that.data.audioSave != '') {
      audioContext.stop();
      //初始化
      that.setData({
        audioSave: ''
      })
    }
  },
  //  _______             __        __  __
  //  |       \           |  \      |  \|  \
  //  | $$$$$$$\ __    __ | $$____  | $$ \$$  _______
  //  | $$__/ $$|  \  |  \| $$    \ | $$|  \ /       \
  //  | $$    $$| $$  | $$| $$$$$$$\| $$| $$|  $$$$$$$
  //  | $$$$$$$ | $$  | $$| $$  | $$| $$| $$| $$
  //  | $$      | $$__/ $$| $$__/ $$| $$| $$| $$_____
  //  | $$       \$$    $$| $$    $$| $$| $$ \$$     \
  //   \$$        \$$$$$$  \$$$$$$$  \$$ \$$  \$$$$$$$
  /**
   * 判断授权 
   */
  checkDeviceAuthorize: function () {
    this.hasOpenDeviceAuthorizeModal = false
    return new Promise((resolve, reject) => {
      if (!wx.getSetting || !wx.getSetting()) {
        // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
        resolve()
      }
      wx.getSetting().then((result) => {
        this.authorizeMic = result.authSetting['scope.record']
        this.authorizeCamera = result.authSetting['scope.camera']
        if (result.authSetting['scope.camera'] && result.authSetting['scope.record']) {
          // 授权成功
          resolve()
        } else {
          // 没有授权，弹出授权窗口
          // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
          console.log('getSetting 没有授权，弹出授权窗口', result)
          wx.authorize({
            scope: 'scope.record',
          }).then((res) => {
            console.log('authorize mic', res)
            this.authorizeMic = true
            if (this.authorizeCamera) {
              resolve()
            }
          }).catch((error) => {
            console.log('authorize mic error', error)
            this.authorizeMic = false
          })
          wx.authorize({
            scope: 'scope.camera',
          }).then((res) => {
            console.log('authorize camera', res)
            this.authorizeCamera = true
            if (this.authorizeMic) {
              resolve()
            } else {
              this.openConfirm()
              reject(new Error('authorize fail'))
            }
          }).catch((error) => {
            console.log('authorize camera error', error)
            this.authorizeCamera = false
            this.openConfirm()
            reject(new Error('authorize fail'))
          })
        }
      })
    })
  },
  /**打开订阅权限设置 */
  openConfirm: function () {
    if (this.hasOpenDeviceAuthorizeModal) {
      return
    }
    this.hasOpenDeviceAuthorizeModal = true
    return wx.showModal({
      content: '您没有打开麦克风和摄像头的权限，是否去设置打开？',
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        this.hasOpenDeviceAuthorizeModal = false
        console.log(res)
        // 点击“确认”时打开设置页面
        if (res.confirm) {
          console.log('用户点击确认')
          wx.openSetting({
            success: (res) => {},
          })
        } else {
          console.log('用户点击取消')
        }
      },
    })
  },
  /**切换语音显示 */
  record() {
    let that = this;
    that.setData({
      isRecord: !that.data.isRecord,
      reportShow: true
    })
  },
  /**默认Tap事件，阻止冒泡事件*/
  true() {},
  /**复制 */
  copy(e) {
    let cope = e.currentTarget.dataset.c;
    wx.setClipboardData({
      data: cope,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  /**
   * 监听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
    })
    if (that.data.isCompleted) {
      //已经拉完所有消息
      setTimeout(() => {
        that.setData({
          scrollloading: false
        })
        wx.showToast({
          title: '没有更多了',
          icon: 'none',
          duration: 2500
        })
      }, 2000);
    } else {
      //未拉完所有消息
      Tim.getMessageList({
        conversationID: that.data.conversationID,
        nextReqMessageID: that.data.nextReqMessageID,
        count: 10
      }).then((imResponse) => {
        console.log("%c续拉消息列表", "color:#04BE02", imResponse)
        let msgList = Util.deepClone(imResponse.data.messageList);
        let messageList = that.messageListParser(msgList);
        messageList = that.showTimestamp(messageList)
        setTimeout(() => {
          that.setData({
            messageList: messageList.concat(that.data.messageList), // 消息列表。
            nextReqMessageID: imResponse.data.nextReqMessageID, // 用于续拉，分页续拉时需传入该字段。
            isCompleted: imResponse.data.isCompleted, // 表示是否已经拉完所有消息。
            scrollloading: false,
          })
        }, 2000);
      }).catch(error => {
        console.error("打开某个会话时，第一次拉取消息列表", error)
      });
    }
  }, 1000, true),
  /**
   * 当前医生信息
   * @param {医生t_unionid} t_unionid 
   */
  getDoctorInfo(t_unionid) {
    var that = this;
    let data = {};
    data.unionid = t_unionid;
    Service.getChatDoctor(data).then((res) => {
      if (res.code == 1) {
        that.setData({
          nav: true,
          doctortitle: Util.getTitle(res.data.title),
          doctorimage: res.data.image,
          doctorname: res.data.name,
          doctorgoodat: res.data.goodat,
          doctorunitid: res.data.unitid,
          t_openid: res.data.openid,
          epidemic: res.data.epidemic ? res.data.epidemic : ''
        });
        var Navtitle = res.data.name + ' | ' + Util.getTitle(res.data.title);
        wx.setNavigationBarTitle({
          title: Navtitle
        })
        that.userPayList(that.data.orderId);
        that.checkModal();
      } else {
        that.setData({
          nav: false
        });
        that.checkModal();
      }
    }).catch(error => {
      console.error("当前医生信息", error)
    })
  },
  /**
   * 服务评价
   */
  estimateShow: function () {
    this.setData({
      estimate: !this.data.estimate
    })
  },
  /**
   * 服务评分
   * @param {*} e 
   */
  graded: function (e) {
    var graded = e.currentTarget.dataset.graded;
    switch (graded) {
      case '1':
        this.setData({
          graded: e.currentTarget.dataset.graded,
          graded_text: '非常不满意，医生服务太差'
        })
        break;
      case '2':
        this.setData({
          graded: e.currentTarget.dataset.graded,
          graded_text: '不满意，医生服务差'
        })
        break;
      case '3':
        this.setData({
          graded: e.currentTarget.dataset.graded,
          graded_text: '服务一般，需要改善'
        })
        break;
      case '4':
        this.setData({
          graded: e.currentTarget.dataset.graded,
          graded_text: '比较满意，仍需改善'
        })
        break;
      case '5':
        this.setData({
          graded: e.currentTarget.dataset.graded,
          graded_text: '非常满意，强烈推荐'
        })
        break;
    }
  },
  /**
   * 服务的问题
   * @param {} e 
   */
  issue: function (e) {
    var that = this;
    var issue = e.currentTarget.dataset.issue;
    switch (issue) {
      case '1':
        this.setData({
          ['estimateIssue.issue1']: !that.data.estimateIssue.issue1,
        })
        break;
      case '2':
        this.setData({
          ['estimateIssue.issue2']: !that.data.estimateIssue.issue2,
        })
        break;
      case '3':
        this.setData({
          ['estimateIssue.issue3']: !that.data.estimateIssue.issue3,
        })
        break;
      case '4':
        this.setData({
          ['estimateIssue.issue4']: !that.data.estimateIssue.issue4,
        })
        break;
    }
  },
  /**
   * 服务评价文字
   * @param {*} e 
   */
  textareaChange: function (e) {
    var lineCount = e.detail.lineCount - 1;
    this.setData({
      cursor: 190 - (lineCount * 20)
    })
  },
  /**
   * 页面高度 
   */
  getHeight: function () {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        that.setData({
          winH: res.windowHeight - 50
        })
      }
    });
  },
  /**
   * 判断是否是iPhonex
   */
  checkModal() {
    let that = this;
    var padding_bottom = 0;
    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)) {
          if (that.data.nav) {
            padding_bottom = 250;
          } else {
            padding_bottom = 180;
          }
          that.setData({
            padding_bottom: padding_bottom,
            iPhoneX: true,
          })
        } else {
          if (that.data.nav) {
            padding_bottom = 220;
          } else {
            padding_bottom = 150;
          }
          that.setData({
            padding_bottom: padding_bottom,
            iPhoneX: false,
          })
        }
      }
    });
  },
  /**
   * 滚动到列表bottom
   */
  scrollToBottom() {
    this.setData({
      scrollTop: 99999
    })
  },
  /**
   * 查询是否接收订阅消息
   */
  getSetting: function () {
    let that = this;
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        var itemSettings = !Util.isEmpty(res.subscriptionsSetting) ? res.subscriptionsSetting.itemSettings : "";
        if (itemSettings) {
          if (itemSettings['d33RkZvTz6O8Zjw8b8faoKIQGXA0cJJ2G24_kIWQjtY'] == 'accept') {
            that.setData({
              remind: false
            });
            that.checkDeviceAuthorize().then((result) => {
              console.log('%c授权成功', 'color:#04BE02', result)
            }).catch((error) => {
              console.log('没有授权', error)
            })
          } else {
            that.setData({
              remind: true
            });
          }
        } else {
          that.setData({
            remind: true
          });
        }
      }
    })
  },
  /**
   * 提示允许接收订阅消息
   */
  remind: function () {
    var that = this;
    that.setData({
      remind: false
    })
    wx.requestSubscribeMessage({
      tmplIds: ['d33RkZvTz6O8Zjw8b8faoKIQGXA0cJJ2G24_kIWQjtY'],
      success(res) {}
    })
    that.checkDeviceAuthorize().then((result) => {
      console.log('%c授权成功', 'color:#04BE02', result)
    }).catch((error) => {
      console.log('没有授权', error)
    })
  },
  /**
   *  服务提前结束 0同意 1拒绝
   */

  endInquiry: function (e) {
    var alldata = wx.getStorageSync('data')
    let that = this;
    var data = {
      id: that.data.orderId,
      consultant_unionid: that.data.userid,
      patient_unionid: alldata.unionid,
      chat_id: that.data.groupID
    }
    if (e == 0) {
      Service.endInquiry(data).then((res) => {
        console.log("endInquiry", res)
        that.userPayList(that.data.orderId);
      })
    } else {
      Service.refuseInquiry(data).then((res) => {
        console.log("refuseInquiry", res)
      })
    }
  },
  /**
   * 返回用户支付列表
   */
  userPayList(orderId) {
    let that = this
    var data = {
      id: orderId,
      consultant_unionid: that.data.t_unionid,
      patient_unionid: wx.getStorageSync('data').unionid,
      unitid: that.data.doctorunitid
    }
    Service.seeBuyStaus(data).then((res) => {
      if (res.code == 1 && res.data.status == '1') {
        that.setData({
          payFlag: true,
          payFlag1: false,
          sendBtns: true,
          end_time: res.data.end_time_stamp,
          status: false,
          serviceName: res.data.name
        })
        return;
      } else if (res.code == 1 && res.data.status == "0") {
        that.setData({
          payFlag1: true,
          end_time: '待接诊',
          sendBtns: true,
          status: true,
          serviceName: res.data.name
        })
        return;
      } else if (res.code == 1 && res.data.status == "2") {
        that.setData({
          payFlag: false,
          end_time: '已结束',
          sendBtns: true,
          status: true,
          serviceName: res.data.name
        })
        that.getFreeChat(that.data.t_unionid, wx.getStorageSync('data').unionid);
      } else {
        that.setData({
          payFlag: false,
          end_time: '',
          serviceName: '未知',
        })
        that.getFreeChat(that.data.t_unionid, wx.getStorageSync('data').unionid);
      }
    }).catch(error => {
      console.error("返回用户支付列表", error)
    })
    // 判断和消费状态
  },
  /**
   * 查询是否有免费咨询
   * @param {医生unionid} consultant_unionid 
   * @param {用户unionid} patient_unionid 
   */
  getFreeChat(consultant_unionid, patient_unionid) {
    let that = this;
    let data = {
      consultant_unionid: consultant_unionid,
      patient_unionid: patient_unionid
    }
    Service.getFreeChat(data).then((res) => {
      if (res.data.is_free == 0) {
        that.setData({
          payFlag: true,
          sendBtns: true,
          isSendNum: res.data.num,
          isSendText: "您有" + res.data.num + "条免费咨询"
        })
      } else {
        that.setData({
          sendBtns: true,
          payFlag: false,
        })
      }
    }).catch((error) => {
      console.error("免费咨询", error)
    })
  },
  /**
   * 扣除免费次数
   * @param {医生unionid} consultant_unionid 
   * @param {用户unionid} patient_unionid 
   */
  setFreeSend(consultant_unionid, patient_unionid) {
    let that = this;
    let data = {
      consultant_unionid: consultant_unionid,
      patient_unionid: patient_unionid
    }
    Service.setFreeSend(data).then((res) => {
      if (res.data.is_free == 0) {
        that.setData({
          payFlag: true,
          isSendNum: res.data.num,
          isSendText: "您有" + res.data.num + "条免费咨询"
        })
        if (res.data.num == 1) {
          that.setData({
            hold: false,
          })
        }
      } else {
        that.setData({
          payFlag: false,
          isSendNum: 0,
          isSendText: ""
        })
      }
    }).catch(error => {
      console.error("修改免费咨询", error)
    })
  },
  /**
   * 医生更多服务
   */
  moreService:Util.debouce(function() {
    var that = this;
    wx.navigateTo({
      url: '/pages/docuterInfo/docuterInfo?t_unionid=' + that.data.t_unionid + '&t_unitid=' + that.data.doctorunitid + '&t_openid=' + that.data.t_openid,
    })
  },1000,true),
  //input获取焦点
  inputFoucus: function (e) {
    var that = this;
    that.setData({
      reportShow: true
    })
    if (!that.data.payFlag) {
      if (!that.data.nav) {
        wx.showToast({
          title: '医生暂未开通此服务！',
          icon: 'none',
          duration: 1500
        })
      } else {
        wx.navigateTo({
          url: '/pages/docuterInfo/docuterInfo?t_unionid=' + that.data.t_unionid + '&t_unitid=' + that.data.doctorunitid + '&t_openid=' + that.data.t_openid,
        })
      }
    }
    var windowHeight = that.data.winH;
    var keyHeight = e.detail.height;
    var scrollHeight = (windowHeight - keyHeight - 158) + 'px'
    this.setData({
      adjust: false,
      scrollHeight: scrollHeight,
      keyHeight: keyHeight
    });
    //延时500ms避免scroll-view的防止抖动生效
    setTimeout(() => {
      that.scrollToBottom(); //使滑动条到最底部
    }, 500);
  },
  //失去聚焦
  inputBlur: function (e) {
    var that = this;
    that.setData({
      adjust: true,
      keyHeight: 0,
      scrollHeight: "100%"
    })
  },
  //获取输入框本文
  inputMessage: function (e) {
    var that = this;
    that.setData({
      msgContent: e.detail.value
    })
  },
  //回车发送输入框本文
  bindconfirm(e) {
    var that = this;
    that.setData({
      msgContent: e.detail.value
    })
    that.createTextMessage()
  },
  /**
   * 图片预览
   */
  previewImage(e) {
    var src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
      current: src
    })
  },
  /**
   * 聊天记录
   */
  chatLog:Util.debouce(function () {
    wx.showLoading();
    wx.navigateTo({
      url: '/packageA/chattingRecords/chattingRecords?id=' + this.data.orderId + '&doctorimage=' + this.data.doctorimage,
    })
    wx.setStorageSync('list', this.data.messageList);
    wx.hideLoading();
  },1000,true),
  scroll: function () {},
  //  ______  __       __        ______             __                                              __
  //  |      \|  \     /  \      |      \           |  \                                            |  \
  //   \$$$$$$| $$\   /  $$       \$$$$$$ _______  _| $$_     ______    ______   _______    ______  | $$
  //    | $$  | $$$\ /  $$$        | $$  |       \|   $$ \   /      \  /      \ |       \  |      \ | $$
  //    | $$  | $$$$\  $$$$        | $$  | $$$$$$$\\$$$$$$  |  $$$$$$\|  $$$$$$\| $$$$$$$\  \$$$$$$\| $$
  //    | $$  | $$\$$ $$ $$        | $$  | $$  | $$ | $$ __ | $$    $$| $$   \$$| $$  | $$ /      $$| $$
  //   _| $$_ | $$ \$$$| $$       _| $$_ | $$  | $$ | $$|  \| $$$$$$$$| $$      | $$  | $$|  $$$$$$$| $$
  //  |   $$ \| $$  \$ | $$      |   $$ \| $$  | $$  \$$  $$ \$$     \| $$      | $$  | $$ \$$    $$| $$
  //   \$$$$$$ \$$      \$$       \$$$$$$ \$$   \$$   \$$$$   \$$$$$$$ \$$       \$$   \$$  \$$$$$$$ \$$
  /**
   * 创建消息上报定时任务
   */
  setMessageRead() {
    var that = this;
    Tim.setMessageRead({
      conversationID: that.data.conversationID
    }).then((event) => {
      // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
      console.log("%c已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0", "color:#04BE02", event)
    }).catch(function (imError) {
      // 已读上报失败
      console.warn("%c已读上报失败", "color:#FF0000", imError);
    });
    that.data.messageReadInterval = setInterval(() => {
      if (App.globalData.isLogin) {
        Tim.setMessageRead({
          conversationID: that.data.conversationID
        }).then(() => {}).catch(function (imError) {
          // 已读上报失败
          console.warn("%c已读上报失败", "color:#FF0000", imError);
        });
      }
    }, 10000);
  },
  /**
   * 打开某个会话时，第一次拉取消息列表和获取群信息
   * @param {*房间号} userID 
   */
  getMessageList(userID) {
    let that = this;
    console.log("userID", userID)
    Service.getServiceList({
      chat: userID
    }).then((res) => {
      console.log("res", res)
      if (res.code == 1) {
        that.setData({
          orderId: res.data[0].id,
        })
        that.getDoctorInfo(that.data.t_unionid);
      }
      return Tim.getMessageList({
        conversationID: 'GROUP' + userID,
        count: 15
      });
    }).then((imResponse) => {
      console.log("%c第一次拉取消息列表", "color:#04BE02", imResponse)
      let msgList = Util.deepClone(imResponse.data.messageList);
      let messageList = that.messageListParser(msgList);
      let length = Number(messageList.length - 1);
      console.log("length",length)
      if (length >= 0) {
        that.data.lastShowTimeStamp = messageList[length].time;
        console.log("messageList[length].payload.data",messageList[length].payload.data)
        if (messageList[length].payload.data == "InitiateEndService") {
          wx.showModal({
            title: '提示',
            content: '对方发起了一个结束当前服务的请求',
            success(res) {
              if (res.confirm) {
                that.endInquiry(0);
                that.userPayList(that.data.orderId ? that.data.orderId : '');
              } else if (res.cancel) {
                that.endInquiry(1);
                that.userPayList(that.data.orderId ? that.data.orderId : '');
              }
            }
          })
        }
      }
      that.setData({
        messageList: that.showTimestamp(messageList), // 消息列表。
        nextReqMessageID: imResponse.data.nextReqMessageID, // 用于续拉，分页续拉时需传入该字段。
        isCompleted: imResponse.data.isCompleted // 表示是否已经拉完所有消息。
      })
      //延时500ms避免scroll-view的防止抖动生效
      setTimeout(() => {
        that.scrollToBottom(); //使滑动条到最底部
      }, 500);
      Tim.tim.on(TIM.EVENT.MESSAGE_RECEIVED, that.onMessageReceived);
    }).catch((error) => {
      console.error("打开某个会话时，第一次拉取消息列表", error)
    });

  },
  /**
   * 设置消息时间戳
   * @param {*消息数组} messages
   */
  showTimestamp(messages) {
    let lastShowTimeStamp = 0;
    let messageList = messages.map(item => {
      if (item.type != 'TIMGroupTipElem') {
        if (item.payload.data == "UserInfo" || item.payload.data == "groupTips") {
          item.time = '';
          return item;
        }
        if (Number(item.time - lastShowTimeStamp) >= 300) {
          lastShowTimeStamp = item.time;
          item.time = Util.timestampIM(item.time)
        } else {
          item.time = '';
        }
        return item;
      }
    })
    return messageList;
  },
  /**
   *   设置新消息时间戳
   * @param {*} messages 
   */
  showNewMessageTime(messages) {
    let that = this;
    console.log("messages", messages);
    console.log("lastShowTimeStamp", that.data.lastShowTimeStamp);
    let messageList = messages.map(item => {
      if (Number(item.time - that.data.lastShowTimeStamp) >= 300) {
        that.data.lastShowTimeStamp = item.time;
        item.time = Util.timestampIM(item.time)
      } else {
        item.time = '';
      }
      return item;
    })
    return messageList;
  },
  /**
   * 监听新的消息，当有新消息时插入messageList中
   */
  onMessageReceived: function (event) {
    let that = this;
    console.log("%c收到推送的单聊", "color:#04BE02", event)
    if (event.data[0].conversationID == that.data.conversationID) {
      let message = Util.deepClone(event.data);
      message = that.showNewMessageTime(message); //设置新消息时间戳
      message = that.messageListParser(message); //解析新消息
      console.log('message', message)
      let isUserInfo = message.some((item) => item.payload.data == "UserInfo")
      console.log(isUserInfo)
      if (isUserInfo) {
        that.userPayList(that.data.orderId);
      }
      that.setData({
        messageList: that.data.messageList.concat(message)
      })
      if (message[message.length - 1].payload.data == "InitiateEndService" && that.data.payFlag) {
        console.log("message", message[message.length - 1])
        wx.showModal({
          title: '提示',
          content: '对方发起了一个结束当前服务的请求',
          success(res) {
            if (res.confirm) {
              that.endInquiry(0, message[message.length - 1].payload.description.relation_id);
              that.userPayList(that.data.orderId ? that.data.orderId : '');
            } else if (res.cancel) {
              that.endInquiry(1, message[message.length - 1].payload.description.relation_id);
              that.userPayList(that.data.orderId ? that.data.orderId : '');
            }
          }
        })
      }
      //延时500ms避免scroll-view的防止抖动生效
      setTimeout(() => {
        that.scrollToBottom(); //使滑动条到最底部
      }, 500);
    }
    // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
    // event.name - TIM.EVENT.MESSAGE_RECEIVED
    // event.data - 存储 Message 对象的数组 - [Message]
  },

  /**
   * 解析自定义消息
   * type值属性
   * reminder      温馨提示
   * reminder2     温馨提示
   * followUp      随访邀请
   * UserInfo      用户信息
   * LaunchVideo   视频通话请求
   * closeVideo    视频通话结束
   * hangUpVideo   视频通话挂断
   * EndOfService  服务结束
   * InitiateEndService   结束服务请求
   * NeverEndService      拒绝结束服务
   * 
   * *********JSON解析两次的**********
   * Prescription         处方药方
   * UserDrug             医生推荐
   * Checkup              心理体检
   * report               量表报告
   */
  messageListParser(messages) {
    let messageList = messages.map(item => {
      if (item.type == "TIMCustomElem") {
        item.payload.data = JSON.parse(item.payload.data)
        let type = item.payload.data.type;
        if (type == 'InitiateEndService' || type == 'NeverEndService' || type == 'EndOfService' || type == 'reminder'||type=='reminder2' || type == 'followUp' || type == 'UserInfo' || type == 'LaunchVideo' || type == 'closeVideo' || type == 'hangUpVideo' || type == 'groupTips') {
          item.payload.description = item.payload.data.content;
          item.payload.data = item.payload.data.type;
        } else if (type == 'Prescription' || type == 'UserDrug' || type == 'Checkup' || type == 'report') {
          item.payload.description = JSON.parse(item.payload.data.content);
          item.payload.data = item.payload.data.type;
        }
      }
      return item;
    })
    return messageList;
  },
  /**
   * 待发送消息插入
   */
  unsentMessageInsert(message) {
    let that = this;
    let Arr = new Array;
    let lastShowTimeStamp = that.data.lastShowTimeStamp;
    console.log("lastShowTimeStamp", lastShowTimeStamp);
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("timestamp", timestamp);
    console.log(Number(timestamp - lastShowTimeStamp));
    if (Number(timestamp - lastShowTimeStamp) >= 300) {
      message.time = Util.timestampIM(timestamp)
    } else {
      message.time = '';
    }
    //只需自定义消息才解析
    if (message.type == "TIMCustomElem") {
      message.payload.data = JSON.parse(message.payload.data);
      message.payload.description = JSON.parse(message.payload.data.content);
      message.payload.data = message.payload.data.type;
    }
    Arr.push(message);

    that.setData({
      unsentMessageList: that.data.unsentMessageList.concat(Arr),
      msgContent: ''
    })
    //扣除免费次数
    if (that.data.isSendNum > 0) {
      that.setFreeSend(that.data.t_unionid, wx.getStorageSync('data').unionid);
    }
    that.scrollToBottom(); //使滑动条到最底部
  },
  /**
   * 发送消息成功
   * 插入新消息删除待发消息
   */
  sendMessageSucceed(imResponse) {
    let that = this;
    let unsentMessageList = that.data.unsentMessageList;
    //删除第一条待发消息
    unsentMessageList.shift();
    let messageList = that.data.messageList;
    //插入新消息
    let lastShowTimeStamp = that.data.lastShowTimeStamp;
    console.log("lastShowTimeStamp", lastShowTimeStamp);
    console.log("imResponse.data.message.time", imResponse.data.message.time);
    console.log(Number(imResponse.data.message.time - lastShowTimeStamp));
    if (Number(imResponse.data.message.time - lastShowTimeStamp) >= 300) {
      that.data.lastShowTimeStamp = imResponse.data.message.time;
      imResponse.data.message.time = Util.timestampIM(imResponse.data.message.time)
    } else {
      imResponse.data.message.time = '';
    }
    messageList.push(imResponse.data.message)
    that.setData({
      messageList: messageList,
      unsentMessageList: unsentMessageList
    })
    setTimeout(() => {
      that.scrollToBottom();
    }, 500);
  },
  /**
   * 发送文本消息createTextMessage
   */
  createTextMessage() {
    var that = this;
    let msgContent = that.data.msgContent.replace(/\s+/g, '');
    if (msgContent == '') {
      that.setData({
        errorToptips: '不能发送空白消息'
      })
      return;
    }
    if (!that.data.payFlag) {
      that.moreService();
    } else {
      let message = {
        to: that.data.groupID,
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          text: that.data.msgContent,
        },
        type: "TIMTextElem"
      }
      //待发送消息插入
      that.unsentMessageInsert(message);
      Tim.createTextMessage(message).then((imResponse) => {
        console.log("%c文本消息发送成功", "color:#04BE02", imResponse)
        //插入新消息删除待发消息
        that.sendMessageSucceed(imResponse);
      }).catch(imError => {
        console.error("发送失败", imError)
      });
    }
  },
  /**
   * 发送图片消息createImageMessage
   */
  createImageMessage() {
    var that = this;
    if (!that.data.payFlag) {
      that.moreService();
    } else {
      wx.chooseImage({
        sizeType: ['compressed', 'original'], //支持原图和压缩图
        sourceType: ['album', 'camera'], // 从相册选择和使用相机
        count: 1, // 只选一张，目前 SDK 不支持一次发送多张图片
        success: function (res) {
          // 2. 创建消息实例，接口返回的实例可以上屏
          let message = {
            to: that.data.groupID,
            conversationType: TIM.TYPES.CONV_GROUP,
            payload: {
              file: res
            },
            //临时图片路径
            path: res.tempFilePaths[0],
            type: "TIMImageElem",
            onProgress: (event) => {
              console.log('file uploading:', event)
            }
          }
          //待发送消息插入
          that.unsentMessageInsert(message)
          // 3. 发送图片
          Tim.createImageMessage(message).then((imResponse) => {
            console.log("%c图片消息发送成功", "color:#04BE02", imResponse)
            that.sendMessageSucceed(imResponse);
          }).catch(imError => {
            console.error("发送失败", imError)
          });
        }
      })
    }
  },
  /**
   * 手指按下
   */
  handleLongPress(e) {
    var that = this;
    //当前是按下状态
    that.data.isTouch=true;
    console.log("手指按下")
    that.data.startPoint = e.touches[0];
    if (!this.data.payFlag) {
      that.moreService();
    } else {
      // 3. 开始录音
      that.startRecording();
    }
  },
  /**手指上滑 */
  handleTouchMove(e) {
    let that = this;
    if (that.data.isRecording) {
      if (that.data.startPoint.clientY - e.touches[e.touches.length - 1].clientY > 100) {
        that.setData({
          title: '松开手指，取消发送',
          canSend: false
        })
      } else if (that.data.startPoint.clientY - e.touches[e.touches.length - 1].clientY > 20) {
        that.setData({
          title: '上划可取消',
          canSend: true
        })
      } else {
        that.setData({
          title: '正在录音',
          canSend: true
        })
      }
    }
  },
  /**
   * 手指离开页面滑动
   */
  handleTouchEnd() {
    console.log("手指离开")
    //当前是手指离开状态
    this.data.isTouch=false;
    wx.hideLoading()
    recorderManager.stop()
    this.setData({
      isRecording: false
    })
  },
  // 开始录音之前要判断一下是否开启权限
  startRecording() {
    var that = this;
    wx.getSetting({
      success: (res) => {
        let auth = res.authSetting['scope.record']
        if (auth === false) { // 已申请过授权，但是用户拒绝
          wx.openSetting({
            success: function (res) {
              let auth = res.authSetting['scope.record']
              if (auth === true) {
                wx.showToast({
                  title: '授权成功',
                  icon: 'success',
                  duration: 1500
                })
              } else {
                wx.showToast({
                  title: '授权失败',
                  icon: 'none',
                  duration: 1500
                })
              }
            }
          })
        } else if (auth === true) { // 用户已经同意授权
          // console.log('this.data.isTouch',this.data.isTouch)
          //判断当前按压状态，是按下就执行录音
          if(this.data.isTouch){
            that.setData({
              canSend: true,
              isRecording: true,
              title: "正在录音"
            })
            recorderManager.start(recordOptions)
          }else{
            //否则提示"说话时间短"
            that.setData({
              errorToptips: '说话时间太短'
            })
          }
        } else { // 第一次进来，未发起授权
          wx.authorize({
            scope: 'scope.record',
            success: () => {
              wx.showToast({
                title: '授权成功',
                icon: 'success',
                duration: 1500
              })
            }
          })
        }
      },
      fail: function () {
        wx.showToast({
          title: '授权失败',
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  /**
   * 播放语音消息
   */
  openAudio(e) {
    let that = this;
    wx.stopVoice();
    audioContext.src = e.currentTarget.dataset.payload.url;
    let uuid = e.currentTarget.dataset.payload.uuid;
    if (uuid == that.data.audioSave) {
      audioContext.stop();
      //初始化
      that.setData({
        audioSave: ''
      })
    } else {
      //不是同一个语音 直接播放其它，将此次语音记录
      audioContext.play();
      that.setData({
        audioSave: uuid
      })
    }
  },

  /**
   * 报告模块列表显示or关闭报告列表
   * @param {} e 
   */
  openReport() {
    let that = this
    if (!that.data.payFlag) {
      that.moreService();
    } else {
      //未显示状态
      if (that.data.reportShow) {
        let data = {
          openid: wx.getStorageSync('user').openid,
          t_openid: that.data.t_openid
        }
        that.setData({
          reportShow: false
        })
        //病人报告unionid
        Service.getSendReports(data).then((res) => {
          let arr = [];
          if (res.code == 1) {
            arr = res.data;
          }
          that.setData({
            result: arr,

          })
        }).catch(error => {
          console.error("报告模块列表显示", error)
        })
      } else {
        this.setData({
          reportShow: true
        })
      }
    }
  },
  /**发送报告消息 */
  createReportMessage(e) {
    let that = this
    let id = e.currentTarget.dataset.id; //量表id
    let res_id = e.currentTarget.dataset.id; //量表id
    let lbname = e.currentTarget.dataset.lbname; //量表id
    let time = e.currentTarget.dataset.time; //量表时间
    let is_type = e.currentTarget.dataset.istype; //量表是否允许查看
    wx.showModal({
      title: '',
      content: '确认发送此报告?',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#555',
      confirmText: '确定',
      confirmColor: '#3cc51f',
      success: (e) => {
        if (e.confirm) {
          if (!that.data.payFlag) {
            that.moreService();
          } else {
            let message = {
              to: that.data.groupID,
              conversationType: TIM.TYPES.CONV_GROUP,
              payload: {
                data: JSON.stringify({
                  type: 'report',
                  content: JSON.stringify({
                    id,
                    res_id,
                    lbname,
                    time,
                    is_type
                  })
                }),
                description: "",
                extension: ""
              },
              type: "TIMCustomElem"
            }
            //待发送消息插入
            this.setData({
              reportShow: true
            })
            let msg = Util.deepClone(message);
            that.unsentMessageInsert(msg);
            Tim.createCustomMessage(message).then((imResponse) => {
              console.log("%c报告消息发送成功", "color:#04BE02", imResponse)
              //插入新消息删除待发消息
              imResponse.data.message.payload.data = JSON.parse(imResponse.data.message.payload.data);
              imResponse.data.message.payload.description = JSON.parse(imResponse.data.message.payload.data.content);
              imResponse.data.message.payload.data = imResponse.data.message.payload.data.type;
              that.sendMessageSucceed(imResponse);
            }).catch(imError => {
              console.error("发送失败", imError)
            });
          }
        }
      }
    })
  },
  /**
   * 查看报告
   */
  lookReport: Util.debouce(function (e) {
    wx.showLoading();
    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',
    })
    // let data = {
    //   src: e.currentTarget.dataset.src
    // };
    // Service.isReport(data).then((res) => {
    //   if (res.data == 0) {
    //     that.setData({
    //       errorToptips: '请联系咨询师进行下一步诊断！'
    //     })
    //     return;
    //   }
    //   wx.navigateTo({
    //     url: '/packageB/webview/webview?id=' + src[0] + '&lbname=' + src[1] + '&share=0&t_openid=0',
    //   })
    // })
    wx.hideLoading();
  }, 1000, true),
  /**心理体检 */
  getCheckup: Util.debouce(function (e) {
    wx.showLoading();
    let data = {}
    data.inquiry_id = e.currentTarget.dataset.id;
    Service.getTestInfo(data).then((res) => {
      console.log("getCheckup", res)
      if (res.code == 1) {
        var data = {
          t_openid: res.data.openid,
          g_time: res.data.time,
          marketstatus: res.data.marketstatus,
          unitid: res.data.unitid,
        }
        wx.setStorageSync('weiLb', data);
        console.log("info", data)
      }
    })
    wx.navigateTo({
      url: '/pages/info/info?otype=1&inquiry=2&inquiry_id=' + e.currentTarget.dataset.id,
    })
    wx.hideLoading();
  }, 1000, true),
  //微信获取手机号
  goSetTel(e) {
    let that = this;
    let alldata = wx.getStorageSync("data")
    if (Util.isEmpty(alldata.mobilephone)) {
      that.acceptFollowUp();
    } else {
      let user = wx.getStorageSync('user')
      let data = {
        openid: user.openid,
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        session_key: user.session_key
      }
      Service.getWxUserPhone(data).then((res) => {
        if (res.code == 1) {
          alldata.mobilephone = res.data;
          wx.setStorageSync('data', alldata)
          that.acceptFollowUp();
        } else {
          that.setData({
            errorToptips: '获取失败，请重新获取'
          })
        }
      }).catch(err => {
        console.error("获取手机号", err)
      })
    }
  },
  //接受随访邀请
  acceptFollowUp: function () {
    var that = this;
    var user = wx.getStorageSync('data')
    var data = {
      consultant_unionid: that.data.t_unionid, //医生unionid
      patient_unionid: user.unionid, //病人unionid
      is_agree: 1
    };
    Service.acceptFollowUp(data).then((res) => {
      if (res.code == 1) {
        that.setData({
          successToptips: '已添加到提醒'
        })
      } else {
        that.setData({
          errorToptips: '添加失败'
        })
      }
    })
  },
  /**
   * 查看处方
   * type 0 处方 1 用药建议
   * @param {} e 
   */
  viewRecipe: Util.debouce(function(e) {
    wx.showLoading();
    let item = e.currentTarget.dataset.item;
    console.log("item", item)
    wx.navigateTo({
      url: '/packageA/recipeDetails/recipeDetails?id=' + item.payid + '&type=' + item.type,
    })
    wx.hideLoading();
  },1000,true),
  /**
   * 购买药品 buyDrug()
   * isQuick	    开药方式0-正常开药，1-二维码，2-快速开药	
   * name       	姓名	
   * title  	    职称	住院医生
   * work_unit  	工作单位	小懂
   * img        	医生头像	
   * diagnosis  	诊断	抑郁
   * prescription	药方ID	
   * type	        0-处方药，1-保健品	
   * payid	      支付ID
   */
  buyDrug:Util.debouce(function(e) {
    wx.showLoading();
    let that = this;
    let item = e.currentTarget.dataset.item;
    // isQuick	开药方式 0-正常开药，1-二维码，2-快速开药
    let id = item.isQuick == 0 ? item.prescription : item.quickid;
    let data = {
      prescription: id,
      patient_unionid: wx.getStorageSync('data').unionid,
      isquick: item.isQuick
    }
    Service.getPayStatus(data).then((res) => {
      if (res.code == 1) {
        wx.navigateTo({
          url: '/packageA/drugOrder/drugOrder'
        })
        wx.hideLoading();
      } else if (res.code == -1) {
        wx.navigateTo({
          url: '/packageA/drugOrderInfo/drugOrderInfo?scene=' + id + '&isQuick=' + item.isQuick + '&orderId=' + this.data.orderId + '&groupID=' + that.data.groupID,
        })
        wx.hideLoading();
      }else if(res.code == 2){
        wx.hideLoading();
        that.setData({
          errorToptips: res.msg
        })
      }
    })
  },1000,true),
  //客服电话
  dial(e) {
    let tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel,
    })
  },
    /**
   * 图片加载失败函数
   * type 0 医生头像 1 患者头像
   * @param {any} e 
   */
  binderrorimg(e) {
    let type = e.currentTarget.dataset.type;
    // let errorindex = e.currentTarget.dataset.errorindex;
    let up;
    let img;
    if (type == 0) {
      up = "doctorimage";
      img="/images/doctor_img.png";
    } else if(type == 1) {
      up = "avatarUrl";
      img="/images/head-img.png";
    }
    console.log('img',img)
    this.setData({
      [up]: img
    })
  },
})