<template>
  <div
    v-show="showChat"
    class="chat-wrap"
    :class="!toggleChatSize ? 'shrink64' : ''"
  >
    <section
      v-show="toggleChatSize"
      id="screenSet"
      class="component-content"
    >
      <article
        v-loadmore="getOldMSGHistory"
        class="center BSListWraper"
      >
        <section class="c-header">
          <div class="header-line">
            <div class="c-header-l">
              <span class="num">{{ currentChat.diagnoseLogId }}</span>
              <span class="dep">&nbsp;{{ currentChat.department }}</span>
            </div>
            <div class="c-header-edit">
              <span
                class="edit-imgclose"
                @click="overFn"
              > 结束问诊 </span>
              <span
                class="edit-img"
                @click="closeChat"
              >
                <img
                  src="../../assets/image/IM/im_close2.png"
                  alt
                >
              </span>
              <span
                class="edit-img"
                @click="toggleChatModal"
              >
                <img
                  src="../../assets/image/IM/im_small.png"
                  alt
                >
              </span>
            </div>
          </div>
          <div class="header-line" />
        </section>
        <diagnosis-Live :doctor-img="doctorImg" />
        <section
          id="msgContentId"
          class="msg-content scroll-box"
        >
          <article
            v-for="(item, index) in messageList"
            :key="index"
          >
            <!-- sendOrReceive 为true在右边 -->
            <div
              class="msg-item"
              :class="{ cr: item.sendOrReceive }"
            >
              <div
                v-if="item.showType != 10"
                class="msg-item-img"
              >
                <img
                  :src="item.avatarImg"
                  alt
                >
              </div>
              <div
                class="msg-item-detail"
                :class="{ line: item.showType == 10 }"
              >
                <span
                  v-if="item.showType != 10"
                  class="mid-time"
                >{{ item.name }} {{ item.timestampStr }}</span>
                <div class="send-warpper">
                  <img
                    v-if="item.sendOrReceive && item.isShowErrorIcon"
                    class="icon"
                    src="../../assets/image/IM/icon-no-send.png"
                    alt
                  >
                  <img
                    v-if="item.sendOrReceive && item.isShowLoadingIcon"
                    class="icon ld"
                    src="../../assets/image/IM/loading-icon-new.png"
                    alt
                  >
                  <div
                    v-if="item.showType == 1"
                    class="mid-text-wrapper"
                    style="max-width: 520px"
                  >
                    <div class="mid-text">
                      {{ item.text }}
                    </div>
                  </div>
                  <div
                    v-if="item.showType == 2"
                    v-viewer
                    class="mid-img"
                  >
                    <div class="img-box">
                      <img
                        class="img"
                        :src="item.url"
                        :style="{
                          width: item.newW + 'px',
                          height: item.newH + 'px',
                        }"
                        alt
                      >
                    </div>
                  </div>
                  <div
                    v-if="item.showType == 3"
                    class="mid-pdf"
                    @click="openPDF(item)"
                  >
                    <div class="midp-left">
                      <span class="name">{{ item.text | shortName(23) }}</span>
                      <span class="size">{{ fileSizeChange(item.size) }}</span>
                    </div>
                    <div class="midp-icon">
                      <img
                        src="../../assets/image/IM/icon-pdf.png"
                        alt
                      >
                    </div>
                  </div>
                  <div
                    v-if="item.showType == 4"
                    class="mid-text"
                  >
                    {{ item.text }}
                    <span class="link">{{ item.suffix }}</span>
                  </div>
                  <div
                    v-if="item.showType == 5"
                    class="mid-text no-support"
                  >
                    <img
                      src="../../assets/image/IM/icon-warning-circle.png"
                      alt
                    >
                    <span>该消息类型PC端暂不支持</span>
                  </div>
                  <!-- 语音消息 -->
                  <div
                    v-if="item.showType == 6"
                    class="audio-box"
                  >
                    <audio controls>
                      <source
                        :src="item.url"
                        type="audio/mpeg"
                      >
                    </audio>
                  </div>
                  <!-- 问诊开始与病例模块 -->
                  <div
                    v-if="item.showType == 7"
                    class="diagnosis-box"
                  >
                    <div class="title">
                      {{ item.title }}
                    </div>
                    <div class="dia-text">
                      <span class="label">患者：</span>
                      <span>{{ item.text.patientName }}
                        {{ item.text.sex == 1 ? '男' : '女' }}
                        {{ item.text.age }}岁</span>
                    </div>
                    <div class="dia-text">
                      <span class="label">病情描述：</span>
                      <span>{{ item.text.illnessDetail }}</span>
                    </div>
                  </div>
                  <!-- 预约时间模块 -->
                  <div
                    v-if="item.showType == 8"
                    class="time-box"
                  >
                    <div class="title">
                      {{ item.title }}
                    </div>
                    <div class="time">
                      {{ item.text.timeStr }}
                    </div>
                    <div class="time-text">
                      {{ item.text.tips }}
                    </div>
                  </div>
                  <!-- 音视频与IM的交互 -->
                  <div
                    v-if="item.showType == 9"
                    class="live-box"
                  >
                    <div class="live-notice">
                      {{ item.text }}
                    </div>
                  </div>
                  <!-- 问诊结束 -->
                  <div
                    v-if="item.showType == 10"
                    class="diagnosis-end"
                  >
                    <div class="split-line">
                      {{ item.text }}
                    </div>
                  </div>
                  <!-- 医生建议模块 -->
                  <div
                    v-if="item.showType == 11"
                    class="suggession-box"
                  >
                    <div class="title">
                      {{ item.title }}
                    </div>
                    <div class="suggession-text">
                      {{ item.text }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <span
              v-if="item.sendOrReceive && item.isShowErrorMsg"
              class="error-mg"
              :class="{ mr: item.sendOrReceive }"
            >{{ item.errorMsg }}</span>
          </article>
        </section>
        <section class="c-bottom">
          <el-input
            v-model="sendText"
            type="textarea"
            class="c-bottom-input"
            placeholder="请输入内容"
            maxlength="499"
          />
          <div class="cb-icon-wrapper">
            <el-upload
              class="bg-uploader"
              action="#"
              accept=".jpg, .png, .pdf"
              :show-file-list="false"
              :before-upload="beforeUploadFile"
            >
              <img
                src="../../assets/image/IM/im_sendfile.png"
                alt
              >
            </el-upload>
            <img
              src="../../assets/image/IM/im_sendvedio.png"
              alt
              @click="preSendLinkMsg"
            >
          </div>
          <el-button
            size="small"
            class="send-btn"
            :class="{ active: canSend }"
            @click="sendTextMsg"
          >
            发送
          </el-button>
        </section>
      </article>
    </section>

    <div
      v-show="!toggleChatSize"
      class="wenzenbox"
      @click="toggleChatModal"
    >
      <div class="wenzenbox-header">
        <img
          src="../../assets/image/IM/wenzhenicon.png"
          alt=""
        >
      </div>
    </div>
    <!-- 选择链接弹窗 -->
    <el-dialog
      title="选择链接"
      :modal="false"
      :show-close="true"
      :visible.sync="showSelectDialog"
      :close-on-click-modal="false"
      width="500px"
      class="link-form"
    >
      <el-form
        ref="linkFormRef"
        :rules="rules"
        :model="linkForm"
        label-width="100px"
      >
        <el-form-item label="普通文本">
          <el-col :span="20">
            <el-input
              v-model="linkForm.remark"
              size="small"
              maxlength="300"
            />
          </el-col>
        </el-form-item>
        <el-form-item
          label="链接文案"
          prop="info"
        >
          <el-col :span="20">
            <el-input
              v-model="linkForm.info"
              size="small"
              maxlength="100"
            />
          </el-col>
        </el-form-item>
        <el-form-item
          label="链接地址"
          prop="url"
        >
          <el-col :span="20">
            <el-select
              v-model="linkForm.url"
              size="small"
              style="width: 300px"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in linkList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="text-align: right"
      >
        <el-button
          size="small"
          @click="showSelectDialog = false"
        >
          取 消
        </el-button>
        <el-button
          size="small"
          type="primary"
          @click="sendLinkMsg"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <alert ref="alert" />
  </div>
</template>
<script>
  import alert from '@/components/common/alert.vue';
  import diagnosisLive from './diagnosis-live';
  import { doUpload, getFilePath } from '@/utils/qiniu-util';
  import { openLoading, closeLoading, betaHandle } from '@/utils/utils';
  import { getPicaKFAccid, getPhomeDemain } from '@/utils';
  import {
    getQueryTemplate,
    getMemberList,
    messageForward,
    messageHistory,
    messageSend,
    diagnoseEndCall,
  } from '@/api/diagnosis';

  import { createNamespacedHelpers } from 'vuex';
  const { mapState } = createNamespacedHelpers('main');
  const CONTAINER_HEIGHT = 700;
  let forwardMsgIntervalId = null,
      continueIntervalId = null,
      autoCompletionIntervalId = null,
      cacheMap = {};
  let _this = null;
  export default {
    components: {
      diagnosisLive,
      alert,
    },
    props: {
      showChat: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        curmbFirst: '云鹊客服',
        curmbSecond: '当前会话',
        sendText: '',
        sessionListData: {
          currentTimestamp: 0,
          myTaskCount: 0,
          sessionList: [],
          waitingTaskCount: 0,
        },
        currentContinueTimes: 0,
        currentSessionIndex: 0,
        currentSession: {},
        currentTaskLogId: '',
        picakfAccId: '',
        historyTimestamp: 0,
        realTimestamp: 0,
        containerHeight: CONTAINER_HEIGHT,
        showSelectDialog: false,
        linkForm: {
          remark: '',
          info: '',
          url: '',
        },
        linkList: [],
        messageList: [],
        rules: {
          info: [
            { required: true, message: '请填写链接显示文案', trigger: 'blur' },
          ],
          url: [{ required: true, message: '请选择链接', trigger: 'change' }],
        },
        imgWidth: 0,
        imgHeight: 0,
        imgProportion: 0,
        hasNoHistoryData: false,
        tid: '',
        teamMemberList: [],
        doctorName: '',
        doctorImg: '',
        toggleChatSize: true,
        loadingListToggle: true,
        loadingInstanceToggle: null,
      };
    },
    computed: {
      ...mapState({
        currentChat: (state) => state.currentChat,
      }),
      canSend() {
        return !!this.sendText;
      },
    },

    watch: {
      // 监听消息列表的变化，添加sessionFlag(会话结束标志)
      messageList: {
        handler(newMsgList) {
          const l = newMsgList.length;
          if (l >= 2) {
            for (let i = 1; i < l; i++) {
              if (newMsgList[i - 1].taskLogId !== newMsgList[i].taskLogId) {
                newMsgList[i].sessionFlag = true;
              }
            }
          }
        },
        deep: true,
      },
      // 监听到有变化，就缓存一下
      sendText(newText) {
        cacheMap[this.currentSession.id] = newText || '';
      },
      currentChat(newVal, oldVal) {
        if (newVal !== oldVal && newVal.imTeamId) {
          this.messageList = [];
          this.chatInit();
        }
      },
      showChat(nv) {
        if (nv) {
          this.scrollToTOLoad();
        } else {
          this.messageList = [];
        }
      },
    },

    created() {
      console.log('diagnoseLogId', this.currentChat);
    },

    mounted() {
      cacheMap = {};
    },

    beforeDestroy() {
      forwardMsgIntervalId && clearInterval(forwardMsgIntervalId);
      autoCompletionIntervalId && clearInterval(autoCompletionIntervalId);
    },

    methods: {
      chatInit() {
        _this = this;
        this.picakfAccId = getPicaKFAccid();
        const { imTeamId } = this.currentChat;
        this.tid = imTeamId;
        this.getFiveContentList();
        autoCompletionIntervalId && clearInterval(autoCompletionIntervalId);
        autoCompletionIntervalId = setInterval(() => {
          this.autoCompletionInterval();
        }, 2000);

        // 监听键盘的回车按键（回车时发送消息，并阻止其在textarea中的回车换行行为）
        document.onkeydown = function (ev) {
          var event = ev || event;
          if (event.keyCode == 13) {
            _this.sendTextMsg();
            event.preventDefault();
          }
        };
        this.getMembersList(); // 获取群聊成员信息
      },
      // 含有敏感信息的消息，自行补全提示文案
      // 每30秒监测敏感信息
      autoCompletionInterval() {
        if (!this.messageList.length) return;
        // 将带有loading的消息转成失败的
        this.messageList.forEach((item) => {
          if (item.isShowLoadingIcon) {
            item.isShowLoadingIcon = false;
            item.isShowErrorIcon = true;
          }
        });
        let flag = false,
            msg;
        for (let i = 0; i < this.messageList.length; i++) {
          msg = this.messageList[i];
          if (msg.isShowErrorIcon && !msg.isShowErrorMsg) {
            flag = true;
            break;
          }
        }
        if (flag) {
          this.getMSGForwardForAC(msg);
        }
      },

      // 查询群组成员列表
      getMembersList() {
        getMemberList({ tid: this.tid }).then((res) => {
          if (res.code === '000000') {
            this.teamMemberList = res.data; // 1 问诊医生 2接诊医生 3居民 4其他
            this.doctorName = this.teamMemberList[0].name;
            this.doctorImg = this.teamMemberList[0].avatarImageUrl;
            this.getMSGHistory(); // 查询群聊历史消息
          }
        });
      },

      // 查询医生和居民的消息 - 向前查找
      getMSGForwardForAC(msg) {
        const params = {
          includeFlag: 0,
          lastMsgTimestamp: msg.realTimestamp,
          limit: 50,
          tid: this.tid,
        };
        messageForward(params).then((res) => {
          if (res.code === '000000') {
            this.contactForwardMessage(res.data, false);
          }
        });
      },

      // 获取元素
      getElmByID(elmId) {
        return document.getElementById(elmId);
      },

      // 查询医生和居民的消息历史(下拉刷新时调用)
      getOldMSGHistory() {
        if (this.hasNoHistoryData) return;
        const params = {
          includeFlag: 0, // 不带本条消息
          lastMsgTimestamp: this.historyTimestamp,
          limit: 20,
          tid: this.tid,
        };
        messageHistory(params)
          .then((res) => {
            if (res.code === '000000') {
              // 将新消息合并到之前的消息中, 并且重置最后一条消息
              if (res.data && res.data.length > 0) {
                this.convertMessageList(res.data, 3);
                this.hasNoHistoryData = false;
              } else {
                this.hasNoHistoryData = true;
              }
            } else {
              this.$message({
                message: res.message,
                type: 'error',
              });
            }
            this.loadingListToggle = true;
          })
          .finally(() => {
            this.loadingListToggle = true;
          });
      },

      // 查询医生和居民的消息历史(第一次进来时就调用)
      getMSGHistory() {
        const params = {
          includeFlag: 1, // 带本条消息
          limit: 20,
          tid: this.tid,
        };
        messageHistory(params)
          .then((res) => {
            if (res.code === '000000') {
              if (res.data && res.data.length > 0) {
                this.convertMessageList(res.data, 1);
                this.hasNoHistoryData = false;
              } else {
                this.hasNoHistoryData = true;
              }
            } else {
              this.$message({
                message: res.message,
                type: 'error',
              });
            }
            this.loadingListToggle = true;
          })
          .finally(() => {
            this.loadingListToggle = true;
          });
      },

      // 查询医生和居民的消息 - 向前查找
      // 将获取消息列表插入到当前消息列表的最后
      getMSGForward() {
        const params = {
          includeFlag: 0,
          lastMsgTimestamp: this.realTimestamp,
          limit: 20,
          tid: this.tid,
        };
        messageForward(params).then((res) => {
          if (res.code === '000000') {
            this.convertMessageList(res.data, 2);
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            });
          }
        });
      },

      /* 转换消息格式
    处理的消息类型只有5种：
    type == TEXT(showType:1)
    type == image 或 picture(showType:2)
    type == custom时，18: PDF文件(showType:3); 19: 链接信息(showType:4); 1 ~ 17: 不支持的消息类型(showType:5);
    directFlag 1: 第一次取数据; 2: 拼接实时消息(push); 3: 拼接历史消息(unshift);
    */
      convertMessageList(messageList, directFlag = 1) {
        messageList.sort((a, b) => {
          return a.timestamp - b.timestamp;
        });
        let msg = null,
            content = null,
            text = '',
            suffix = '',
            showType = 1,
            size = 0,
            url = '',
            title = '';
        const cMessageList = [];
        messageList.forEach((rawMsg) => {
          text = '';
          suffix = '';
          showType = 1;
          size = 0;
          url = '';
          title = '';
          msg = Object.assign({}, rawMsg);
          msg.sendOrReceive = rawMsg.fromAccId === this.picakfAccId; // 判断消息是显示在左边还是右边, true 右
          // msg.avatarImg = msg.sendOrReceive ? this.kfAvatar : this.currentSession.avatarImageUrl;
          for (let i = 0; i < this.teamMemberList.length; i++) {
            if (rawMsg.fromAccId == this.teamMemberList[i].accId) {
              msg.avatarImg = this.teamMemberList[i].avatarImageUrl;
              msg.name = this.teamMemberList[i].name;
              break;
            }
          }
          if (msg.type.toLowerCase() == 'custom') {
            content = JSON.parse(msg.content);
            text = content.content;
            if (content.bizType == -1 || content.bizType == 27) {
              // 系统消息：消息由于违规未发送成功（可以不处理）
              showType = -1;
              text = content.content;
            } else if (content.bizType == 18) {
              // PDF
              showType = 3;
              text = content.name;
              size = content.size;
              url = content.url;
            } else if (content.bizType == 19) {
              // 链接
              showType = 4;
              text = content.content;
              suffix = content.suffix;
            } else if (content.bizType == 22) {
              // 病例
              showType = 7;
              title = content.title;
              text = JSON.parse(content.content);
            } else if (content.bizType == 23) {
              // 预约时间
              showType = 8;
              title = content.title;
              text = JSON.parse(content.content);
            } else if (content.bizType == 24) {
              // 音视频与IM交互
              showType = 9;
              text = content.content;
            } else if (content.bizType == 25) {
              // 本次问诊结束
              showType = 10;
              text = content.content;
            } else if (content.bizType == 26) {
              // 医生建议
              showType = 11;
              title = content.title;
              text = content.content;
            } else {
              showType = 5;
            }
          } else if (
            msg.type.toLowerCase() == 'image' ||
            msg.type.toLowerCase() == 'picture'
          ) {
            // 图片
            content = JSON.parse(msg.content);
            url = content.url;
            text = content.name;
            showType = 2;
            this.imgSizeHandleNew(msg, content.w, content.h);
          } else if (msg.type.toLowerCase() == 'audio') {
            // 语音
            content = JSON.parse(msg.content);
            url = content.url;
            showType = 6;
          } else {
            showType = 1; // 文本
            text = msg.content;
          }
          msg.title = title;
          msg.text = text;
          msg.showType = showType;
          msg.suffix = suffix;
          msg.size = size;
          msg.url = url;
          msg.sessionFlag = false;
          cMessageList.push(msg);
        });

        if (directFlag === 1) {
          this.messageList = [];
          this.$forceUpdate();
          forwardMsgIntervalId && clearInterval(forwardMsgIntervalId);
          this.messageList = cMessageList;
          this.$forceUpdate();
          setTimeout(() => {
            this.$nextTick(() => {
              const scrollBoxDom = document.querySelector('.scroll-box');
              scrollBoxDom.scrollTop = scrollBoxDom.scrollHeight;
            });
          }, 100);
          this.currentContinueTimes =
            this.sessionListData.currentTimestamp -
            this.currentSession.handleStartTime;
          continueIntervalId && clearInterval(continueIntervalId);
          continueIntervalId = setInterval(() => {
            this.currentContinueTimes += 1000;
          }, 1000);
        // 最新消息，要合并CUSTOM类型中，bizType是-1的数据（系统消息）
        } else if (directFlag === 2) {
          this.contactForwardMessage(cMessageList);
        } else {
          if (cMessageList.length) {
            this.messageList.unshift(...cMessageList);
            this.$nextTick(() => {
              const scrollBoxDom = document.querySelector('.scroll-box');
              scrollBoxDom.scrollTop = 1000;
            });
          }
        }
        if (this.messageList.length) {
          this.historyTimestamp = this.messageList[0].timestamp;
          const timestamp =
            this.messageList[this.messageList.length - 1].timestamp;
          if (timestamp) {
            this.realTimestamp = timestamp;
          }
        }

        // 自己发送消息时，暂时不刷新消息
        if (directFlag == 1) {
          forwardMsgIntervalId = setInterval(() => {
            this.getMSGForward();
          }, 3000);
        }
        this.$forceUpdate();
      },

      // 接接数据
      contactForwardMessage(cMessageList, canPush = true) {
        let content = {},
            signature = '',
            msgIndex = -1,
            flag = false;
        cMessageList.forEach((item) => {
          content = {};
          signature = '';
          msgIndex = -1;
          if (item.type.toLowerCase() == 'custom') {
            content = JSON.parse(item.content);
            if (content.bizType == -1 || content.bizType == 27) {
              signature = content.signature;
              msgIndex = this.messageList.findIndex((m) => {
                return m.signature == signature && !m.isShowErrorMsg;
              });
              if (msgIndex > -1) {
                flag = true;
                this.messageList[msgIndex].errorMsg = content.content;
                this.messageList[msgIndex].isShowErrorMsg = true;
              }
              this.$forceUpdate();
            } else {
              flag = true;
              canPush && this.messageList.push(item);
            }
          } else {
            flag = true;
            canPush && this.messageList.push(item);
          }
        });

        if (flag) {
          this.$nextTick(() => {
            var element = document.querySelector('.scroll-box');
            if (
              element.scrollTop >=
              element.scrollHeight - element.offsetHeight - 400
            ) {
              element.scrollTop = element.scrollHeight - element.offsetHeight;
            }
          });
        }
      },

      // 打开PDF
      openPDF(item) {
        window.open(item.url, '__blank');
      },

      // 根据字段名及其值，从数组中查找对象
      findItemByKeyAndVal(arr, key, value, flag = 0) {
        if (flag == 0) {
          return arr.find((item) => {
            return item[key] == value;
          });
        } else if (flag == 1) {
          return arr.findIndex((item) => {
            return item[key] == value;
          });
        }
      },

      // 获取积木列表
      getFiveContentList() {
        getQueryTemplate().then((res) => {
          if (res.code === '000000') {
            this.linkList = res.data.templateList || [];
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            });
          }
        });
      },

      // 上传文件
      beforeUploadFile(file) {
        console.log('file', file);
        const fileSize = file.size / (1024 * 1024);
        if (fileSize > 5) {
          this.$message({
            message: '请上传小于5M的文件',
            type: 'warning',
          });
          return;
        }
        openLoading(_this);
        doUpload(
          _this,
          file,
          getFilePath(file, null),
          'preview4',
          'progress',
          ''
        ).then(function (resData) {
          closeLoading(_this);
          const params = {};
          params.fileSize = resData.size;
          params.fileExt = resData.ext;
          params.url = resData.fullPath;
          params.info = resData.name;
          params.type = 2;

          // 如果是图片，则要获取其宽与高
          if (
            params.fileExt.toLowerCase() === '.jpg' ||
            params.fileExt.toLowerCase() === '.jpeg' ||
            params.fileExt.toLowerCase() === '.png'
          ) {
            params.type = 1;
            const image = new Image();
            image.src = params.url;
            image.onload = function () {
              const _img = this;
              params.width = _img.width;
              params.height = _img.height;
              _this.sendCommonMsg(params);
            };
          } else {
            _this.sendCommonMsg(params);
          }
        });
      },

      // 打开发送链接弹框
      preSendLinkMsg() {
        this.linkForm = {
          remark: '',
          info: '',
          url: '',
        };
        this.showSelectDialog = true;
      },

      // 发送带链接消息
      sendLinkMsg() {
        this.$refs['linkFormRef'].validate((valid) => {
          if (valid) {
            const params = Object.assign({}, this.linkForm);
            params.url = getPhomeDemain() + `/template_v2/?id=${params.url}`;
            params.type = 3;
            this.sendCommonMsg(params);
            this.showSelectDialog = false;
          }
        });
      },

      // 发送文本消息
      sendTextMsg() {
        if (!this.canSend) return;
        debugger;
        this.sendCommonMsg({ info: this.sendText });
        this.sendText = '';
      },

      /* 处理发送消息
     1: 先将消息体直接显示在对话框中
     2: 设置一个时间戳，以便再次找回
     3: 保存再次发送的数据
     4: 设置各种状态（1:isShowErrorIcon; 2:isShowLoadingIcon; 3:isShowErrorMsg）
    */
      handleSendMsg(params, sendId) {
        const msg = Object.assign({}, params);
        msg.fromAccount = this.tid;
        msg.toAccount = this.picakfAccId;
        // type: 0, // 类型 0文本 1图片 2pdf 3链接
        msg.text = params.info || '';
        msg.suffix = params.remark || '';
        if (msg.type == 3) {
          msg.suffix = params.info;
          msg.text = params.remark || '';
        }
        msg.size = params.fileSize;
        msg.url = params.url;
        msg.showType = params.type - 0 + 1;
        msg.sessionFlag = false;
        msg.isShowLoadingIcon = true;
        msg.isShowErrorIcon = false;
        msg.isShowErrorMsg = false; // 只有在下次拉取新数据时才有可能是为ture
        msg.extData = Object.assign({}, params); // 再将发送时的数据
        msg.sendId = sendId;
        msg.sendOrReceive = true;
        msg.timestampStr = new Date().format('hh:mm');
        msg.realTimestamp = this.realTimestamp;
        msg.taskLogId = this.currentTaskLogId;

        this.teamMemberList.forEach((item) => {
          if ((this.picakfAccId = item.accId)) {
            msg.avatarImg = item.avatarImageUrl; // 运营头像
          }
        });
        if (msg.type == 1) {
          this.imgSizeHandleNew(msg, msg.width, msg.height);
        }
        this.messageList.push(msg);
        this.$nextTick(() => {
          var element = document.querySelector('.scroll-box');
          element.scrollTop = element.scrollHeight;
        });
      },

      // 发送通用消息
      async sendCommonMsg(params) {
        const sendMsgParams = {
          fromAccount: this.picakfAccId,
          toAccount: this.tid,
          fileExt: '', // 文件扩展名称图片或PDF文件）
          fileSize: 0, // 文件大小（图片或PDF文件）
          height: 0, // 图片高度（仅图片）
          width: 0, // 图片宽度（仅图片）
          info: '', // 文本内容，图片的名称，pdf的名称，链接显示内容
          md5: '', // 图片或文件MD5  暂时由后台生成
          remark: '', // 其他信息（链接中的前缀文案）
          type: 0, // 类型 0文本 1图片 2pdf 3链接
          url: '', // url地址（图片、pdf，链接）
        };
        params = Object.assign(sendMsgParams, params);
        // 将获取新数据的定时器关闭
        forwardMsgIntervalId && clearInterval(forwardMsgIntervalId);
        const sendId = new Date().getTime();
        this.handleSendMsg(params, sendId);
        console.log('params---', params);
        await messageSend(params)
          .then((res) => {
            console.log('res------------', res);
            if (res.code === '000000') {
              // 校验结果：1校验通过 2校验不通过
              let msg = this.messageList[this.messageList.length - 1];
              if (msg.sendId !== sendId) {
                msg = this.getMsgBySendId(sendId);
              }
              if (res.data.checkFlag == 1) {
                this.realTimestamp = res.data.timetag;
                msg.isShowLoadingIcon = false;
                msg.isShowErrorIcon = false;
                msg.isShowErrorMsg = false; // 只有在下次拉取新数据时才有可能是为ture
              } else {
                msg.signature = res.data.signature;
                msg.isShowLoadingIcon = false;
                msg.isShowErrorIcon = true;
                msg.isShowErrorMsg = false; // 只有在下次拉取新数据时才有可能是为ture
              }
              this.teamMemberList.forEach((item) => {
                if (params.fromAccount == item.accId) {
                  msg.name = item.name;
                }
              });
            } else {
              this.$message({
                message: res.message,
                type: 'error',
              });
            }
          })
          .catch((error) => {
            console.log('error-----------------', error);
            let msg = this.messageList[this.messageList.length - 1];
            if (msg.sendId !== sendId) {
              msg = this.getMsgBySendId(sendId);
            }
            msg.isShowLoadingIcon = false;
            msg.isShowErrorIcon = true;
            msg.isShowErrorMsg = false; // 只有在下次拉取新数据时才有可能是为ture
            msg.canRepeatSend = true;
          });
        this.$forceUpdate();
        // 重新开启定时器
        forwardMsgIntervalId = setInterval(() => {
          this.getMSGForward();
        }, 3000);
      },

      // 根据sendId，查找到对应的消息
      getMsgBySendId(sendId) {
        console.log('------------getMsgBySendId------------');
        const l = this.messageList.length;
        let i = l - 1;
        for (; i > 0; i--) {
          if (this.messageList[i].sendId == sendId) {
            break;
          }
        }
        return this.messageList[i];
      },

      // 文件大小单位转换
      fileSizeChange(val) {
        return betaHandle(val);
      },

      closeChat() {
        if (window.rtc) {
          window.rtc.leave();
        }
        this.clearSession();
        this.$store.commit('main/updateShowChat', false);
        this.$store.commit('main/updateCurrentChat', {});
      },

      clearSession() {
        sessionStorage.removeItem('TIME_askTime');
        sessionStorage.removeItem('TIME_answerTime');
        sessionStorage.removeItem('TIME_useTime');
        sessionStorage.removeItem('TIME_loseTime');
      },

      // 结束会话
      overFn() {
        this.$refs.alert
          .init({
            cancleTxt: '取消',
            confirmTxt: '确定',
            title: '确定要结束会话吗？',
            content: '结束会话后，APP端问诊室将关闭',
          })
          .then(() => {
            this.out();
          });
      },

      out() {
        const { diagnoseLogId } = this.currentChat;
        diagnoseEndCall({
          diagnoseLogId: diagnoseLogId,
        })
          .then((res) => {
            if (res.code == '000000') {
              this.closeChat();
            } else {
              this.$refs.alert
                .init({
                  confirmTxt: '我知道了',
                  title: '操作失败,请稍后重试',
                })
                .then(() => {});
            }
          })
          .catch(() => {
            this.$refs.alert
              .init({
                confirmTxt: '我知道了',
                title: '操作失败,请稍后重试',
              })
              .then(() => {});
          });
      },

      toggleChatModal() {
        this.toggleChatSize = !this.toggleChatSize;
      },

      scrollToTOLoad() {
        const scrollBoxDom = document.querySelector('.scroll-box');
        const that = this;
        console.log('---scrollBoxDom', scrollBoxDom);
        scrollBoxDom.addEventListener('scroll', function () {
          if (scrollBoxDom.scrollTop == 0 && this.loadingListToggle) {
            this.loadingListToggle = false;
            that.getOldMSGHistory();
          }
        });
      },
    },
  };
</script>
<style lang="scss" scoped>
@import './chat.scss';
</style>
