<template>
  <view class="page">
    <BackBar :title="stuData.nickName || ''" />
    <scroll-view :scroll-into-view="row" class="scroll_view" scroll-y scroll-with-animation>
      <view v-for="(item, index) of chatList" :id="`item-${index}`" :key="index">
        <view v-if="item?.type === 'divider'" class="time">{{ item.timeDate }}</view>
        <view v-if="item?.sender === 2" class="stundent">
          <wd-img width="80rpx" height="80rpx" round :src="getAvatarUrl(item.avatarUrl)"></wd-img>
          <view class="info stu-box">
            <wd-img class="left-icon" width="12rpx" height="24rpx" :src="leftIcon"></wd-img>
            <text>{{ item.messageContent }}</text>
          </view>
        </view>
        <view v-if="item?.sender === 1" class="myself">
          <wd-img
            width="56rpx"
            class="notice"
            height="56rpx"
            round
            :src="Notice"
            @click="notice(item)"
          ></wd-img>
          <view class="info self-box">
            <wd-img class="right-icon" width="12rpx" height="24rpx" :src="rightIcon"></wd-img>
            <text>{{ item.messageContent }}</text>
          </view>
          <wd-img width="80rpx" height="80rpx" round :src="getAvatarUrl(item.avatarUrl)"></wd-img>
        </view>
      </view>
    </scroll-view>
    <view class="footer">
      <!--      <view class="suffix"></view>-->
      <input v-model="content" class="uni-input" @focus="inputFouse" />
      <button :class="{ 'send-btn': true, disabled: !content }" :disabled="!content" @click="send">
        发送
      </button>
    </view>
    <CustomPopup v-model="showNotice" titleText="设置强提醒" @handleConfirmBtn="confirmNotice">
      <view class="popup-content">以弹窗形式提醒学生？频繁提醒会中断学习哦~</view>
    </CustomPopup>
  </view>
