<script setup lang='ts'>
import { showFailToast, showSuccessToast } from 'vant'
import QRCode from 'qrcode'
import 'aliyun-webrtc-sdk'
import { TypeMap, formatNumber, getFullPath } from '~/pages/detail/util'
import { user } from '~/store'
import zzzbImg from '~/assets/zzzb.png'

let fromZlb = localStorage.getItem('fromZlb') === '1'
const props = defineProps<{
  // type: string
  tmk_id: string
  tmz_id: string
}>()
let truthPid = props.tmk_id === '-' ? undefined : props.tmk_id

const _type_ = 'zbkc_ks'
const theType = TypeMap[_type_]

const router = useRouter()
const route = useRoute()

const showShare = ref(false)
function openShare() {
  showShare.value = true
}

const qrshow = ref(false)
const qrsrc = ref('')
function handleShareSelect(option: any) {
  const link = location.href
  switch (option.icon) {
    case 'link':
      navigator.clipboard.writeText(link).then(() => {
        showShare.value = false
        showSuccessToast('已复制到剪贴板')
      }).catch(() => {
        showFailToast('当前环境不支持复制链接')
      })

      break
    case 'qrcode':
      QRCode.toDataURL(link, (err, url) => {
        if (err)
          showFailToast('生成二维码失败')
        qrsrc.value = url
        showShare.value = false
        qrshow.value = true
      })
      break
    default:
      break
  }
}

const loading = ref(true)
const detail = ref<any>()
const rows = ref<any[]>([])

const isRtcUser = ref(false)
const isRtcTime = ref(false)
const isRtcing = ref(false)
const rtcPlayerRef = ref()

function fixTruthPid(pid: string) {
  const routePid = truthPid
  if (routePid !== pid) {
    console.info('纠正pid', pid)
    truthPid = pid
  }
  return truthPid
}

const aliWebrtc = new AliRtcEngine()
aliWebrtc.setVideoProfile({
  frameRate: 20,
  width: 1280,
  height: 720,
}, 1)

async function initRTC() {
  const response = await fetch(`https://push.txhlwxx.com/openapi/rtcsdk/login?user_id=${user.value?.user_id}&tzk_id=${props.tmz_id}`)
  const data = await response.json()

  const options = {
    ...data.data,
    channel: props.tmz_id,
  }
  console.log('rtc options : ', options)
  await aliWebrtc.startPreview(
    rtcPlayerRef.value,
  ).then(() => {
    console.log('预览成功')
  }).catch((error: any) => {
    console.error('预览失败 : ', error)
  })

  await aliWebrtc.joinChannel(options, user.value?.user_realname).then(() => {
    console.log('入会成功')
  }, (error: any) => {
    console.error('入会失败 : ', error)
  })

  isRtcing.value = true

  return aliWebrtc
}

function init() {
  loading.value = true
  return request({
    url: `/txwx/${_type_}/detail`,
    data: {
      [theType.id]: props.tmz_id,
      live: 1,
    },
  }).then((res) => {
    if (res?.code === '1') {
      detail.value = res.data.one_info
      isRtcUser.value = user.value?.user_id === detail.value.tzk_zjr_user_id
      // isRtcUser.value = true
      isRtcTime.value = detail.value.status === 1 || detail.value.status === 2
      // isRtcTime.value = true
      const otherData: any = {}
      if (Array.isArray(theType.pid)) {
        const t: string[] = []
        theType.pid.forEach((item: string) => {
          otherData[item] = detail.value[item]
          t.push(detail.value[item])
        })
        fixTruthPid(t.join('-'))
      }
      else {
        otherData[theType.pid] = detail.value[theType.pid]
        fixTruthPid(detail.value[theType.pid])
      }
      return request({
        url: `/txwx/${_type_}/index`,
        data: {
          // [theType.pid]: props.tmk_id,
          ...otherData,
          limit: 4,
        },
      }).then((res) => {
        if (res?.code === '1')
          rows.value = res.data.page_data
      })
    }
  }).finally(() => {
    loading.value = false
  })
}

