<template>
  <div class="flex overflow-hidden message-list-modal">
    <slot></slot>
    <div class="message-info-container">
      <div class="flex direction-column message-info">
        <div class="flex items-center p-base message-info-header">
          <div class="flex items-center send-user">
            <!-- <span class="m-r-mini">发件人</span> -->
            <span class="radius-base user-name">{{
              mainStore?.myUserInfo?.id == currentMessage?.sendUserId
                ? currentMessage?.receiveUserName
                : currentMessage?.sendUserName
            }}</span>
          </div>
          <!-- <div class="grid pointer m-l-auto close-icon" @click="$emit('close')">
            <el-icon><close /></el-icon>
          </div> -->
        </div>
        <div
          class="p-base"
          :style="{ height: isFromMyLeader && !isFromSystem ? 'calc(100% - 221px)' : 'calc(100% - 111px)' }"
        >
          <!-- <pre
            class="full-h radius-base p-extra-base scroll-y-auto message-info-content"
            @click="onContentClick"
            v-html="currentMessage?.content"
          ></pre> -->
          <div ref="historyMsgWrap" class="history-box scroll-auto">
            <div v-for="(message, index) in historyReverse" :key="index" class="message-item-box m-b-base">
              <div
                class="one-message"
                :class="{
                  'other-person': message.sendUserId != mainStore?.myUserInfo?.id,
                  'self-person': message.sendUserId == mainStore?.myUserInfo?.id,
                }"
              >
                <div class="m-b-mini message-header">
                  <span class="m-r-base user-name"
                    >{{ message.sendUserName
                    }}{{ message.sendUserId == mainStore?.myUserInfo?.id ? '（我）' : '' }}</span
                  >
                  <span class="message-time">{{ message.sendTime }}</span>
                </div>
                <div class="history-message-info-content" @click="onContentClick" v-html="message.content"></div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="isFromMyLeader && !isFromSystem" class="p-base" style="padding-top: 0">
          <div class="p-base radius-base overflow-hidden msg-content-box">
            <div style="height: calc(100% - 18px)" class="scroll-y-auto">
              <content-edit-able
                v-model="messageContent"
                class="full content-edit-able"
                @click="onContentClick"
              ></content-edit-able>
            </div>

            <div class="limit-tip">{{ messageContent.length }} / 2000</div>
          </div>
        </div>
        <div class="p-base flex items-center justify-between">
          <!-- <el-button size="small" type="primary" :disabled="!currentMessage" @click="onReply">回复</el-button> -->
          <!-- <el-button size="small" plain :disabled="!currentMessage" @click="toggleHistory">历史消息</el-button> -->
          <el-button
            :disabled="!(showSendPaper && isFromMyLeader) || isFromSystem"
            size="small"
            plain
            @click="sendCurrentPaper"
            >发送当前试卷</el-button
          >
          <!-- <el-button
            v-if="isFromMyLeader"
            size="small"
            type="primary"
            :disabled="!allowSend"
            :loading="sendLoading"
            @click="onSendMessage"
            >发送</el-button
          > -->
          <el-button
            :disabled="!isFromMyLeader || !allowSend || isFromSystem"
            size="small"
            type="primary"
            :loading="sendLoading"
            @click="onSendMessage"
            >发送</el-button
          >
        </div>
      </div>
      <!-- <message-history v-if="showHistory" :send-user-id="currentMessage?.sendUserId"></message-history> -->
    </div>
  </div>
  <image-preview
    v-model="previewModalVisible"
    resize-key="can-resize-message-img"
    :url="paperPath"
    :is-big="true"
  ></image-preview>
</template>

