<script setup lang='ts'>
import { showFailToast, showSuccessToast } from 'vant'
import QRCode from 'qrcode'
import { TypeMap, formatNumber, getFullPath } from '~/pages/detail/util'

const props = defineProps<{
  type: string
  tmk_id: string
  tmz_id: string
}>()

let truthPid = props.tmk_id === '-' ? undefined : props.tmk_id

const theType = TypeMap[props.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[]>([])

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

function scoreAtTarget(payload: object) {
  return request({
    url: '/openapi/user_view_log.php',
    data: {
      id: props.tmz_id,
      view_type: `txwx_${props.type}`,
      ...payload,
    },
  })
}

function init() {
  loading.value = true
  return request({
    url: `/txwx/${props.type}/detail`,
    data: {
      [theType.id]: props.tmz_id,
    },
  }).then((res) => {
    if (res?.code === '1') {
      detail.value = res.data.one_info
      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/${props.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.tmz_dzl++
    }
  })
}

function isShowHomework() {
  // return props.type === 'kclx' && detail.value?.tmz_zy
  return true
}

function routerToHomework() {
  console.log('routerToHomework')
  sessionStorage.setItem('tmp_detail', JSON.stringify(detail.value))
  router.push(`/detail/${props.type}/${truthPid}/${props.tmz_id}/homework`)
}
function routerToLearningGuide() {
  sessionStorage.setItem('tmp_detail', JSON.stringify(detail.value))
  router.push(`/detail/${props.type}/${truthPid}/${props.tmz_id}/learningGuide`)
}
</script>

<template>
  <van-nav-bar left-arrow @click-left="() => router.back()" @click-right="openShare">
    <template #right>
      <van-icon name="share-o" size="18" />
    </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>
        {{ 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-player
      :key="detail[theType.video]" :src="getFullPath(detail[theType.video])"
      :poster="getFullPath(detail[theType.img])" @scoreAtTarget="scoreAtTarget"
    />

    <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 v-if="isShowHomework" class="flex items-center justify-between px-14px mb-2" @click="routerToHomework">
      <div class="text-16px font-bold">
        作业 & 答案
      </div>
      <van-icon name="arrow" size="18" />
    </div>
  <div v-if="isShowHomework" class="flex items-center justify-between px-14px mb-2"     @click="routerToLearningGuide">
      <div class="text-16px font-bold">
       导学案
      </div>
      <van-icon name="arrow" size="18" />
    </div>
    <div
      class="flex items-center justify-between px-14px "
      @click="router.push(`/detail/${props.type}/${truthPid}/list`)"
    >
      <div class="text-16px font-bold">
        相关章节
      </div>
      <van-icon name="arrow" size="18" />
    </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/${props.type}/${truthPid}/${item[theType.id]}`)"
      >
        <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>
