<script setup lang="ts">
import AgoraRTC from "agora-rtc-sdk-ng"
import type { IAgoraRTCClient, IMicrophoneAudioTrack, ICameraVideoTrack } from "agora-rtc-sdk-ng"
import type { type_dyaw_xlfw_zxhd, type_dyaw_xlfw_zxhd_log } from '~/types';
import user from '~/store/user';
import { createSocket, socketSend } from '~/utils/ws';
import type { TSocketRes } from '~/utils/ws';
import { formatTimestamp } from '~/utils/time'

const router = useRouter()
let teacher
const SessionConsultTeacher = sessionStorage.getItem('consult_teacher')
if (SessionConsultTeacher !== null) {
  teacher = JSON.parse(SessionConsultTeacher)
} else {
  router.back()
}

let teacherInfo = $ref<{
  dxp_user_realname: string;
  dxp_user_phone: string;
  dxp_wx_qrcode: string;
  dxp_jj: string;
  dxp_user_avatar: string;
}>()
request({
  url: '/dyaw/xlfw_pbgl/detail',
  data: {
    user_id: teacher.user_id
  }
}).then(res => {
  if (res.code === '1') {
    teacherInfo = res.data.one_info
  }
})

const dyaw_xlfw_zxhd: type_dyaw_xlfw_zxhd = (await request({
  url: '/dyaw/xlfw_zxhd/add',
  data: {
    dyaw_xlfw_zxhd: {
      dxz_stu_user_id: user.user_id,
      dxz_tea_user_id: teacher.user_id
    }
  }
})).data.one_info

let rateDialogVisible = $ref(false)
let endTime = $ref<string>()
let rateNum = $ref(5)
function handleClickEnd() {
  // ChatAudioRef && ChatAudioRef.open()
  endTime = getDatabaseTime(new Date())
  rateDialogVisible = true
}
function handleConfirmRate() {
  request({
    url: '/dyaw/xlfw_zxhd/edit',
    data: {
      dxz_id: dyaw_xlfw_zxhd.dxz_id,
      dyaw_xlfw_zxhd: {
        dxz_star: rateNum,
        dxz_star_datetime: endTime,
        // 下行代码【可能】导致使用问题
        dxz_status: '1'
      }
    }
  }).then(res => {
    if (res.code === '1') {
      rateDialogVisible = false
      router.back()
    }
  })
}

let infoList = $ref<Array<type_dyaw_xlfw_zxhd_log>>([])
let inputValue = $ref('')
let isSending = $ref(false)
let TinyRef = $ref<typeof import('~/components/tinymce-area/index.vue')['default']>()
async function handleClickSend() {
  if (isSending) return;
  isSending = true
  const reqDate = {
    dxz_id: dyaw_xlfw_zxhd.dxz_id,
    dxzl_stu_user_id: dyaw_xlfw_zxhd.dxz_stu_user_id,
    dxzl_stu_user_realname: dyaw_xlfw_zxhd.dxz_stu_user_realname,
    dxzl_tea_user_id: dyaw_xlfw_zxhd.dxz_tea_user_id,
    dxzl_tea_user_realname: dyaw_xlfw_zxhd.dxz_tea_user_realname,
    dxzl_last_msg_content: encodeURIComponent(inputValue),
    dxzl_type: inputValue.includes('><img') ? '2' : '1'
  }

  // infoList.push({
  //   create_user_id: user.user_id,
  //   create_dateline: Date.now().toString().slice(0, 10),

  //   ...reqDate
  // })
  TinyRef?.clear()
  // console.log('inputValue :>> ', inputValue);
  request({
    url: '/dyaw/xlfw_zxhd_log/add',
    data: {
      dyaw_xlfw_zxhd_log: reqDate
    }
  }).then(res => {
    if (res.code === '1') {
      const fullSendData = {
        create_user_id: user.user_id,
        create_dateline: Date.now().toString().slice(0, 10),
        ...reqDate,
        dxzl_id: `${res.data.insert_id}`
      }
      infoList.push(fullSendData)
      socketSend(ws, fullSendData)
      isSending = false
    }
  })
}

