<template>
  <div v-loading="loading" class="chat-wrapper">
    <div v-if="recordContent.length>0" class="chat-content">
      <div v-for="(record,index) in recordContent" :key="index">
        <div v-if="!record.IsCurrentUser" class="word">
          <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">
          <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">
        </div>
      </div>
    </div>
    <div v-else class="chat-content">
      <!-- 暂无数据 -->
      <h3>{{ $t('trials:consistencyCheck:label:noData') }}</h3>
    </div>
    <div v-if="checkChallengeState !== 3 && checkState !== 11" class="chat-message">
      <div class="message">
        <el-input :maxLength="$inputMax"
          v-model="newMessage"
          v-hasPermi="['trials:trials-panel:visit:consistency-check:fallback']"
          type="textarea"
          :rows="2"
        />
      </div>
      <div class="function">
        <!-- 申请回退 -->
        <el-button
          v-hasPermi="['trials:trials-panel:visit:consistency-check:apply-fallback']"
          type="primary"
          :disabled="!(checkState === 10 && (requestBackState === 0 || requestBackState === 3))"
          @click="handleApplyBack"
        >
          {{ $t('trials:consistencyCheck:action:applyFallback') }}
        </el-button>
        <!-- 拒绝回退 -->
        <el-button
          v-hasPermi="['trials:trials-panel:visit:consistency-check:fallback']"
          type="primary"
          :disabled="!(requestBackState === 1)"
          @click="handleRejectBack"
        >
          {{ $t('trials:consistencyCheck:button:rejectBack') }}
        </el-button>
        <!-- 回退 -->
        <el-button
          v-hasPermi="['trials:trials-panel:visit:consistency-check:fallback']"
          type="primary"
          :disabled="!(requestBackState === 1)"
          @click="handleBack"
        >
          {{ $t('trials:consistencyCheck:action:fallback') }}
        </el-button>
        <!-- 发送 -->
        <el-button
          v-hasPermi="['role:pm']"
          :disabled="!(checkState === 10 && checkChallengeState !== 3) || newMessage === ''"
          type="primary"
          :loading="btnLoading"
          @click="handleReply()"
        >
          {{ $t('trials:consistencyCheck:button:sendMessage') }}
        </el-button>
        <!-- 回复 -->
        <el-button
          v-hasPermi="['role:crc']"
          :disabled="!(checkState === 10 && checkChallengeState !== 3) || (recordContent && recordContent.length > 0 ? recordContent[recordContent.length - 1].UserTypeEnum * 1 === 2 : false)"
          type="primary"
          :loading="btnLoading"
          @click="handleCRCReply"
        >
          {{ $t('trials:consistencyCheck:title:reply') }}
        </el-button>
        <!-- 关闭 -->
        <el-button
          type="primary"
          :loading="btnLoading"
          @click="close"
        >
          {{ $t('trials:consistencyCheck:title:close') }}
        </el-button>
      </div>
    </div>
    <!-- 回复一致性核查 -->
    <el-dialog
      v-if="sendMessageCRCVisible"
      v-dialogDrag
      :visible.sync="sendMessageCRCVisible"
      :close-on-click-modal="false"
      append-to-body
      custom-class="base-dialog-wrapper"
      :width="'600px'"
      :title="$t('trials:consistencyCheck:title:replyConsistency')"
    >
      <crcSendMessage :crc-message-info="crcMessageInfo" @sendMessage="handleReply" />
    </el-dialog>
  </div>