</template>
<script setup lang="ts">
import CustomPopup from '@/components/CustomPopup/index.vue'
import { formatDate, getAvatarUrl, getCache } from '@/utils'
import { onShow, onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { onMounted, ref, watch, computed, nextTick } from 'vue'
import leftIcon from '@/static/svg/icon-left.svg'
import rightIcon from '@/static/svg/icon-right.svg'
import { getTalkDetails, saveTalk, readMsg } from '@/api/modules/inspector'
import { useSocket } from '@/hooks/useSocket'
import dayjs from 'dayjs'
import Notice from '@/static/svg/notice.svg'
import db from '@/utils/db'

const row = ref('')
const scrollContainerRef = ref()
const showNotice = ref(false)
const { init: socketInit, inspectorMessage, sendMsg } = useSocket()
const stuData = ref<any>({})
const OSS_URL = import.meta.env.VITE_OSS_HOST
const defaultAvatar = `${OSS_URL}/urm/default_avatar.png`
const current = ref(1)
const userInfo = ref<any>({})
const chatList = ref<any[]>([])
const noticeText = ref<string>('')

interface userInfoType {
  userName: string
  userId: string
}

const FIVE_MINUTES = 5 * 60 * 1000
const lastMessageTs = computed(() => dayjs(chatList.value.at(-2)?.createTime).valueOf() ?? 0)
const content = ref('')

const inputFouse = async () => {
  row.value = ''
  nextTick(() => {
    setTimeout(() => {
      row.value = 'item-' + (chatList.value.length - 1)
    }, 300)
  })
}

async function send() {
  const { code, data } = await saveTalk({
    senderId: userInfo.value.userId,
    // inspectorPlanId: stuData.value.inspectorPlanId,
    receiverId: stuData.value.sender === 2 ? stuData.value.senderId : stuData.value.receiverId,
    messageType: 1,
    sender: 1,
    messageContent: content.value,
  })
  if (code === 200) {
    const msg = {
      id: data.id,
      senderId: userInfo.value.userId,
      receiverId: stuData.value.sender === 2 ? stuData.value.senderId : stuData.value.receiverId,
      messageType: 1,
      sender: 1,
      // inspectorPlanId: stuData.value.inspectorPlanId,
      messageContent: content.value,
      avatarUrl: userInfo.value.avatarUrl,
      senderName: userInfo.value.nickName,
      senderAvatarUrl: userInfo.value.avatarUrl,
    }
    const newMessage = {
      sender: 1,
      messageContent: content.value,
      avatar: '',
      avatarUrl: userInfo.value.avatarUrl,
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
    chatList.value = [
      ...chatList.value,
      lastMessageTs.value === 0 ||
      dayjs(newMessage.createTime).valueOf() - lastMessageTs.value > FIVE_MINUTES
        ? { timeDate: formatDate(newMessage.createTime), type: 'divider' }
        : null,
      newMessage,
    ].filter(Boolean) as any[]

    sendMsg({ type: 'inspectorTalkMessage', msg })
    content.value = ''
    nextTick(() => {
      setTimeout(() => {
        row.value = 'item-' + (chatList.value.length - 1)
      }, 500)
    })
  }
}

// 设置请提醒
function notice(row: any) {
  showNotice.value = true
  noticeText.value = row.messageContent
}

// 确认设置提醒
function confirmNotice() {
  const msg = {
    type: 'systemMessage',
    userId: stuData.value.sender === 2 ? stuData.value.senderId : stuData.value.receiverId,
    msg: noticeText.value,
  }
  sendMsg(msg)
  showNotice.value = false
}

async function getDetails() {
  try {
    uni.showLoading({
      title: '加载中...',
    })
    const { code, data } = await getTalkDetails({
      inspectorTalkRecordId: chatList.value[0]?.id ?? (chatList.value[1]?.id || undefined),
      userId: stuData.value.sender === 2 ? stuData.value.senderId : stuData.value.receiverId,
    })
    uni.hideLoading()
    uni.stopPullDownRefresh()
    if (code === 200) {
      const ids = chatList.value.filter(item => item.status === 1).map(item => item.id)
      if (ids.length) {
        readMsg({
          receiverId: userInfo.value.userId,
          senderId: stuData.value.sender === 2 ? stuData.value.senderId : stuData.value.receiverId,
        })
      }
      const newChat = insertDividers(data)
      chatList.value = [...newChat, ...chatList.value]
      chatList.value = chatList.value.map((v: any) => {
        if (v.sender === 1) {
          return { ...v, avatarUrl: userInfo.value.avatarUrl }
        }
        return { ...v }
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.stopPullDownRefresh()
  }
}

function insertDividers(messages: any[]) {
  const result = []
  if (messages.length > 0) {
    result.push({ timeDate: formatDate(messages[0].createTime), type: 'divider' })
  }
  return messages.reduce((acc, currentMessage, index) => {
    acc.push(currentMessage)
    if (index < messages.length - 1 && currentMessage.type !== 'divider') {
      const nextMessage = messages[index + 1]
      if (
        dayjs(nextMessage.createTime).valueOf() - dayjs(currentMessage.createTime).valueOf() >=
        FIVE_MINUTES
      ) {
        acc.push({ timeDate: formatDate(nextMessage.createTime), type: 'divider' })
      }
    }
    return acc
  }, result) as any[]
}

watch(inspectorMessage, msg => {
  if (!msg) return
  const newMsgTs = dayjs(msg.createTime).valueOf()
  console.log('msg1', msg)
  const newMsg = {
    sender: 2,
    avatarUrl: msg.senderAvatarUrl || defaultAvatar,
    createTime: msg.createTime,
    messageContent: msg.messageContent,
  }
  chatList.value.push(newMsg)
  chatList.value = [
    ...chatList.value,
    lastMessageTs.value === 0 || newMsgTs - lastMessageTs.value > FIVE_MINUTES
      ? { timeDate: formatDate(msg.createTime), type: 'divider' }
      : null,
  ]
  readMsg({ receiverId: msg.receiverId, senderId: msg.senderId })
  nextTick(() => {
    row.value = 'item-' + (chatList.value.length - 1)
  })
})

onMounted(() => {
  // userInfo.value = uni.getStorageSync('QY_USERINFO');
  userInfo.value = db.get('dxs_userInfo')
  socketInit()
  nextTick(() => {
    setTimeout(() => {
      row.value = 'item-' + (chatList.value.length - 1)
    }, 500)
  })
  readMsg({
    receiverId: userInfo.value.userId,
    senderId: stuData.value.sender === 2 ? stuData.value.senderId : stuData.value.receiverId,
  })
})
onShow(() => {
  stuData.value = uni.getStorageSync('stu')
})
onPullDownRefresh(() => {
  getDetails()
})
onLoad(() => {
  nextTick(() => {
    // uni.startPullDownRefresh();
    getDetails()
  })
})
</script>
<style lang="scss" scoped>
.page {
  // width: 750rpx;
  height: 100vh;
  padding: 0 30rpx 100rpx 30rpx;
  box-sizing: border-box;

  .scroll_view {
    height: calc(100vh - 210rpx);
    padding: 10rpx 0;
    box-sizing: border-box;
  }
  .stundent {
    display: flex;
    margin-bottom: 30rpx;

    .stu-box {
      background-color: #fff;
      position: relative;
      margin-left: 20rpx;

      .left-icon {
        position: absolute;
        left: -12rpx;
        top: 28rpx;
      }
    }
  }

  .time {
    font-size: 22rpx;
    color: #8d8d8d;
    text-align: center;
    margin: 20rpx;
  }

  .myself {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 30rpx;

    .notice {
      margin-top: 12rpx;
      margin-right: 10rpx;
    }

    .self-box {
      background-color: #c5c3ff;
      position: relative;
      margin-right: 20rpx;

      .right-icon {
        position: absolute;
        right: -10rpx;
        top: 24rpx;
      }
    }
  }

  .info {
    max-width: 500rpx;
    font-size: 32rpx;
    color: #0a1f13;
    line-height: 48rpx;
    padding: 16rpx 20rpx;
    box-sizing: border-box;
    border-radius: 12rpx;
  }

  .footer {
    height: 112rpx;
    width: 100vw;
    position: fixed;
    z-index: 99;
    bottom: 0;
    left: 0;
    background: #f1f2f5;
    padding: 15rpx 30rpx 30rpx 30rpx;
    box-sizing: border-box;
    border-top: 1rpx solid #f6f6f6;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .uni-input {
      height: 78rpx;
      width: calc(100vw - 188rpx);
      background: #fff;
      border-radius: 12rpx;
      padding: 0 12rpx;
      box-sizing: border-box;
    }

    .send-btn {
      display: grid;
      place-content: center;
      color: #fff;
      background: #615dff;
      font-size: 30rpx;
      padding: 0;
      width: 108rpx;
      height: 60rpx;
      border-radius: 10rpx;
      line-height: 60rpx;
      margin: 0;
    }

    .disabled {
      background: #c5c3ff;
    }

    .suffix {
      width: 30rpx;
    }
  }
}

.popup-content {
  text-align: left;
  margin: 50rpx 0;
  padding: 0 63rpx;
  box-sizing: border-box;
}

:deep(.uni-scroll-view-content) {
  height: 98%;
}
</style>
