<template>
  <a-spin :spinning="state.loading" >
  <a-card
    style="min-height: 600px;"
  >
    <a-row justify="space-between" style="margin-bottom: 20px;" >
      <a-col span="12" >
        <a-select allowClear placeholder="请选择协议" v-model:value="state.name" style="width: 170px;" >
          <a-select-option
            v-for="item in protocolList"
            :key="item"
          >
            {{item}}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col  >
        <a-space>
          <a-button type="primary" @click="saveProtocol"> 保存 </a-button>
          <a-button type="primary" @click="reloadProtocol"> 更新 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <code-mirror-tsx
      :key="state.name"
      v-if="state.bodyJson"
      :body-json="state.bodyJson"
      body-type="json"
      ref="codeMirrorRef"
    />
    <a-empty  style="margin-top: 200px;" v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" description="请在左上角选择协议"/>

  </a-card>
</a-spin>
</template>
<script lang="ts" setup >
import { RtsController } from '@/controller/rts'
import { onMounted, reactive, ref, watch } from 'vue'
import { CodeMirrorTsx } from '@/components/CodeMirror/index'
import { useScheduler } from '@/hooks'
import { Empty } from 'ant-design-vue'

const protocolList = ['RTSP', 'RTMP', 'HLS', 'HDL', 'GB28181']

const codeMirrorRef = ref()

const state = reactive<{
  name: RTS.protocol | '',
  bodyJson: string
  loading: boolean
}>({
  name: 'RTSP',
  bodyJson: '',
  loading: false
})

watch(
  () => state.name,
  () => getProtocol()
)
const { start, stop } = useScheduler(() => state.loading = false, 2000)

const reloadProtocol = async () => {
  await RtsController.updateProtocol(state.name as RTS.protocol)
}

const saveProtocol = async () => {
  await RtsController.postProtocol(state.name as RTS.protocol, codeMirrorRef.value.getValue())
}

const getProtocol = async () => {
  state.loading = true
  const { data } = await RtsController.protocol(state.name as RTS.protocol)
  start()
  state.bodyJson = JSON.stringify(data)
}

onMounted(() => {
  getProtocol()
})
</script>

<style lang="less" scoped >
</style>