<script setup lang="ts" name="MessageList">
/** 消息列表*/
import { ref, watch, onUnmounted, computed, nextTick, unref, onMounted } from 'vue'
import { ElButton, ElIcon, ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import useFetch from '@/hooks/useFetch'
import MessageHistory from '@/components/shared/message/MessageHistory.vue'
import ImagePreview from '../ImagePreview.vue'
import useMainStore from '@/store/main'
import { setLastMsgs } from '@/hooks/useMessageLoop'
import bus from '@/utils/bus'
import type { ExtractApiResponse } from '@/api/api'
import ContentEditAble from '@/components/common/ContentEditAble.vue'
import { getUserConfigByType, setUserConfigByType } from '@/utils/common'
type MessageType = ExtractArrayValue<ExtractApiResponse<'getMessageList'>>
const historyMsgWrap = ref()
const mainStore = useMainStore()
const props = defineProps<{
  replyUserId?: number | null
  paperPath?: string | null
  replyUserName?: string | null
  secretNumber?: string | number | null
}>()

const emits = defineEmits(['close', 'change-type', 'reply', 'refresh'])
const { fetch: getMessageHistory, result: history, loading } = useFetch('getMessageHistory')
const historyReverse = computed(() => {
  return ((history.value as any) || []).reverse()
})
/** 图片预览 */
const previewModalVisible = ref<boolean>(false)
/** 是否已发送试卷 */
const sendedPaper = ref<boolean>(false)

/** 显示发送试卷按钮 */
const showSendPaper = computed<boolean>(() => {
  // return !!props.paperPath && !sendedPaper.value
  return !!props.paperPath
})
/** 发送当前试卷 */
const sendCurrentPaper = () => {
  if (props.paperPath) {
    messageContent.value += `<span class="pointer inline link-button" contenteditable="false" data-path="${props.paperPath}">查看试卷(${props.secretNumber})</span>`
  }
}

/** 消息内容 */
const messageContent = ref<string>('')
watch(messageContent, (val: string) => {
  // let reg = /<span class=\"pointer inline link-button\" contenteditable=\"false\" data-path=.*>查看试卷<\/span>/g
  // let arr = messageContent.value.match(reg)
  // let text = messageContent.value.replace(reg, '【查看试卷临时替换字符】')
  // text = transHtmlContent(text)
  // if (arr && arr.length) {
  //   text = text.replace('【查看试卷临时替换字符】', arr[0])
  // }
  // messageContent.value = text
  nextTick(() => {
    const paperButton = document.querySelector(`.content-edit-able [data-path="${props.paperPath}"]`)
    sendedPaper.value = !!paperButton
  })
  if (sendTargetId.value) {
    let config: any = getUserConfigByType('draft')
    config[sendTargetId.value] = val || ''
    setUserConfigByType('draft', config)
  }
})
/** 图片路径 */
const paperPath = ref<string>('')

const showHistory = ref<boolean>(false)

const { fetch: getMessageList, result: messageList } = useFetch('getMessageList')

const currentMessage = ref<MessageType>()
// const isFromOther = computed(() => {
//   return mainStore?.myUserInfo?.id != currentMessage.value?.sendUserId
// })
const getOtherRole = computed(() => {
  return mainStore?.myUserInfo?.id == currentMessage.value?.sendUserId
    ? currentMessage.value?.receiveUserRole
    : currentMessage.value?.sendUserRole
})
const isFromMyLeader = computed(() => {
  // return isFromOther.value && currentMessage.value?.sendUserRole === 'DEPUTY'
  return mainStore?.myUserInfo?.role !== 'MARKER' || getOtherRole.value === 'DEPUTY'
})
const isFromSystem = computed(() => {
  return currentMessage.value?.sendUserRole === 'SYSTEM'
})
function scrollToBottom() {
  let scrollHeight = historyMsgWrap.value.scrollHeight
  if (scrollHeight > 200) {
    historyMsgWrap.value.scrollTop = scrollHeight - 200 + 100
  }
}
watch(historyReverse, (newVal: any, oldVal: any) => {
  let oldV = unref(oldVal)
  if ((oldV || []).length == 0) {
    nextTick(() => {
      scrollToBottom()
    })
  }
})
const sendTargetId = computed(() => {
  return currentMessage.value?.sendUserId == mainStore?.myUserInfo?.id
    ? currentMessage.value?.receiveUserId
    : currentMessage.value?.sendUserId
})
watch(currentMessage, (newVal: any, oldVal: any) => {
  if (currentMessage.value) {
    messageContent.value = ''
    if (currentMessage.value?.unReadCount) {
      // currentMessage.value.unReadCount--
      currentMessage.value.unReadCount = 0
    }
    if (currentMessage.value?.sendUserId) {
      const targetId =
        currentMessage.value.sendUserId == mainStore?.myUserInfo?.id
          ? currentMessage.value.receiveUserId
          : currentMessage.value.sendUserId
      getMessageHistory({
        sendUserId: targetId,
      }).then(() => {
        let newV = unref(newVal)
        let oldV = unref(oldVal)
        if (newV.id != oldV?.id) {
          setTimeout(scrollToBottom, 1)
        }
      })

      const targetIdDraft = getUserConfigByType('draft')?.[targetId]
      targetIdDraft && (messageContent.value = targetIdDraft)
    }
  }
})
const allowSend = computed<boolean>(() => {
  return !!(messageContent.value && currentMessage.value?.sendUserId)
})
const { fetch: sendMessage, loading: sendLoading } = useFetch('sendMessage')
/** 发送消息 */
const onSendMessage = async () => {
  try {
    if (messageContent.value.length > 2000) {
      return ElMessage.error('输入内容过长')
    }

    await sendMessage({
      content: messageContent.value,
      // receiveUserIds: [currentMessage.value?.sendUserId as number],
      receiveUserIds: [
        (currentMessage.value?.sendUserId == mainStore?.myUserInfo?.id
          ? currentMessage.value?.receiveUserId
          : currentMessage.value?.sendUserId) as number,
      ],
    })
    ElMessage.success('发送成功')
    messageContent.value = ''
    emits('refresh')
    // if (currentMessage.value?.sendUserId) {
    //   getMessageHistory({
    //     sendUserId:
    //       currentMessage.value.sendUserId == mainStore?.myUserInfo?.id
    //         ? currentMessage.value.receiveUserId
    //         : currentMessage.value.sendUserId,
    //   }).then(() => {
    //     setTimeout(scrollToBottom, 1)
    //   })
    // }
    // emit('close')
  } catch (error) {
    console.error(error)
  }
}
// const checkMessage = (message: MessageType) => {
//   currentMessage.value = message
// }
bus.on('clickChangeMsg', (msg: any) => {
  currentMessage.value = msg
})

const toggleHistory = () => {
  showHistory.value = !showHistory.value
}

const onReply = () => {
  if (currentMessage.value) {
    emits('change-type', 'send')
    emits('reply', currentMessage.value.sendUserId, currentMessage.value.sendUserName)
  }
}

const onContentClick = (e: Event) => {
  const target = e.target as HTMLButtonElement
  const path = target.getAttribute('data-path')
  if (path) {
    previewModalVisible.value = true
    paperPath.value = path
  }
}

onUnmounted(() => {
  useFetch('getUnReadMessage')
    .fetch()
    .then((res) => {
      setLastMsgs(res)
    })
})
</script>

<style scoped lang="scss">
.message-list-modal {
  width: 100%;
  height: 100%;
  background-color: transparent;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 6px;
  .message-info-container {
    // width: 600px;
    width: calc(100% - 260px);
    height: 100%;
    position: relative;
    .history-box {
      height: 100%;
      // border: 1px solid #eee;
      background-color: #eee;
      border-radius: 4px;
      padding: 15px;
      &:after {
        content: '';
        display: block;
        clear: both;
      }
      .message-item-box {
        &:after {
          content: '';
          display: block;
          clear: both;
        }
      }
      .one-message {
        max-width: 75%;
        .history-message-info-content {
          border-radius: 4px;
          padding: 12px;
        }
        &.other-person {
          float: left;
          :deep(.link-button) {
            background-color: #e6f0ff !important;
          }
          .message-header {
            .user-name {
              // color: #444;
              color: #888;
              font-size: 12px;
              font-weight: bold;
            }
            .message-time {
              color: #888;
              font-size: 12px;
            }
          }
        }
        &.self-person {
          float: right;
          .history-message-info-content {
            color: #fff;
            background-color: $color--primary;
          }
          .message-header {
            text-align: right;
            .user-name {
              // color: #fff;
              color: #888;
              font-size: 12px;
              font-weight: bold;
            }
            .message-time {
              // color: #fff;
              color: #888;
              font-size: 12px;
            }
          }
        }
      }
      // .message-header {
      //   color: $color--primary;
      //   &.other-name {
      //     color: #999;
      //   }
      // }
      .history-message-info-content {
        white-space: pre-wrap;
        color: #444;
        font-size: 12px;
        font-weight: 400;
        line-height: 18px;
        background-color: #fff;
      }
    }
    .msg-content-box {
      height: 100px;
      font-size: 13px;
      border: 1px solid #0091ff;
      color: #444;
      .limit-tip {
        text-align: right;
        height: 18px;
        padding-top: 5px;
      }
    }
    .message-info {
      // height: 446px;
      height: 100%;
      background-color: $color--white;
      .message-info-header {
        border-bottom: $OnePixelLine;
        .send-user {
          font-size: $SmallFont;
          color: $RegularFontColor;
          .user-name {
            display: inline-block;
            width: 160px;
            padding: 0 12px;
            border: $OnePixelLine;
            height: 38px;
            line-height: 36px;
          }
        }
        .close-icon {
          width: 20px;
          height: 20px;
          place-items: center;
          font-size: 18px;
          color: $RegularFontColor;
          &:hover {
            color: $NormalColor;
          }
        }
      }
      .message-info-content {
        border: $OnePixelLine;
        font-size: $SmallFont;
        white-space: pre-wrap;
      }
    }
  }
}
</style>