request({
  url: '/dyaw/xlfw_zxhd_log/index',
  data: {
    dxz_id: dyaw_xlfw_zxhd.dxz_id,
    limit: 100
  }
}).then(res => {
  if (res.code === '1') {
    infoList = res.data.page_data.reverse()
  }
})
const ws = createSocket(
  { teacher: teacher.user_id, student: user.user_id },
  {
    message(socketRes: TSocketRes<type_dyaw_xlfw_zxhd_log>) {
      if (socketRes.from_client_name.endsWith('teacher')) {
        infoList.push(socketRes.content)
      }
    }
  }
)

const scrollbarRef = $ref<HTMLElement>()
function scrollToBottom() {
  if (!scrollbarRef) return;
  const scrollHeight = scrollbarRef!.scrollHeight;
  scrollbarRef!.scrollTo(0, scrollHeight);
}
watch(
  () => (infoList),
  () => {
    nextTick(() => {
      scrollToBottom()
    })
  },
  {
    deep: true,
  }
)

// ==========
// chat audit/video
// ==========

let rtcInstance: {
  client?: IAgoraRTCClient;
  localAudioTrack?: IMicrophoneAudioTrack;
  localVideoTrack?: ICameraVideoTrack
} = {
  client: undefined,
  localAudioTrack: undefined,
  localVideoTrack: undefined,
}

const ws2 = createSocket(
  { teacher: teacher.user_id, student: '*' },
  {
    message(socketRes: TSocketRes<type_dyaw_xlfw_zxhd_log & { operate: CHAT_OPERATION }>) {
      if (socketRes.from_client_name.endsWith('teacher')) {
        // infoList.push(socketRes.content)
        if (socketRes.content.dxzl_stu_user_id === user.user_id) {
          switch (socketRes.content.operate) {
            case CHAT_OPERATION.START:
              auditChatStatus = CHAT_STATUS.WAITING_YOU_ACCEPT
              ChatAudioRef!.open()
              break;
            case CHAT_OPERATION.CANCEL:
              ChatAudioRef!.close()
              break;
            case CHAT_OPERATION.ACCEPT:
              auditChatStatus = CHAT_STATUS.CHATING
              break;
            case CHAT_OPERATION.DENY:
              ChatAudioRef!.close()
              break;
            case CHAT_OPERATION.END:
              ChatAudioRef!.close()
              break;
            default:
              break;
          }
        }
      }
    }
  }
)

enum CHAT_STATUS { 'WAITING_YOU_ACCEPT', 'WAITING_OTHERS_ACCEPT', 'WAITING_BUSY', 'CHATING' }
enum CHAT_OPERATION { 'START', 'CANCEL', 'ACCEPT', 'DENY', 'END' }
let auditChatStatus = $ref<CHAT_STATUS>(CHAT_STATUS.WAITING_OTHERS_ACCEPT)

const ChatAudioRef = $ref<typeof import("~/components/chat-dialog/index.vue")['default']>()
const ChatVideoRef = $ref<typeof import("~/components/chat-dialog/index.vue")['default']>()

