<template>
  <div v-loading="loading" class="chat-wrapper">
    <div class="chat-content">
      <div v-for="(record,index) in recordContent" :key="index">
        <div v-if="!record.IsCurrentUser" class="word">
          <!-- <img :src="record.headUrl"> -->
          <img v-if="record.UserTypeEnum*1 === 8" :src="adminAvatar" alt="Admin">
          <img v-else-if="record.UserTypeEnum*1 === 1" :src="pmAvatar" alt="PM">
          <img v-else-if="record.UserTypeEnum*1 === 2" :src="crcAvatar" alt="CRC">
          <img v-else-if="record.UserTypeEnum*1 === 3" :src="qcAvatar" alt="QC">
          <div class="info">
            <p class="user-info">
              <span style="font-weight:700;">{{ record.CreateUserName }} </span>
              <span>({{ record.CreateTime }}) </span>
            </p>
            <div class="info-content" v-html="record.TalkContent" />
          </div>
        </div>

        <div v-else class="word-my">
          <div class="info">
            <p class="user-info">
              <span style="font-weight:700;">{{ record.CreateUserName }} </span>
              <span>({{ record.CreateTime }}) </span>
            </p>
            <div class="info-content" v-html="record.TalkContent" />
          </div>
          <!-- <img :src="record.headUrl"> -->
          <img v-if="record.UserTypeEnum*1 === 8" :src="adminAvatar" alt="Admin">
          <img v-else-if="record.UserTypeEnum*1 === 1" :src="pmAvatar" alt="PM">
          <img v-else-if="record.UserTypeEnum*1 === 2" :src="crcAvatar" alt="CRC">
          <img v-else-if="record.UserTypeEnum*1 === 3" :src="qcAvatar" alt="QC">
        </div>
      </div>
    </div>
    <div
      v-if="hasPermi(['trials:trials-panel:visit:qc-question:send']) && currentUserId === data.CurrentActionUserId"
      v-show="showNewMessage"
      class="chat-message"
    >
      <div class="message">
        <el-input :maxLength="$inputMax"
          v-model="newMessage"
          type="textarea"
          :rows="2"
        />
      </div>
      <div class="function">
        <!-- 同意重传 -->
        <el-button
          v-show="ReuploadEnum === 1"
          v-hasPermi="['trials:trials-panel:visit:qc-question:agree-reupload']"
          type="primary"
          :loading="setUploadLoading"
          @click="setReupload"
        >
          {{ $t('trials:qcQuality:dialogButton:agreeToReupload') }}
        </el-button>
        <!-- 发送 -->
        <el-button

          v-hasPermi="['trials:trials-panel:visit:qc-question:send']"
          :disabled="newMessage===''"
          type="primary"
          :loading="btnLoading"
          @click="handleReply"
        >
          {{ $t('trials:qcQuality:dialogButton:send') }}
        </el-button>
        <!-- 关闭 -->
        <el-button
          type="primary"
          :loading="btnLoading"
          @click="close"
        >
          {{ $t('trials:qcQuality:dialogButton:close') }}
        </el-button>
      </div>
    </div>

  </div>
