<script setup>
import QrcodeVue from "qrcode.vue";
// import CommonHeader from "@/components/CommonHeader/index.vue";
import CheckRow from "~/components/CheckRow/index.vue";

import img_lczs from '~/assets/zbktssys/bar.png';


import { View as IconView, Histogram as IconHistogram, Search as IconSearch } from '@element-plus/icons-vue';
import { getFullUrl, getAvatarUrl } from '~/utils/helper';
import { user } from '~/store/user';
import { ElMessage } from "element-plus";
const props = defineProps({
  status: String
})
const queryForm = reactive({
  ks_status: props.status,
  grade_id: undefined,
  subject_id: undefined,
  team_id: undefined,
  limit: 10,
  page: 1,
})
const keyword = $ref('')

watch(
  queryForm,
  () => {
    queryData()
  }
)

function queryData() {
  request({
    url: '/kzkt/ssyskc/index',
    data: { ...queryForm, keyword, is_qtxs: queryForm.ks_status === '3' ? 1 : undefined }
  }).then(res => {
    if (res.code === '1') {
      data = res.data.page_data
      total = res.data.total_rows * 1
    }
  })
}

// let nj = $ref()
// let fc = $ref()

// request({
//   url: '/jcxx/grade/index',
//   data: {
//     limit: 99
//   }
// }).then(res => {
//   if (res.code === '1') {
//     nj = [{ n: '全部', v: undefined }].concat(res.data.page_data.map(({ grade_name, grade_id }) => ({ v: grade_id, n: grade_name })))
//   }
// })

let nj = $ref([])
let km = $ref([])

function queryParams() {
  return Promise.all([
    request({
      url: '/jcxx/grade/index',
      data: {
        limit: 99
      }
    }).then(res => {
      if (res.code === '1') {
        nj = [{ n: '全部', v: undefined }].concat(res.data.page_data.map(({ grade_name, grade_id }) => ({ v: grade_id, n: grade_name })))
      }
    })
    ,
    request({
      url: '/jcxx/subject/index',
      data: {
        limit: 99
      }
    }).then(res => {
      if (res.code === '1') {
        km = [{ n: '全部', v: undefined }].concat(res.data.page_data.map(({ subject_name, subject_id }) => ({ v: subject_id, n: subject_name })))
      }
    })
  ])
}
queryParams()

let data = $ref([])
let total = $ref(0)

request({
  url: '/kzkt/ssyskc/index',
  data: { ...queryForm, keyword, is_qtxs: queryForm.ks_status === '3' ? 1 : undefined }
}).then(res => {
  if (res.code === '1') {
    // fc = [{ n: '全部', v: undefined }].concat(res.data.table_structure.field.team_id.option)
    data = res.data.page_data
    total = res.data.total_rows * 1
  }
})


function hrefTo(href) {
  window.open(href, '_blank')
}

const router = useRouter()

function handleJyClick(row) {
  router.push(`/zbkt/ssys/content/${row.ks_id}/${row.ks_status}`)
}

function handleRtcClick(row) {
  if (row.ks_status === 2) {
    try {
      let arr1 = row.ks_kzms_json ? JSON.parse(row.ks_kzms_json) : [];
      let arr2 = row.ks_qkls_json ? JSON.parse(row.ks_qkls_json) : [];
      const jiedui = arr1.concat(arr2)
      // router.push(`/zbkt/ssys/rtc/${row.ks_id}`)
      if (jiedui.some(({ user_id }) => user_id === user.user_id)) { router.push(`/zbkt/ssys/rtc/${row.ks_id}`) }
      else {
        ElMessage.info('您无权访问该页面')
      }
    } catch (error) {
      console.log('handleRtcClick error :>> ', error);
    }
  }
}

function handleHfClick(row) {
  router.push(`/zbkt/ssys/video/${row.ks_id}/${row.ks_status}`
  )
}

async function copyLink(link) {
  await navigator.clipboard.writeText(link);
  ElMessage.success("已复制");
}

function getQrcodeList(ksInfo) {
  const ks_kzms = ksInfo.ks_kzms_hls ?? [];
  const ks_qkls = ksInfo.ks_qkls_hls ?? [];
  return [...ks_kzms, ...ks_qkls].map(({ user_realname, hls }) => ({
    user_realname,
    qrlink: `https://pull.txhlwxx.com/ssys.php?source=${hls}&cover=${ksInfo.ks_img}`
  }))
}

// function getDownList(ksInfo) {
//   const ks_kzms = ksInfo.ks_kzms_flv ?? [];
//   const ks_qkls = ksInfo.ks_qkls_flv ?? [];
//   return [...ks_kzms, ...ks_qkls].map(({ user_realname, flv }) => ({
//     user_realname,
//     downlink: flv
//   }))
// }
// // download file
// function downloadFile(url){
//   const el = document.createElement('a')
//   el.setAttribute('href', url)
//   el.setAttribute('download', '')
//   el.click()
// }

</script>