</template>
<script>
import { getCheckChallengeDialogList, addCheckChallengeReply, rejectCheckBack } from '@/api/trials'
import crcSendMessage from './crcSendMessageNew'
import adminAvatar from '@/assets/Admin.png'
import pmAvatar from '@/assets/PM.png'
import crcAvatar from '@/assets/CRC.png'
export default {
  name: 'ConsistencyCheckForm',
  components: { crcSendMessage },
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    dialogList: {
      type: Array,
      default() {
        return []
      }
    },
    isReply: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      recordContent: [],
      sendMessageCRCVisible: false,
      newMessage: '',
      loading: false,
      btnLoading: false,
      userId: zzSessionStorage.getItem('userId'),
      adminAvatar,
      pmAvatar,
      crcAvatar,
      requestBackState: null,
      checkState: null,
      checkChallengeState: null,
      crcMessageInfo: {
        arrayOnelist: [],
        arrayTwolist: []
      }
    }
  },
  watch: {
    data: {
      handler(newVal) {
        this.requestBackState = newVal.RequestBackState
        this.checkState = newVal.CheckState
        this.checkChallengeState = newVal.CheckChallengeState
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.getMessageList(this.dialogList)
    console.log(this.dialogList)
  },
  methods: {
    close() {
      this.$emit('close')
    },
    getMessageList(dialogList) {
      var recordContent = []
      dialogList.forEach(element => {
        recordContent.push(element)
      })
      this.recordContent = recordContent
      this.setScrollHeight()
    },
    setScrollHeight() {
      setTimeout(() => {
        var container = document.querySelectorAll('.chat-content')[0]
        container.scrollTop = container.scrollHeight
      }, 100)
    },
    addMessage(newMsg) {
      this.recordContent.push(newMsg)
      this.setScrollHeight()
      this.loading = false
    },
    // getMessageList2() {
    //   this.loading = true
    //   getCheckChallengeDialogList(this.data.Id).then(res => {
    //     var recordContent = []
    //     res.Result.forEach(element => {
    //       recordContent.push(element)
    //     })
    //     this.recordContent = recordContent
    //     this.loading = false
    //   }).catch(() => {
    //     this.loading = false
    //   })
    // },
    handleApplyBack() {
      this.$emit('handleApplyBack')
    },
    handleBack() {
      this.$emit('handleBack')
    },
    handleRejectBack() {
      const trialId = this.$route.query.trialId
      this.loading = true
      rejectCheckBack(trialId, this.data.Id).then(res => {
        if (res.IsSuccess) {
          this.$emit('getDialogList')
        }
      }).catch(() => { this.loading = false })
    },
    handleCRCReply() {
      this.sendMessageCRCVisible = true
      var list = Object.assign([], this.recordContent)
      list = list.filter(v => {
        return v.IsCRCNeedReply === true
      })
      var lastCheckMessage = list[list.length - 1]
      console.log(lastCheckMessage)
      if (!lastCheckMessage.TalkContent) return
      this.crcMessageInfo = lastCheckMessage
      // var arrayOneStr = lastCheckMessage.TalkContent.replace('你好根据本系统自动像识别，该受者本访视已提交的像检查情况如下：', '').replaceAll('<br/>', '').split("<span style='color: #f00'>存在问题如下：</span>\r\n")[0]
      // var arrayTwoStr = lastCheckMessage.TalkContent.replace('你好根据本系统自动像识别，该受者本访视已提交的像检查情况如下：', '').replaceAll('<br/>', '').split("<span style='color: #f00'>存在问题如下：</span>\r\n")[1]
      // console.log(arrayOneStr.split('<br>'), arrayTwoStr.split('<br>'))
      // var arrayOnelist = arrayOneStr.split('<br>')
      // arrayOnelist.pop()
      // arrayOnelist.shift()
      // var arrayTwolist = arrayTwoStr.split('<br>')
      // arrayTwolist.pop()
      // arrayTwolist.shift()
      // this.crcMessageInfo.arrayOnelist = arrayOnelist
      // this.crcMessageInfo.arrayTwolist = arrayTwolist
    },
    handleReply(TalkContent, callback) {
      console.log(TalkContent)
      this.newMessage = TalkContent || this.newMessage
      if (!this.newMessage) return
      const trialId = this.$route.query.trialId
      var params = {
        TalkContent: this.newMessage,
        SubjectVisitId: this.data.Id
      }
      this.loading = true
      addCheckChallengeReply(trialId, params).then(res => {
        if (res.IsSuccess) {
          // this.getMessageList()
          this.newMessage = ''
          if (callback) {
            callback()
          }
          this.sendMessageCRCVisible = false
          this.$emit('getDialogList')
        }
      }).catch(() => { this.loading = 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;
    }
  }
}
</style>