</template>
<script>
import { getQCChallengeDialogList, addQCChallengeReply, setNeedReupload } from '@/api/trials'
import adminAvatar from '@/assets/Admin.png'
import pmAvatar from '@/assets/PM.png'
import crcAvatar from '@/assets/CRC.png'
import qcAvatar from '@/assets/QC.png'
export default {
  name: 'ChatForm',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    bodyParts: {
      type: String,
      default: ''
    },
    modalities: {
      type: String,
      default: ''
    },
    signText: {
      type: String,
      default: ''
    },
    clinicalEnum: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      recordContent: [],
      newMessage: '',
      showNewMessage: false,
      loading: false,
      btnLoading: false,
      userId: zzSessionStorage.getItem('userId'),
      adminAvatar,
      pmAvatar,
      crcAvatar,
      qcAvatar,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      trialCode: this.$route.query.trialCode,
      needReUpload: false,
      setUploadLoading: false,
      ReuploadEnum: 0,
      trialId: this.$route.query.trialId,
      currentUserId: zzSessionStorage.getItem('userId')
    }
  },
  watch: {
    data: {
      handler(newName, oldName) {
        this.getMessageList()
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    if (!this.data.IsClosed) {
      this.showNewMessage = true
    }
    this.ReuploadEnum = this.data.ReuploadEnum * 1
    this.getMessageList()
  },
  methods: {
    close() {
      this.$emit('close')
    },
    // 初始化聊天信息
    getMessageList() {
      var recordContent = []
      var contents = []
      if (this.data.Content && this.data.Content.indexOf('|') !== -1) {
        contents = this.data.Content.split('|')
      } else if (this.data.Content && this.data.Content !== '') {
        contents.push(this.data.Content)
      }

      var li = contents.map(content => { return `<li>${content}</li>` })
      const content = `
                        <div>${this.$t('trials:qcQuality:dialog:qcContent')}
                        <ol>
                        ${li.join('')}
                        </ol>
                        </div>
                        <p>
                        ${this.$t('trials:qcQuality:dialogTips:tip')}
                        </p>
                        <p style='color:red'>${this.$t('trials:qcQuality:dialog:deadline')}: ${this.data.DeadlineTime ? this.data.DeadlineTime : this.$t('trials:qcQuality:dialog:none')}</p>`
      const userId = zzSessionStorage.getItem('userId')
      recordContent.push(
        {
          IsCurrentUser: this.data.CreateUserId === userId,
          TalkContent: content,
          CreateTime: this.data.CreateTime,
          CreateUserName: this.data.CreateUserName,
          CreateUserId: this.data.CreateUserId,
          UserTypeEnum: this.data.UserTypeEnum
        }
      )
      this.data.DialogList.forEach(element => {
        recordContent.push(element)
      })
      this.recordContent = recordContent
      this.setScrollHeight()
    },
    getMessageList1() {
      this.loading = true
      // this.recordContent = []
      var recordContent = []
      var contents = []
      if (this.data.Content && this.data.Content.indexOf('|') !== -1) {
        contents = this.data.Content.split('|')
      } else if (this.data.Content && this.data.Content !== '') {
        contents.push(this.data.Content)
      }

      var li = contents.map(content => { return `<li>${content}</li>` })
      const content = `
                        <div>${this.$t('trials:qcQuality:dialog:qcContent')}
                        <ol>
                        ${li.join('')}
                        </ol>
                        </div>
                        <p>
                        ${this.$t('trials:qcQuality:dialogTips:tip')}
                        </p>
                        <p style='color:red'>${this.$t('trials:qcQuality:dialog:deadline')}: ${this.data.DeadlineTime ? this.data.DeadlineTime : this.$t('trials:qcQuality:dialog:none')}</p>`
      const userId = zzSessionStorage.getItem('userId')
      recordContent.push(
        {
          IsCurrentUser: this.data.CreateUserId === userId,
          TalkContent: content,
          CreateTime: this.data.CreateTime,
          CreateUserName: this.data.CreateUserName,
          CreateUserId: this.data.CreateUserId,
          UserTypeEnum: this.data.UserTypeEnum
        }
      )
      getQCChallengeDialogList(this.data.Id).then(res => {
        this.loading = false
        res.Result.forEach(element => {
          recordContent.push(element)
        })
        this.recordContent = recordContent
        this.setScrollHeight()
      }).catch(() => {
        this.loading = false
      })
    },
    setScrollHeight() {
      setTimeout(() => {
        var container = document.querySelectorAll('.chat-content')[0]
        container.scrollTop = container.scrollHeight
      }, 100)
    },
    // 回复质疑
    handleReply() {
      if (!this.newMessage) return
      var params = {
        talkContent: this.newMessage,
        qcChallengeId: this.data.Id,
        subjectVisitId: this.data.SubjectVisitId
      }
      this.btnLoading = true
      addQCChallengeReply(this.trialId, params).then(res => {
        this.btnLoading = false
        if (res.IsSuccess) {
          // this.getMessageList()
          this.newMessage = ''
          this.reFreshList()
        }
      }).catch(() => { this.btnLoading = false })
    },
    // 刷新父组件列表
    reFreshList() {
      this.$emit('getDialogList')
    },
    // 设置同意重传
    setReupload() {
      // 是否确认同意重传
      this.$confirm(this.$t('trials:qcQuality:message:agreeToReupload'), {
        type: 'warning',
        distinguishCancelAndClose: true
      }).then(v => {
        this.setUploadLoading = true
        setNeedReupload(this.trialId, this.data.SubjectVisitId, this.data.Id)
          .then(res => {
            this.setUploadLoading = false
            if (res.IsSuccess) {
              // this.$message.success(this.$t('common:message:savedSuccessfully'))
              this.ReuploadEnum = 2
              // this.getMessageList()
              this.reFreshList()
            }
          }).catch(() => { this.setUploadLoading = false })
      })
    }
  }

}

</script>
<style lang="scss">
.chat-wrapper{
::-webkit-scrollbar {
    width: 7px;
    height: 7px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
  }
  .chat-content{
    width:100%;
    padding: 20px;
    height: 500px;
    overflow-y: auto;
    .word{
      display: flex;
      margin-bottom: 20px;
      img{
        width:40px;
        height: 40px;
        border-radius: 50%;
      }
      .info{
        margin-left: 10px;
        .user-info{
          font-size: 12px;
          color:rgba(51,51,51,0.8);
          margin:0;
          height: 20px;
          line-height: 20px;
          margin-top: -5px;
        }
        .info-content{
          padding: 10px;
          font-size: 14px;
          background-color: #ebeef5;
          position: relative;
          margin-top: 8px;
        }
        .info-content::before{
          position: absolute;
          left: -8px;
          top: 8px;
          content: '';
          border-right: 10px solid #ebeef5;
          border-top: 8px solid transparent;
          border-bottom: 8px solid transparent;
        }
      }
    }
    .word-my{
      display: flex;
      justify-content: flex-end;
      margin-bottom: 20px;
      img{
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
      .info{
        width: 90%;
        margin-left: 10px;
        text-align: right;
        .user-info{
          font-size: 12px;
          color: rgba(51,51,51,0.8);
          margin: 0;
          height: 20px;
          line-height: 20px;
          margin-top: -5px;
          margin-right: 10px;
        }
        .info-content{
          position: relative;
          max-width: 70%;
          padding: 10px;
          font-size: 14px;
          float: right;
          margin-right: 10px;
          margin-top: 8px;
          background-color: #7574d9;
          color: #fff;
          text-align: left;
        }
        .info-content::after{
          position: absolute;
          right: -8px;
          top: 8px;
          content: '';
          border-left: 10px solid #7574d9;
          border-top: 8px solid transparent;
          border-bottom: 8px solid transparent;
        }
      }
    }
  }
  .chat-message{
    padding: 0 50px;
    .function{
      margin-top: 10px;
      text-align: right;
    }
  }
  ol{
    margin: 5px;
    padding: 0px 10px;
    counter-reset: num;
    li{
      counter-increment: num;
      // list-style:none;
    }
  }
  ol.example{counter-reset: num;}
  ol.example li{counter-increment: num; list-style:none;}
}
</style>