function handleAuditChatStart() {
  ChatAudioRef!.open()
  socketSend(ws2, {
    dxzl_stu_user_id: dyaw_xlfw_zxhd!.dxz_stu_user_id,
    dxzl_tea_user_id: dyaw_xlfw_zxhd!.dxz_tea_user_id,
    operate: CHAT_OPERATION.START
  })
}
function handleAuditChatCancel() {
  socketSend(ws2, {
    dxzl_stu_user_id: dyaw_xlfw_zxhd!.dxz_stu_user_id,
    dxzl_tea_user_id: dyaw_xlfw_zxhd!.dxz_tea_user_id,
    operate: CHAT_OPERATION.CANCEL
  })
  ChatAudioRef!.close()
}
function handleAuditChatAccept() {
  socketSend(ws2, {
    dxzl_stu_user_id: dyaw_xlfw_zxhd!.dxz_stu_user_id,
    dxzl_tea_user_id: dyaw_xlfw_zxhd!.dxz_tea_user_id,
    operate: CHAT_OPERATION.ACCEPT
  })
  // ChatAudioRef!.close()
  auditChatStatus = CHAT_STATUS.CHATING
}
function handleAuditChatDeny() {
  socketSend(ws2, {
    dxzl_stu_user_id: dyaw_xlfw_zxhd!.dxz_stu_user_id,
    dxzl_tea_user_id: dyaw_xlfw_zxhd!.dxz_tea_user_id,
    operate: CHAT_OPERATION.DENY
  })
  ChatAudioRef!.close()
}
function handleAuditChatEnd() {
  socketSend(ws2, {
    dxzl_stu_user_id: dyaw_xlfw_zxhd!.dxz_stu_user_id,
    dxzl_tea_user_id: dyaw_xlfw_zxhd!.dxz_tea_user_id,
    operate: CHAT_OPERATION.END
  })
  ChatAudioRef!.close()
}
function handleVideoChatStart() {
  request({
    url: '/dyaw/xlfw_zxhd/get_rtc_token',
    data: {
      dxz_id: dyaw_xlfw_zxhd?.dxz_id
    }
  })
  // ChatVideoRef!.open()
}
</script>