<template>
  <common-header />
  <div class="w-full flex items-center justify-center shadow-sm h-60px bg-hex-fefefe">
    <div class="w-1400px flex items-center">
      <div class="text-lg text-hex-050026">全景课堂</div>
      <el-divider direction="vertical" />
      <div class="text-sm">
        <span class="text-hex-949494">直播课堂</span>
        <span> - 全景课堂</span>
      </div>
    </div>
  </div>

  <div class="w-full relative h-200px">
    <img :src="img_lczs" alt="" class="w-full h-full">
    <div class="w-full h-full absolute top-0 z-2 flex flex-col items-center justify-evenly">
      <div class="text-hex-fff text-5xl">全景课堂</div>
      <el-input class="input w-500px h-50px rounded-md" placeholder="搜索关键字" v-model="keyword">
        <template #suffix>
          <div class="w-26px h-26px bg-hex-00A3FF rounded-md flex justify-center items-center cursor-pointer"
            @click="queryData()">
            <el-icon size="13" color="#fff">
              <IconSearch />
            </el-icon>
          </div>
        </template>
      </el-input>
    </div>
  </div>

  <div class="w-full flex items-center justify-center mt-4">
    <div class="w-1400px flex flex-col">
      <div class="w-full">
        <el-tabs v-model="queryForm.ks_status">

          <el-tab-pane label="待开始" name="1"></el-tab-pane>
          <el-tab-pane label="进行中" name="2"></el-tab-pane>
          <el-tab-pane label="已结束" name="3"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="mt-4">
        <check-row v-model="queryForm.grade_id" label="年级" :items="nj"></check-row>
        <check-row v-model="queryForm.subject_id" label="科目" :items="km"></check-row>
        <!-- <check-row v-model="queryForm.team_id" label="分册" :items="fc"></check-row> -->

      </div>

      <div class="flex flex-wrap justify-between">
        <template v-if="data.length">
          <div class="w-647px h-155px rounded-xl shadow-lg my-7 flex overflow-hidden" v-for="i in data">
            <div class="w-264px h-full flex-none">
              <img :src="getFullUrl(i.ks_img)" alt="" class="w-full h-full">
            </div>
            <div class="p-2 pr-6 flex-auto flex flex-col">
              <div class="flex justify-between w-full items-center py-1">
                <div class="font-bold">{{ i.ks_name }}</div>
                <div class="text-hex-949494 text-sm flex justify-between items-center">
                  <el-icon :size="14" color="#949494">
                    <icon-view />
                  </el-icon>
                  <span class="ml-1">{{ i.kss_views || '0' }}</span>
                </div>
              </div>

              <div class="text-sm text-hex-949494 py-1 line-clamp-2 overflow-ellipsis h-12 ">
                {{ i.ks_brief }}
              </div>

              <div class="text-sm py-1 flex-auto">
                <span>{{ i.grade_name }}</span>
                <span class="mx-2">|</span>
                <span>{{ i.subject_name }}</span>
              </div>

              <div class="flex text-sm justify-between items-center w-full">
                <div class="cursor-pointer flex items-center flex-auto">
                  <!-- getAvatarUrl(i.user_id) -->
                  <el-avatar :size="16" :src="i.user_avatar" class="flex-none"></el-avatar>
                  <!-- <img :src="i.user_avatar" class="w-4 h-4" alt=""> -->
                  <el-tooltip effect="dark" :content="i.ks_zjjsxm">
                    <span class="ml-1 w-18 truncate">{{ i.ks_zjjsxm }}</span>
                  </el-tooltip>
                </div>
                <el-popover trigger="hover" width="auto">
                  <template #reference>
                    <i:ic:baseline-qrcode v-if="i.ks_status === 2" class="mr-2 text-dark-50 cursor-pointer" />
                  </template>

                  <div class="flex space-x-2 flex-wrap max-w-900px">
                    <div v-for="({ user_realname, qrlink }) in getQrcodeList(i)" class="flex flex-col space-y-2">
                      <div>{{ user_realname }}</div>
                      <qrcode-vue :value="qrlink" :size="120" level="H" />
                      <el-button size="small" type="primary" @click="copyLink(qrlink)">复制链接</el-button>
                    </div>
                  </div>
                </el-popover>
                <!-- <el-popover trigger="hover" width="auto">
                  <template #reference>
                    <i:ic:baseline-file-download v-if="i.ks_status === 3" class="mr-2 text-dark-50 cursor-pointer" />
                  </template>

                  <el-empty description="暂未提供下载" :image-size="70" v-if="!(getDownList(i).length)"></el-empty>
                  <div class="flex space-x-2 flex-wrap max-w-900px" v-else>
                    <div v-for="({ user_realname, downlink }) in getDownList(i)" class="flex flex-col space-y-2">
                      <div>{{ user_realname }}</div>
                      <el-button size="small" type="primary" @click="downloadFile(downlink)">点击下载</el-button>
                    </div>
                  </div>
                </el-popover> -->

                <div @click="handleRtcClick(i)"
                  class="h-26px rounded-14px px-2 flex items-center text-hex-0083C5 cursor-pointer flex-none mr-2"
                  :class="i.ks_status === 2 && 'border border-hex-f00 text-hex-f00'">
                  <i-bx:bar-chart></i-bx:bar-chart>
                  <span class="ml-2 "> {{ i.ks_status_msg }}</span>
                </div>
                <div class="flex flex-none">
                  <div
                    class="h-26px leading-26px px-4 bg-gradient-to-l from-green-400 to-blue-500 text-white rounded-14px cursor-pointer"
                    @click="handleJyClick(i)">
                    讲义</div>

                  <div v-show="i.ks_status == 3"
                    class="ml-4 h-26px leading-26px px-4 bg-gradient-to-l from-red-500 to-blue-500 text-white rounded-14px cursor-pointer"
                    @click="handleHfClick(i)">
                    回放</div>
                </div>

              </div>

            </div>
          </div>
        </template>

        <div v-else class="flex justify-center w-full">
          <el-empty description="暂无直播" />
        </div>
      </div>

      <div class="flex justify-end mb-8">
        <el-pagination background layout="prev, pager, next" :total="total" v-model:current-page="queryForm.page" />
      </div>
    </div>
  </div>
  <common-footer />
</template>

<style scoped>
.border_b {
  border-bottom: 1px solid #e4e6e8;
}

:deep(.el-tabs__nav-wrap::after) {
  background-color: transparent;
}

.input {
  height: 50px;
  width: 500px;
}
</style>