watch(
  () => route.params,
  () => {
    init()
  },
  { immediate: true },
)

function handleGoodjob() {
  if (detail.value.is_like)
    return
  request({
    url: '/txwx/dz/add',
    data: {
      txwx_dz: {
        td_kclx: theType?.idx,
        td_dz_id: detail.value[theType.id],
        td_keyword: detail.value[theType.title],
      },
    },
  }).then((res) => {
    if (res?.code === '1') {
      showSuccessToast('点赞成功')
      detail.value.is_like = 1
      detail.value[theType.dzl] = parseInt(detail.value[theType.dzl]) + 1
    }
  })
}

async function handleStartRtc() {
  try {
    await aliWebrtc.isSupport()
  }
  catch (error) {
    return showFailToast('当前浏览器不支持直播')
  }
  try {
    await initRTC()
  }
  catch (e) {
    console.error('初始化rtc失败')
    return showFailToast('初始化rtc失败')
  }
  await aliWebrtc.publish()
  await fetch(`https://push.txhlwxx.com/openapi/rtcsdk/push?user_id=${user.value?.user_id}&stream=zbkc_${truthPid}_${props.tmz_id}`)
    .then(res => res.json())
    .then((res) => {
      console.log('推流res : ', res)
      if (res?.code !== '1')
        showFailToast(res.msg)
    })
    .catch((error) => {
      console.error('推流失败 : ', error)
    })
}
function handleEndRtc() {
  fetch(`https://push.txhlwxx.com/openapi/rtcsdk/push?user_id=${user.value?.user_id}&stream=zbkc_${truthPid}_${props.tmz_id}&do=stop`)
  aliWebrtc.unPublish()
  aliWebrtc.leaveChannel()
  aliWebrtc.stopPreview()
  aliWebrtc.muteLocalCamera(true)
  aliWebrtc.muteLocalMic(true)

  request({
    url: '/txwx/zbkc_ks/edit',
    data: {
      tzk_id: props.tmz_id,
      txwx_zbkc_ks: {
        // yyyy-mm-dd hh:mm:ss
        tzk_zbjssj: new Date().toLocaleString().replace(/\//g, '-').replace(/\b\d\b/g, '0$&'),
      },
    },
  })

  isRtcing.value = false
}

function handleNavRightClick() {
  if (isRtcUser.value && isRtcTime.value) {
    if (isRtcing.value) {
      handleEndRtc()
      console.log('结束直播 ')
    }
    else {
      request({
        url: '/txwx/zbkc_ks/edit',
        data: {
          tzk_id: props.tmz_id,
          txwx_zbkc_ks: {
            // yyyy-mm-dd hh:mm:ss
            tzk_zbjssj: '0000-00-00 00:00:00',
          },
        },
      })
      handleStartRtc()
    }
  }
  else { openShare() }
}

function test() {
  request({
    url: '/txwx/zbkc_ks/edit',
    data: {
      tzk_id: props.tmz_id,
      txwx_zbkc_ks: {
        // yyyy-mm-dd hh:mm:ss
        tzk_zbjssj: '0000-00-00 00:00:00',
      },
    },
  })
}
</script>

<template>
  <van-nav-bar :left-arrow="!fromZlb" @click-left="() => router.back()" @click-right="handleNavRightClick">
    <template #right>
      <template v-if="!loading">
        <span v-if="isRtcUser && isRtcTime">{{ isRtcing ? '结束直播' : '开始直播' }}</span>
        <van-icon v-else name="share-o" size="18" />
      </template>
    </template>
  </van-nav-bar>
  <van-share-sheet
    v-model:show="showShare" title="立即分享给好友"
    :options="[{ name: '复制链接', icon: 'link' }, { name: '二维码', icon: 'qrcode' }]" @select="handleShareSelect"
  >
    <template
      #description
    >
      注意：复制链接功能仅限手机浏览器中打开；微信，钉钉等第三方应用中无法使用。
    </template>
  </van-share-sheet>
  <van-dialog v-model:show="qrshow" title="请截图保存并分享二维码">
    <div class="flex flex-col items-center py-32px">
      <img :src="qrsrc">
      <div @click="test">
        {{ detail[theType.title] }}
      </div>
    </div>
  </van-dialog>

  <div v-if="loading" class="flex justify-center pt-32px">
    <van-loading type="spinner" />
  </div>
  <template v-else>
    <video v-if="isRtcUser" ref="rtcPlayerRef" class="w-100vw h-56.25vw bg-dark-900" controls />
    <video-player-rtc
      v-else :d="detail" :src="getFullPath(detail[theType.video])"
      :poster="getFullPath(detail[theType.img])"
    />

    <div class="px-14px py-20px">
      <div class="text-14px font-bold">
        {{ detail[theType.title] }}
      </div>
      <div class="flex justify-between items-center text-14px px-2px py-12px">
        <div class="text-gray-400">
          {{ detail[theType.teacher] }}
        </div>
        <div class="flex  text-hex-333  text-12px leading-12px">
          <div class="flex items-center">
            <van-icon name="eye-o" size="14" />
            <div class="ml-2px">
              {{ formatNumber(detail[theType.lll]) }}
            </div>
          </div>
          <div
            class="flex items-center ml-6px" :class="detail.is_like === 1 ? 'text-red-500' : ''"
            @click="handleGoodjob"
          >
            <van-icon :name="detail.is_like === 1 ? 'good-job' : 'good-job-o'" size="14" />
            <div class="ml-2px">
              {{ formatNumber(detail[theType.dzl]) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="flex items-center justify-between px-14px ">
      <div class="text-16px font-bold">
        相关章节
      </div>
      <van-icon
        name="arrow" size="18"
        @click="router.push({ name: 'detail-type-tmk_id-list', params: { type: _type_, tmk_id: truthPid } })"
      />
    </div>

    <div class="px-14px py-20px grid grid-cols-2 gap-10px">
      <div
        v-for="item in rows" :key="item[theType.id]"
        class="relative w-44vw rounded-8px overflow-hidden shadow flex flex-col"
        @click="router.replace(`/detail/${_type_}/${truthPid}/${item[theType.id]}`)"
      >
        <div
          v-if="item.status === 1"
          class="rounded-tl-6px rounded-br-6px absolute top-0 left-0 text-12px text-white bg-hex-ef7a02d9 px-10px py-5px"
        >
          {{ item.status_msg }}
        </div>
        <div
          v-if="item.status === 2"
          class="rounded-t-6px absolute z-10 w-full h-100px top-0 left-0 text-14px text-hex-00A3FF bg-hex-00000066 flex items-center"
        >
          <div class="text-center w-full">
            <img class="m-auto" :src="zzzbImg" alt="">
            <div>{{ item.status_msg }}</div>
          </div>
        </div>
        <div
          v-if="item.status === 3"
          class="rounded-tl-6px rounded-br-6px absolute top-0 left-0 text-12px text-white bg-hex-797979d9 px-10px py-5px"
        >
          {{ item.status_msg }}
        </div>

        <div class="absolute top-0 right-0 flex text-12px px-6px py-4px text-white bg-hex-00000050">
          <div class="flex items-center">
            <van-icon name="eye-o" size="12" />
            <div class="ml-4px w-24px tracking-tighter">
              {{ formatNumber(item[theType.lll]) }}
            </div>
          </div>
          <div class="flex items-center ml-4px">
            <van-icon name="good-job-o" size="12" />
            <div class="ml-4px w-24px tracking-tighter">
              {{ formatNumber(item[theType.dzl]) }}
            </div>
          </div>
        </div>
        <img :src="getFullPath(item[theType.img])" alt="" class="w-full h-24.75vw">
        <div class="p-8px  flex-auto flex flex-col justify-between">
          <div class="text-14px font-bold pb-8px leading-16px truncate">
            {{ item[theType.title] }}
          </div>
          <div class="flex justify-between text-12px ">
            <div class="whitespace-nowrap mr-8px">
              {{ item[theType.teacher] }}
            </div>
            <div class="truncate max-w-48px">
              {{ item[theType.school] }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
</template>