<template>
  <div class="h-640px bg-hex-f2f2f295 flex justify-center divide-x">
    <div class="w-1000px h-full divide-y">
      <div class="bg-pink-300 flex justify-between h-48px items-center px-18px">
        <span class="text-lg px-1 tracking-wider">{{`${dyaw_xlfw_zxhd.dxz_tea_user_realname}老师正在为您服务`}}</span>
        <div class="text-pink-300 text-sm bg-white w-100px h-32px flex_center rounded-2xl cursor-pointer"
          @click="handleClickEnd">结束会话</div>
      </div>
      <div ref="scrollbarRef"
        class="bg-hex-fff8fb space-y-2 h-410px py-2 px-6 scrollbar scrollbar-thin scrollbar-thumb-rounded-md scrollbar-thumb-gray-200 scrollbar-track-transparent">
        <div class="w-full text-center text-sm">{{ formatTimestamp(dyaw_xlfw_zxhd.create_dateline) }} 开始沟通</div>
        <info-item v-for="item in infoList" :key="item.dxzl_id" :left="item.create_user_id === user.user_id"
          :d="item"></info-item>
      </div>
      <div class="bg-white h-180px p-5px flex flex-col justify-between">
        <!-- <div class="h-48px"></div>
        <el-input type="textarea"></el-input> -->
        <tinymce-area v-model="inputValue" ref="TinyRef" @click:audit="handleAuditChatStart"
          @click:video="handleVideoChatStart"></tinymce-area>
        <div class="flex justify-end">
          <div class="bg-pink-300 text-sm text-white w-80px h-32px flex_center rounded-2xl cursor-pointer"
            @click="handleClickSend">发送</div>
        </div>
      </div>
    </div>
    <div
      class="w-400px h-full space-y-4 bg-white overflow-y-auto flex flex-col items-stretch px-30px py-4 divide-y scrollbar scrollbar-thin scrollbar-thumb-rounded-md scrollbar-thumb-gray-200 scrollbar-track-transparent">

      <template v-if="teacherInfo">
        <div class="w-full">
          <img :src="teacherInfo.dxp_wx_qrcode" alt="">
        </div>
        <div class="py-4">
          <div class="text-lg font-bold max-w-24 truncate">{{ teacherInfo.dxp_user_realname }}</div>
          <div class="text-hex-5B9FF0">联系电话：{{ teacherInfo.dxp_user_phone }}</div>
          <div class=" text-hex-00000041 h-10 leading-5 mt-1">
            {{ teacherInfo.dxp_jj }}
          </div>
        </div>
      </template>
    </div>
  </div>

  <el-dialog v-model="rateDialogVisible" title="请评价" align-center width="405px">
    <p>于 {{ endTime }} 结束沟通</p>
    <div class="flex items-center my-4">
      <div>评价：</div>
      <el-rate size="large" v-model="rateNum"></el-rate>
    </div>
    <template #footer>
      <div class="flex_center">
        <el-button round type="primary" @click="handleConfirmRate">
          确认
        </el-button>
        <el-button round @click="rateDialogVisible = false">取消</el-button>
      </div>
    </template>

  </el-dialog>


  <chat-dialog ref="ChatAudioRef">
    <div class="h-full flex_center flex-col text-light-50 space-y-4">
      <el-avatar :size="158" :src="teacherInfo?.dxp_user_avatar"></el-avatar>
      <div>{{ teacherInfo?.dxp_user_realname }}</div>
      <!-- <div class="text-hex-909090 flex_center flex-col space-y-2 h-16"> -->
      <div class="text-hex-909090 flex_center flex-col space-y-2 h-16"
        v-show="auditChatStatus === CHAT_STATUS.WAITING_OTHERS_ACCEPT">
        <div>正在等待对方接受邀请</div>
        <i:line-md:loading-alt-loop class="text-xl" />
      </div>
      <div class="text-hex-909090 flex_center flex-col space-y-2 h-16"
        v-show="auditChatStatus === CHAT_STATUS.WAITING_YOU_ACCEPT">
        <div>邀请你语音通话...</div>
      </div>
      <div class="text-hex-909090 flex_center flex-col space-y-2 h-16"
        v-show="auditChatStatus === CHAT_STATUS.WAITING_BUSY">
        <div class="text-red-500">对方忙线中请等待</div>
        <div class="text-red-500">当前排队：{{ 4 }}</div>
        <i:line-md:loading-alt-loop class="text-xl" />
      </div>
      <div class="text-hex-909090 flex_center flex-col space-y-2 h-16" v-show="auditChatStatus === CHAT_STATUS.CHATING">
        <div>正在通话中</div>
        <div>{{ '00:30' }}</div>
      </div>
      <!-- </div> -->

      <div class="pt-16 text-xl flex justify-around w-full">
        <div v-show="auditChatStatus === CHAT_STATUS.WAITING_YOU_ACCEPT"
          class="bg-green-600 w-12 h-12 rounded-1 cursor-pointer flex items-center justify-around"
          @click="handleAuditChatAccept">
          <i:ic:baseline-phone />
        </div>
        <div v-show="auditChatStatus === CHAT_STATUS.WAITING_YOU_ACCEPT"
          class="bg-red-600 w-12 h-12 rounded-1 cursor-pointer flex items-center justify-around"
          @click="handleAuditChatDeny">
          <i:mdi:phone-hangup />
        </div>
        <div v-show="auditChatStatus === CHAT_STATUS.CHATING"
          class="bg-hex-efefef text-hex-272636 w-12 h-12 rounded-1 cursor-pointer flex items-center justify-around"
          @click="">
          <i:ant-design:audio-outlined v-show="true" />
          <i:ant-design:audio-muted-outlined v-show="false" />
        </div>
        <div v-show="auditChatStatus === CHAT_STATUS.CHATING"
          class="bg-red-600 w-12 h-12 rounded-1 cursor-pointer flex items-center justify-around"
          @click="handleAuditChatEnd">
          <i:ic:outline-close></i:ic:outline-close>
        </div>
        <div
          v-show="auditChatStatus === CHAT_STATUS.WAITING_OTHERS_ACCEPT || auditChatStatus === CHAT_STATUS.WAITING_BUSY"
          class="bg-red-600 w-12 h-12 rounded-1 cursor-pointer flex items-center justify-around"
          @click="handleAuditChatCancel">
          <i:ic:outline-close></i:ic:outline-close>
        </div>

      </div>
    </div>
  </chat-dialog>

  <chat-dialog ref="ChatVideoRef">
    <i:ant-design:audio-outlined />
    <i:ant-design:audio-muted-outlined />

    <i:material-symbols:video-camera-back-rounded />
    <i:material-symbols:video-camera-front-off-rounded />
  </chat-dialog>
</template>

<style scoped lang="scss">

</style>
