import logger from '../../../../utils/logger';
import constant from '../../../../utils/constant';
import { wechatTimeFormat } from './../../../../../utils/wechatTime'
import { API } from '../../../../../utils/network/api';
import Message from 'tdesign-miniprogram/message/index';

const { GDXZ_CUSTOM_MSEEAGE } = constant;
// eslint-disable-next-line no-undef
const app = getApp();
const api = new API()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    conversation: {
      type: Object,
      value: {},
      observer(newVal) {
        if (!newVal.conversationID) return;
        this.setData({
          conversation: newVal,
        }, () => {
          this.getMessageList(this.data.conversation);
        });
      },
    },
    order_inquiry_id:{
      type: String,
      value: "",
    },
    unreadCount: {
      type: Number,
      value: '',
      observer(newVal) {
        this.setData({
          unreadCount: newVal,
        });
      },
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    avatar: '',
    userID: '',
    isLostsOfUnread: false,
    unreadCount: '',
    conversation: {}, // 当前会话
    messageList: [],
    // 自己的 ID 用于区分历史消息中，哪部分是自己发出的
    scrollView: '',
    triggered: true,
    nextReqMessageID: '', // 下一条消息标志
    isCompleted: false, // 当前会话消息是否已经请求完毕
    messagepopToggle: false,
    messageID: '',
    checkID: '',
    selectedMessage: {},
    deleteMessage: '',
    RevokeID: '', // 撤回消息的ID用于处理对方消息展示界面
    showName: '',
    showDownJump: false,
    showUpJump: false,
    jumpAim: '',
    messageIndex: '',
    isShow: false,
    Show: false,
    UseData: '',
    chargeLastmessage: '',
    groupOptionsNumber: '',
    showNewMessageCount: [],
    messageTime: '',
    messageHistoryTime: '',
    messageTimeID: {},
    showMessageTime: false,
    showMessageHistoryTime: false,
    showMessageError: false,
    personalProfile: {},
    showPersonalProfile: false,
    resendMessage: {},
    showOnlyOnce: false,
    lastMessageSequence: '',
    isRewrite: false,
    isMessageTime: {},
    firstTime: Number,
    newArr: {},
    errorMessage: {},
    errorMessageID: '',
    typingMessage: {},
    autoToButtom: true,
    cachTime: "",
    cachRealTime: "",
    list_first_loading: false,
    message_rounds: 0,
    static_host: api.getStaticHost()
  },

  lifetimes: {
    attached() {
      
    },
    ready() {
      if (this.data.unreadCount > 12) {
        if (this.data.unreadCount > 99) {
          this.setData({
            isLostsOfUnread: true,
            showUpJump: true,
          });
        } else {
          this.setData({
            showUpJump: true,
          });
        }
      }
      
      wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.SDK_READY, function(){
        console.warn("messageList ready")
        wx.$TUIKit.getMyProfile().then((res) => {
          this.data.avatar = res.data.avatar;
          this.data.userID = res.data.userID;
        });
      },this);
      

      wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.$onMessageReceived, this);
      wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
      wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.MESSAGE_REVOKED, this.$onMessageRevoked, this);

    },

    detached() {
      // 一定要解除相关的事件绑定
      wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.$onMessageReceived);
      wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer);
      wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.MESSAGE_REVOKED, this.$onMessageRevoked);
    },
  },
  pageLifetimes: {
    show(){
      this.setData({
        list_first_loading: true
      })
      // console.log("showshowshowshowshowshowshow")
    },
    hide(){
      this.setData({
        list_first_loading: false
      })
      // console.log("hidehidehidehidehidehidehidehidehidehidehide")
    }
  },
  methods: {

    // 刷新消息列表
    refresh() {
      // console.log("refresh.......")
      this.setData({
        autoToButtom: false,
        list_first_loading: true
      })
      if (this.data.isCompleted) {
        this.setData({
          isCompleted: true,
          triggered: false,
          list_first_loading: false
        });
        return;
      }
      this.getMessageList(this.data.conversation);
      setTimeout(() => {
        this.setData({
          triggered: false,
        });
      }, 2000);
    },
    pcrefresh(){
      console.log("pcrefresh")
      wx.startPullDownRefresh()
    },
    // 获取消息列表
    getMessageList(conversation) {
      // console.log("getMessageListgetMessageListgetMessageList")
      if (!this.data.isCompleted) {
        wx.$TUIKit.getMessageList({
          conversationID: conversation.conversationID,
          nextReqMessageID: this.data.nextReqMessageID,
          count: 15,
        }).then((res) => {
          let HMM_data = res.data;//HMM
          let HMM_messageList_del = [];
          // console.log("HMM getMessageList: ", HMM_data);
          let HMM_messageList = HMM_data.messageList;
          HMM_messageList.forEach(item => {
            // let HMM_type = item.type;
            // console.log(item)
            //去除自定义消息
            // if(HMM_type == "TIMCustomElem") return;
            this.refreshMessageRounds(item)
            let checkShowAvatar = this.checkShowAvatar(item, false)
            if(!checkShowAvatar){
              item.no_avatar = true;
            }else{
              item.no_avatar = false;
            }
            
            let cath_time = this.cachMessageTime(item.time * 1000);
            item.messageTime = cath_time[0]
            item.isShowTime = cath_time[1]
            item.showMessageTime = cath_time[1]
            HMM_messageList_del.push(item);
          })
          HMM_data.messageList = HMM_messageList_del;

          // this.showMoreHistoryMessageTime(HMM_messageList_del);
          // this.showHistoryMessageTime(HMM_messageList_del);
          const { messageList } = HMM_data; // 消息列表。
          this.data.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
          this.data.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
          this.data.messageList = [...messageList, ...this.data.messageList];
          if (messageList.length > 0 && this.data.messageList.length < this.data.unreadCount) {
            this.getMessageList(conversation);
          }
          this.$handleMessageRender(this.data.messageList, messageList);
        }).then(res => {
          this.setData({
            list_first_loading: false
          })
        }).catch(error => {
          this.setData({
            list_first_loading: false
          })
        });
      }
    },
    //检测是不是横幅消息
    checkNoticeMessage(message){
      console.log("messageList checkNoticeMessage message: ", message);
      let cloudCustomData = "";
      let cloudCustomDataJson = "";
      if(message.cloudCustomData){
        cloudCustomData = message.cloudCustomData;
      }
      if(cloudCustomData){
        cloudCustomDataJson = JSON.parse(cloudCustomData);
      }
      let is_system = cloudCustomDataJson.is_system;
      if(is_system != 1){//不是系统消息直接返回
        return false
      }
      let payload = message.payload.data;
      if(!payload){//没有payload
        return false
      }
      const payloadData = JSON.parse(message.payload.data);
      if(!payloadData){
        return false
      }

      const { GDXZ_CUSTOM_MSEEAGE } = constant;
      let message_type = payloadData.message_type
      if (message_type === GDXZ_CUSTOM_MSEEAGE.BANNER_MESSAGE) {
        let message_title = payloadData.title
        let message_desc = payloadData.desc
        let message_path = payloadData.data.message_path
        this.setData({
          message_title: message_title,
          message_desc: message_desc,
          message_path: message_path,
        })
        this.showTextMessage()
      }
    },
    showTextMessage() {
      Message.info({
        context: this,
        offset: [80, 20],
        duration: 5000,
        icon: false,
        closeBtn: true,
      });
      wx.vibrateShort({
        "type": "light"
      })
    },
    handleMessagePath(){
      console.log("handleMessagePath")
      let url = this.data.message_path
      console.log(url)
      wx.switchTab({
        url: url,
      })
    },
    refreshMessageRounds(message){
      try {
        // console.log("messageList refreshMessageRounds message: ", message);
        let cloudCustomData = "";
        let cloudCustomDataJson = "";
        if(message.cloudCustomData){
          cloudCustomData = message.cloudCustomData;
        }
        if(cloudCustomData){
          cloudCustomDataJson = JSON.parse(cloudCustomData);
        }

        let order_inquiry_id = cloudCustomDataJson.order_inquiry_id;
        let now_order_inquiry_id = this.data.order_inquiry_id
        if(order_inquiry_id != now_order_inquiry_id){
          return
        }

        let payload = message.payload.data;
        if(payload){
          const payloadData = JSON.parse(message.payload.data);
          if(payloadData){
            let title = payloadData.title
            //问诊已开始，重置message_rounds = 0
            if(title && title.indexOf("问诊已开始") > -1){
              this.setData({
                message_rounds: 0
              })
              var myEventOption = {}
              myEventOption.message_rounds = 0
              this.triggerEvent('refreshMessageRounds', myEventOption)
              return
            }
          }
        }
        
        let now_message_rounds = this.data.message_rounds
        // console.log("now_message_rounds: ", now_message_rounds)
        if(cloudCustomDataJson){
          let message_rounds = cloudCustomDataJson.message_rounds;
          // console.log("message_rounds: ", message_rounds)
          if(message_rounds > now_message_rounds){
            this.setData({
              message_rounds: message_rounds
            })
            var myEventOption = {}
            myEventOption.message_rounds = message_rounds
            this.triggerEvent('refreshMessageRounds', myEventOption)
          }
        }
      } catch (error) {
        console.error(error)
      }
        
    },
    checkShowAvatar(message, refreshBaseInfo){
      // console.log("checkShowAvatar ");
      let type = message.type;
      // console.log("message type: ", type);
      let show_avatar = true;
      if(type === "TIMCustomElem"){
        const customMessage = JSON.parse(message.payload.data);
        if(Number(customMessage.message_type) != GDXZ_CUSTOM_MSEEAGE.PRESCRIBE && Number(customMessage.message_type) != GDXZ_CUSTOM_MSEEAGE.PRESCRIBE_VERIFY && Number(customMessage.message_type) != GDXZ_CUSTOM_MSEEAGE.SUGAR_CHECK){
          show_avatar = false;
        }
        if(Number(customMessage.message_type) == GDXZ_CUSTOM_MSEEAGE.TRABECULA && refreshBaseInfo){
          const title = customMessage.title
          if(title.indexOf("问诊已结束") > -1){
            setTimeout(() => {
              //收到横条消息去触发父组件getbase方法,演示1秒
              this.triggerEvent('getInquiryMessageBasic');
            }, 1000);
          }
        }
      }


      return show_avatar;
    },
    //获取问诊订单状态
    getInquiryMessageBasic(order_inquiry_id) {
      // console.log("order_inquiry_id: ", this.data.order_inquiry_id);
      api.getInquiryMessageBasic({order_inquiry_id:order_inquiry_id}).then(response => {
        let result=response.data;
        if(result.inquiry_status==3){
          wx.redirectTo({
            url: '/Pages/yishi/wenzhen_v2/wenzhen',
          })
        }
      }).then(res => {

      }).catch(errors => {console.error(errors);})
    },
    // 历史消息渲染
    $handleMessageRender(messageList, currentMessageList) {
      //console.log("order_inquiry_id:"+this.data.order_inquiry_id)
      console.log(messageList);
      // if(messageList.length>0){
      //   let last_cloudCustomData=messageList[messageList.length-1].cloudCustomData;
      //   if(last_cloudCustomData){
      //     let cloudCustomData=JSON.parse(last_cloudCustomData);
      //     this.getInquiryMessageBasic(cloudCustomData.order_inquiry_id)
      //   }
      // }
      // console.log("handleMessageRenderhandleMessageRenderhandleMessageRender");
      // this.showHistoryMessageTime(currentMessageList);
      if (messageList.length > 0) {
        if (this.data.conversation.type === '@TIM#SYSTEM') {
          this.filterRepateSystemMessage(messageList);
        } else {
          this.setData({
            messageList,
            // 消息ID前拼接字符串为了解决scroll-into-view，无法跳转以数字开头的ID。
            jumpAim: `ID-${this.filterSystemMessageID(currentMessageList[currentMessageList.length - 1].ID)}`,
          }, () => {
          });
        }
      }
    },
    // 系统消息去重
    filterRepateSystemMessage(messageList) {
      // console.log("filterRepateSystemMessage")
      const noRepateMessage = [];
      for (let index = 0;  index < messageList.length; index++) {
        if (!noRepateMessage.some(item => item && item.ID === messageList[index].ID)) {
          noRepateMessage.push(messageList[index]);
        }
      }
      this.setData({
        messageList: noRepateMessage,
      });
    },
    // 消息已读更新
    $onMessageReadByPeer(event) {
      this.updateReadByPeer(event);
    },
    // 更新已读更新
    // updateReadByPeer(event) {
    //   console.log("updateReadByPeerupdateReadByPeer")
    //   event.data.forEach((item) => {
    //     const index = this.data.messageList.findIndex(element => element.ID === item.ID);
    //     this.data.messageList[index] = item;
    //     this.setData({
    //       messageList: this.data.messageList,
    //     });
    //   });
    // },

    // 收到的消息
    $onMessageReceived(value) {

      let autoToButtom = this.data.autoToButtom;
      // console.log("autoToButtom:", autoToButtom)
      const message = value.data[0];
      //检测是不是横幅消息
      this.checkNoticeMessage(message)
      //更新会话数
      this.refreshMessageRounds(message)
      if(message.flow == 'out'){
        message.isRead = false;
      }
      if(!this.checkShowAvatar(message, true)){
        message.no_avatar = true;
      }
      wx.$TUIKit.setMessageRead({ conversationID: this.data.conversation.conversationID }).then(() => {
        logger.log('| MessageList | setMessageRead | ok');
      });
      // console.log('| MessageList | setMessageRead | ok');
      // console.log('message cloudCustomData：', message.cloudCustomData);
      const { BUSINESS_ID_TEXT, MESSAGE_TYPE_TEXT } = constant;
      // this.messageTimeForShow(message);

      let cath_time = this.cachMessageTime(message.time * 1000);
      message.messageTime = cath_time[0]
      message.isShowTime = cath_time[1]
      message.showMessageTime = cath_time[1]

      this.setData({
        UseData: value,
      });
      value.data.forEach((item) => {
        if (item.conversationID !== this.data.conversation.conversationID) {
          return;
        }
        // 判断收到的消息是否是正在输入状态消息。由于正在输入状态消息是自定义消息，需要对自定义消息进行一个过滤，是自定义消息但不是正在输入状态消息，则新消息未读数加1，不是自定义消息则新消息未读数直接加1
        if (this.data.messageList.length > 12 && !message.isRead) {
          try {
            const typingMessage = JSON.parse(item.payload.data);
            this.setData({
              typingMessage,
            });
          } catch (error) {
          }
          if ((item.type === MESSAGE_TYPE_TEXT.TIM_CUSTOM_ELEM && this.data.typingMessage.businessID !== BUSINESS_ID_TEXT.USER_TYPING) || item.type !== MESSAGE_TYPE_TEXT.TIM_CUSTOM_ELEM) { 

            if(!autoToButtom){
              this.data.showNewMessageCount.push(message);
              this.setData({
                showNewMessageCount: this.data.showNewMessageCount,
                showDownJump: true,
              });
            }
            
          }
        } else {
          this.setData({
            showDownJump: false,
          });
        }
      });
      // 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
      // 将收到的消息存入messageList之前需要进行过滤，正在输入状态消息不用存入messageList.
      const list = [];
      value.data.forEach((item) => {
        if (item.conversationID === this.data.conversation.conversationID && item.type === MESSAGE_TYPE_TEXT.TIM_CUSTOM_ELEM) {
          try {
            const typingMessage = JSON.parse(item.payload.data);
            if (typingMessage.businessID !== BUSINESS_ID_TEXT.USER_TYPING) {
              list.push(item);
            } else {
              this.triggerEvent('typing', {
                typingMessage,
              });
            }
          } catch (error) {
          }
        } else if (item.conversationID === this.data.conversation.conversationID) {
          list.push(item);
        }
      });
      this.data.messageList = this.data.messageList.concat(list);
      this.setData({
        messageList: this.data.messageList,
        groupOptionsNumber: this.data.messageList.slice(-1)[0].payload.operationType,
      });
      if (this.data.conversation.type === 'GROUP') {
        this.triggerEvent('changeMemberCount', {
          groupOptionsNumber: this.data.messageList.slice(-1)[0].payload.operationType,
        });
      }

      let jumpAim = `ID-${this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - 1].ID)}`;
      // console.log("jumpAim:", jumpAim);

      // console.log("message.from: ", message.from)
      // console.log("conversation: ", this.data.conversation)
      // console.log("conversation: ", this.data.conversation.lastMessage.from)
      if(autoToButtom && message.conversationID === this.data.conversation.conversationID){
        this.setData({
          jumpAim: jumpAim
        })
      }
      //主动跳到 消息跳转到最新
      // this.handleJumpNewMessage()
    },
    // 自己的消息上屏
    updateMessageList(message) {
      // console.log("自己的消息上屏 updateMessageList: ", message);
      // console.log(message);
      //自己的消息有头像
      if(!this.checkShowAvatar(message, false)){
        message.no_avatar = true;
      }
      if (message.conversationID !== this.data.conversation.conversationID) return;
      wx.$TUIKit.setMessageRead({ conversationID: this.data.conversation.conversationID }).then(() => {
        logger.log('| MessageList | setMessageRead | ok');
      });
      const { BUSINESS_ID_TEXT, MESSAGE_TYPE_TEXT } = constant;
      // this.$onMessageReadByPeer();
      // this.messageTimeForShow(message);

      let cath_time = this.cachMessageTime(message.time * 1000);
      message.messageTime = cath_time[0]
      message.isShowTime = cath_time[1]
      message.showMessageTime = cath_time[1]

      if (message.type === MESSAGE_TYPE_TEXT.TIM_CUSTOM_ELEM) {
        const typingMessage = JSON.parse(message.payload.data);
        if (typingMessage.businessID === BUSINESS_ID_TEXT.USER_TYPING) {
          this.setData({
            messageList: this.data.messageList,
          });
        } else {
          this.data.messageList.push(message);
        }
      } else {
        // console.log(message)
        this.data.messageList.push(message);
      }
      this.setData({
        lastMessageSequence: this.data.messageList.slice(-1)[0].sequence,
        messageList: this.data.messageList,
        jumpAim: `ID-${this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - 1].ID)}`,
      }, () => {
        this.setData({
          messageList: this.data.messageList,
        });
      });
    },
    refreshMessageStatus(message){
      console.log("MessageList refreshMessageStatus", message)
      this.setData({
        messageList: this.data.messageList,
      }, () => {
        this.setData({
          messageList: this.data.messageList,
        });
      });
    },
    // 兼容 scrollView
    filterSystemMessageID(messageID) {
      const index = messageID.indexOf('@TIM#');
      const groupIndex = messageID.indexOf('@TGS#');
      if (index === 0) {
        messageID =  messageID.replace('@TIM#', '');
      }
      if (groupIndex === 0) {
        messageID =  messageID.replace('@TGS#', '');
      }
      return messageID;
    },
    // 获取消息ID
    handleLongPress(e) {
      // for (let index = 0; index < this.data.messageList.length; index++) {
        
        // if (this.data.messageList[index].status === 'success') {
          const { index } = e.currentTarget.dataset;
          // let message = this.data.messageList[index];
          // console.log(message)
          // if(message.type === 'TIMCustomElem'){
          //   return
          // }

          let selectedMessage = this.data.messageList[index]
          if(selectedMessage.type === 'TIMCustomElem'){
            return
          }
          if(selectedMessage.type === 'TIMImageElem'){
            return
          }
          this.setData({
            messageID: e.currentTarget.id,
            selectedMessage: selectedMessage,
            Show: true,
          });
          wx.vibrateShort({
            "type": "heavy"
          })

        // }
      // }
    },
    // 更新 messagelist
    updateMessageByID(deleteMessageID) {
      // console.log("updateMessageByIDupdateMessageByIDupdateMessageByID")
      const { messageList } = this.data;
      const deleteMessageArr = messageList.filter(item => item.ID === deleteMessageID);
      this.setData({
        messageList,
      });
      return deleteMessageArr;
    },
    // 删除消息
    deleteMessage() {
      wx.aegis.reportEvent({
        name: 'messageOptions',
        ext1: 'messageOptions-delete',
        ext2: wx.$chat_reportType,
        ext3: wx.$chat_SDKAppID,
      });
      wx.$TUIKit.deleteMessage([this.data.selectedMessage])
        .then((imResponse) => {
          this.updateMessageByID(imResponse.data.messageList[0].ID);
          wx.showToast({
            title: '删除成功!',
            duration: 800,
            icon: 'none',
          });
        })
        .catch(() => {
          wx.showToast({
            title: '删除失败!',
            duration: 800,
            icon: 'error',
          });
        });
    },
    // 撤回消息
    revokeMessage() {
      wx.aegis.reportEvent({
        name: 'messageOptions',
        ext1: 'messageOptions-revoke',
        ext2: wx.$chat_reportType,
        ext3: wx.$chat_SDKAppID,
      });
      wx.$TUIKit.revokeMessage(this.data.selectedMessage)
        .then((imResponse) => {
          this.setData({
            resendMessage: imResponse.data.message,
          });
          this.updateMessageByID(imResponse.data.message.ID);
          // 消息撤回成功
        })
        .catch((imError) => {
          wx.showToast({
            title: '超过2分钟消息不支持撤回',
            duration: 800,
            icon: 'none',
          }),
          this.setData({
            Show: false,
          });
          // 消息撤回失败
          console.warn('revokeMessage error:', imError);
        });
    },

    // 撤回消息重新发送
    resendMessage(e) {
      this.triggerEvent('resendMessage', {
        message: e.detail.message,
      });
    },
    // 关闭弹窗
    handleEditToggleAvatar() {
      this.setData({
        Show: false,
      });
    },
    // 向对方通知消息撤回事件
    $onMessageRevoked(event) {
      this.updateMessageByID(event.data[0].ID);
    },
    // 复制消息
    copyMessage() {
      wx.aegis.reportEvent({
        name: 'messageOptions',
        ext1: 'messageOptions-copy',
        ext2: wx.$chat_reportType,
        ext3: wx.$chat_SDKAppID,
      });
      wx.setClipboardData({
        data: this.data.selectedMessage.payload.text,
        success() {
          wx.getClipboardData({
            success(res) {
              logger.log(`| TUI-chat | message-list | copyMessage: ${res.data} `);
            },
          });
        },
      });
      this.setData({
        Show: false,
      });
    },
    // 消息跳转到最新
    handleJumpNewMessage() {
      // console.log("handleJumpNewMessage")
      this.setData({
        jumpAim: `ID-${this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - 1].ID)}`,
        showDownJump: false,
        showNewMessageCount: [],
      });
    },
    // 消息跳转到最近未读
    handleJumpUnreadMessage() {
      // console.log("handleJumpUnreadMessage")
      if (this.data.unreadCount > 15) {
        this.getMessageList(this.data.conversation);
        this.setData({
          jumpAim: `ID-${this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - this.data.unreadCount].ID)}`,
          showUpJump: false,
        });
      } else {
        this.getMessageList(this.data.conversation);
        this.setData({
          jumpAim: `ID-${this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - this.data.unreadCount].ID)}`,
          showUpJump: false,
        });
      }
    },
    //myscroll 自定义滑动事件
    myscroll(e){
      // console.log(e.detail.deltaY,e.detail.scrollTop)
    },
    // 滑动到最底部置跳转事件为false
    scrollHandler() {
      // console.log("触底了")
      this.setData({
        jumpAim: `ID-${this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - 1].ID)}`,
        showDownJump: false,
        autoToButtom: true
      });
    },
    // 删除处理掉的群通知消息
    changeSystemMessageList(event) {
      this.updateMessageByID(event.detail.message.ID);
    },
    // 展示消息时间
    messageTimeForShow(message) {
      // console.log("messageTimeForShow")
      // const interval = 5 * 60 * 1000;
      const interval = 5 * 60;
      const nowTime = Math.floor(message.time / 10) * 10 * 1000;
      // console.log("nowTime: ", nowTime)
      if (this.data.messageList.length > 0) {
        const lastTime = this.data.messageList.slice(-1)[0].time * 1000;
        // console.log("nowTime  - lastTime=", (nowTime  - lastTime))
        if (nowTime  - lastTime > interval) {
          Object.assign(message, {
            isShowTime: true,
          }),
          this.data.messageTime = this.cachMessageTime(nowTime)[0];
          let messageTime = this.cachMessageTime(nowTime);
          message.messageTime = messageTime[0];
          message.showMessageTime = messageTime[1];
          // console.log("dayjs(nowTime): ", dayjs(nowTime))
          this.setData({
            messageTime: this.cachMessageTime(nowTime)[0],
            showMessageTime: true,
          });
        }
      }
    },
    // 渲染历史消息时间
    showHistoryMessageTime(messageList) {
      const cut = 5 * 60;
      for (let index = 0; index < messageList.length; index++) {
        const thismessagetime = Math.floor(messageList[index].time / 10) * 10 * 1000;
        let messageTime = this.cachMessageTime(thismessagetime);
        messageList[index].messageTime = messageTime[0]
        messageList[index].showMessageHistoryTime = messageTime[1]
        this.setData({
          messageHistoryTime: messageTime[0],
          showMessageHistoryTime: messageTime[1]
        });
          
      }
    },
    // 拉取更多历史消息渲染时间
    showMoreHistoryMessageTime(messageList) {
      if (messageList.length > 0) {
        const showHistoryTime = messageList[0].time * 1000;
        Object.assign(messageList[0], {
          isShowMoreHistoryTime: true,
        }),
        this.data.newArr[messageList[0].ID] = this.cachMessageTime(showHistoryTime)[0];
        this.setData({
          newArr: this.data.newArr,
        });
      }
    },
    cachMessageTime(messageTime){
      // console.log("cachMessageTime messageTime 参数:", messageTime)

      let cachRealTime = this.data.cachRealTime
      if(cachRealTime > messageTime){
        return ["", false]
      }
      this.setData({
        cachRealTime: messageTime
      })
      let time = wechatTimeFormat(messageTime)
      // console.log("cachMessageTime: ", time)
      if(time){
        // let nowCachTime = time.split(":")[0]  //小时级别
        let nowCachTime = time
        let cachTime = this.data.cachTime
        // console.log("nowCachTime: ", nowCachTime)
        // console.log("cachTime: ", cachTime)
        if(nowCachTime == cachTime){
          return [time, false]
        }else{
          this.setData({
            cachTime: nowCachTime
          })
          return [time, true]
        }
      }
      return [time, false]
    },
    // 消息发送失败
    sendMessageError(event) {
      this.setData({
        errorMessage: event.detail.message,
        errorMessageID: event.detail.message.ID,
      });
      const errorCode = event.detail.showErrorImageFlag;
      const { MESSAGE_ERROR_CODE, TOAST_TITLE_TEXT } = constant;
      switch (errorCode) {
        case MESSAGE_ERROR_CODE.DIRTY_WORDS:
          this.showToast(TOAST_TITLE_TEXT.DIRTY_WORDS);
          break;
        case MESSAGE_ERROR_CODE.UPLOAD_FAIL:
          this.showToast(TOAST_TITLE_TEXT.UPLOAD_FAIL);
          break;
        case MESSAGE_ERROR_CODE.REQUESTOR_TIME || MESSAGE_ERROR_CODE.DISCONNECT_NETWORK:
          this.showToast(TOAST_TITLE_TEXT.CONNECT_ERROR);
          break;
        case MESSAGE_ERROR_CODE.DIRTY_MEDIA:
          this.showToast(TOAST_TITLE_TEXT.DIRTY_MEDIA);
          break;
        default:
          break;
      }
    },
    // 消息发送失败后重新发送
    ResendMessage() {
      const { MESSAGE_ERROR_CODE, TOAST_TITLE_TEXT } = constant;
      wx.showModal({
        content: '确认重发该消息？',
        success: (res) => {
          if (!res.confirm) {
            return;
          }
          wx.$TUIKit.resendMessage(this.data.errorMessage) // 传入需要重发的消息实例
            .then(() => {
              this.showToast(TOAST_TITLE_TEXT.RESEND_SUCCESS);
              this.setData({
                showMessageError: false,
              });
            })
            .catch((imError) => {
              switch (imError.code) {
                case MESSAGE_ERROR_CODE.DIRTY_WORDS:
                  this.showToast(TOAST_TITLE_TEXT.DIRTY_WORDS);
                  break;
                case MESSAGE_ERROR_CODE.UPLOAD_FAIL:
                  this.showToast(TOAST_TITLE_TEXT.UPLOAD_FAIL);
                  break;
                case MESSAGE_ERROR_CODE.REQUESTOR_TIME || MESSAGE_ERROR_CODE.DISCONNECT_NETWORK:
                  this.showToast(TOAST_TITLE_TEXT.CONNECT_ERROR);
                  break;
                case MESSAGE_ERROR_CODE.DIRTY_MEDIA:
                  this.showToast(TOAST_TITLE_TEXT.DIRTY_MEDIA);
                  break;
                default:
                  break;
              }
            });
        },
      });
    },

    showToast(toastTitle) {
      if (this.data.showMessageError) {
        wx.showToast({
          title: toastTitle,
          duration: 800,
          icon: 'none',
        });
      } else {
        this.setData({
          showMessageError: true,
        });
        wx.showToast({
          title: toastTitle,
          duration: 800,
          icon: 'none',
        });
      }
    },
    // 点击购买链接跳转
    handleJumpLink(e) {
      if (app?.globalData?.reportType !== constant.OPERATING_ENVIRONMENT) return;
      const { BUSINESS_ID_TEXT }  = constant;
      const dataLink = JSON.parse(e.currentTarget.dataset.value.payload.data);
      if (dataLink.businessID === BUSINESS_ID_TEXT.ORDER || dataLink.businessID === BUSINESS_ID_TEXT.LINK) {
        const url = `/pages/TUI-User-Center/webview/webview?url=${dataLink.link}&wechatMobile`;
        wx.navigateTo({
          url: encodeURI(url),
        });
      }
    },
    goMedinceList(){
     wx.navigateTo({
       url: '/Pages/yishi/medince_list/index',
     })
    },
  },

});
