<template>
  <Box title="监控">
    <div class="h-full flex flex-col">
      <div class="py-10px relative" v-if="!isBase">
        <div
          class="text-center bg-clip-text text-transparent bg-gradient-to-t from-[#76E9F0] to-[#A7E6EE] text-14px font-bold"
        >
          {{ currentTabValue }}
        </div>
        <div
          class="absolute right-18px top-1/2 transform -translate-y-1/2"
          v-if="tabList.length > 1"
        >
          <Dropdown
            overlayClassName="dropdownClass"
            placement="bottomRight"
            trigger="click"
            :style="{ height: '300px' }"
          >
            <div class="cursor-pointer">
              <span class="text-white text-12px">更多</span>
              <DownOutlined :style="{ fontSize: '12px', color: '#FFF' }" />
            </div>
            <template #overlay>
              <Menu @click="onMenuClick">
                <menu-item v-for="item in tabList" :key="item.id">
                  <div>{{ item.name }}</div>
                </menu-item>
              </Menu>
            </template>
          </Dropdown>
        </div>
      </div>
      <div class="flex-1 flex flex-col py-0px box-content" :class="{ 'pt-0': !isBase }">
        <div class="flex-1">
          <div
            class="h-130px"
            :class="{ '!h-160px': isBase }"
            v-for="(item, index) in listBig"
            :key="item.url + index"
          >
            <VideoFlv
              @onScreen="onScreenClick"
              class="cursor-pointer"
              :url="item.url"
              :name="item.base_name"
            />
          </div>
        </div>
        <div class="overflow-y-auto h-80px" v-if="isBase">
          <div class="grid grid-cols-3 gap-x-6px pt-10px" v-for="(ar, i) in listSmall" :key="i">
            <div class="h-66px" v-for="item in ar" :key="item.id">
              <VideoFlv
                @onScreen="onScreenClick"
                class="cursor-pointer"
                :url="item.url"
                :name="item.base_name"
                :screen="true"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <LinkModal
      v-model:visible="visibleModal"
      :footer="null"
      :title1="currentModelVideo && currentModelVideo.name"
      :width="1100"
    >
      <template #content>
        <div class="w-full">
          <VideoFlv
            v-if="currentModelVideo.url"
            :url="currentModelVideo.url"
            :screen="false"
            :name="currentModelVideo.name"
          />
        </div>
      </template>
    </LinkModal>
  </Box>
</template>

<script lang="ts">
  import {
    defineComponent,
    reactive,
    ref,
    onBeforeMount,
    computed,
    toRefs,
    toRaw,
    onBeforeUnmount,
  } from 'vue'
  import { DownOutlined } from '@ant-design/icons-vue'
  import { Dropdown, Menu } from 'ant-design-vue'
  import { getAgriculturalDeviceBasic, getDevices, getffmpegip } from '/@/api/sys/other'
  import Box from './Box.vue'
  import VideoFlv from './VideoFlv.vue'
  import v01 from '../../../assets/images/v01.png'
  import v02 from '../../../assets/images/v02.png'
  import v03 from '../../../assets/images/v03.png'
  import LinkModal from '../LinkModal.vue'
  import axios from 'axios'
  export default defineComponent({
    components: {
      Box,
      Dropdown,
      DownOutlined,
      Menu,
      MenuItem: Menu.Item,
      VideoFlv,
      LinkModal,
    },
    props: ['baseId'],
    setup(props) {
      console.log('===JK')
      console.log(props.baseId)
      const Data = reactive({
        tabList: ref<any>([]),
        currentTab: ref<number | string>(''),
        list: ref<any[]>([]),
      })

      const visibleModal = ref(false)

      const chartRef = ref<HTMLDivElement | null>(null)

      const currentVido = ref<any>(null)

      const currentModelVideo = ref<any>(null)

      const listSmall = computed(() => chunkArray(Data.list?.slice(1, Data.list.length) ?? [], 3))
      const listBig = computed(() => Data.list.slice(0, 1))

      const currentTabValue = computed(
        () => Data.tabList.find((e) => e.id == Data.currentTab)?.name ?? '',
      )

      function onMenuClick({ key }) {
        if (Data.currentTab == key) return
        Data.currentTab = key
        getData()
      }

      function chunkArray(array, chunkSize) {
        const result = []
        for (let i = 0; i < array.length; i += chunkSize) {
          result.push(array.slice(i, i + chunkSize))
        }
        return result
      }

      async function getTabs() {
        const resData = await getAgriculturalDeviceBasic({
          device_type: 1,
          is_recommended: props.baseId ? null : 1,
        })
        Data.tabList = resData
        if (resData.length) Data.currentTab = resData[0].id
        getData()
      }

      async function getData() {
        const { ip, port, change_time } = await getffmpegip()

        const resData = await getDevices({
          base_id: props.baseId ?? Data.currentTab,
          type: 1,
          status: 1,
          is_recommend: props.baseId ? null : 1,
        })
        Data.list = []

        currentVido.value = null

        const arr = resData.splice(0, 4)
        const list: any = []

        for (let index = 0; index < arr.length; index++) {
          const e = arr[index]

          const option = toRaw(e)
          const { supplier, extends: extend, sn } = option

          const { rtsp_url } = extend
          const url = rtsp_url
          let playUrl: any = `ws://${ip}:${port}/rtsp?url=${window.btoa(url)}`
          if (supplier?.id == 'device-supplier-biang') {
            try {
              playUrl = await getSeedingLive({
                username: extend.username,
                password: extend.password,
                equipmentCode: sn,
                channelNo: extend.passage,
              })
            } catch (error) {}
          }
          list.push(
            Object.assign(
              {},
              {
                ...e,
                img: index == 0 ? v01 : index == 1 ? v02 : index == 2 ? v03 : v01,
                url: playUrl,
              },
            ),
          )
        }

        Data.list = list
        console.log(Data.list[0])

        if (Data.list.length > 0) currentVido.value = Data.list[0]

        if (!isBase.value) {
          autoChage(change_time)
        }
      }

      function getSeedingLive(params) {
        return new Promise(async (resolve, reject) => {
          try {
            const { data } = await axios.get(
              'https://yun.bigdata5s.com/api/open-api/open/getSeedingLive',
              {
                params,
              },
            )
            if (data.code == 200) resolve(data.data)
            else reject(data)
          } catch (error) {
            reject(error)
          }
        })
      }

      let timer: any = null

      function autoChage(time) {
        timer && clearInterval(timer)
        if (time == 0) return
        timer = setInterval(() => {
          const index = Data.tabList.findIndex((e) => e.id == Data.currentTab)
          const currentIndex = index + 1
          const current = Data.tabList[currentIndex % Data.tabList.length]
          onMenuClick({ key: current.id, ...current })
        }, 1000 * time)
      }

      function onChangeVideo(e) {
        if (currentVido.value.url == e.url) return
        currentVido.value = e
      }

      function onScreenClick(e) {
        currentModelVideo.value = e
        visibleModal.value = true
      }

      const isBase = computed(() => !!props.baseId)

      onBeforeMount(() => {
        if (isBase.value) {
          getData()
        } else {
          getTabs()
        }
      })

      onBeforeUnmount(() => {
        timer && clearInterval(timer)
      })

      return {
        isBase,
        listBig,
        listSmall,
        onChangeVideo,
        currentVido,
        currentModelVideo,
        ...toRefs(Data),
        chartRef,
        currentTabValue,
        onMenuClick,
        visibleModal,
        onScreenClick,
      }
    },
  })
</script>
