<template>
  <div id="mediaServer" class="iot-sip-mediaServer">
    <el-card style="padding-bottom: 100px; border: 0" v-loading="loading" shadow="never">
      <div class="mb-8">
        <el-button type="primary" :icon="Plus" size="small" @click="add">{{
          t('sip.mediaServer998535-0')
        }}</el-button>
        <el-button type="warning" plain :icon="Refresh" size="small" @click="getServerList"
          >刷新</el-button
        >
      </div>
      <el-row :gutter="30">
        <el-col
          :xs="24"
          :sm="12"
          :md="12"
          :lg="8"
          :xl="6"
          v-for="(item, index) in mediaServerList"
          :key="index"
          style="margin-bottom: 30px; text-align: center"
        >
          <div class="card-box-outer">
            <el-card shadow="always" class="card-item">
              <el-row :gutter="10">
                <el-col :span="15">
                  <el-descriptions :column="1" size="small" style="white-space: nowrap">
                    <el-descriptions-item :label="t('sip.mediaServer998535-1')">
                      {{ item.serverId }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('sip.mediaServer998535-2')">
                      {{ item.ip }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('sip.mediaServer998535-3')">
                      {{ item.protocol }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('sip.mediaServer998535-4')">
                      {{ parseTime(item.createTime, '{y}-{m}-{d}') }}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-col>
                <el-col :span="8">
                  <div style="margin-top: 10px">
                    <el-image :src="zlmLogo" fit="fit" />
                  </div>
                </el-col>
              </el-row>
              <el-button-group style="margin-top: 10px">
                <el-button
                  class="text-[#ff6363]!"
                  style="padding: 5px 10px"
                  :icon="Delete"
                  @click="del(item)"
                  >删除</el-button
                >
                <el-button
                  class="text-[#0147eb]!"
                  size="small"
                  style="padding: 5px 15px; margin: 0 10px"
                  :icon="View"
                  @click="view(item)"
                  >查看</el-button
                >
                <el-button
                  v-if="!istrue"
                  class="text-[#67c23b]!"
                  size="small"
                  style="padding: 5px 15px"
                  :icon="Odometer"
                  @click.prevent="edit(item)"
                >
                  编辑
                </el-button>
                <el-button
                  v-else
                  class="success-btn"
                  size="small"
                  style="padding: 5px 15px"
                  :icon="Odometer"
                  :loading="true"
                  disabled
                  >{{ t('sip.mediaServer998535-5') }}</el-button
                >
              </el-button-group>
            </el-card>
          </div>
        </el-col>
      </el-row>
      <div v-if="total === 0">
        <el-empty description="暂无数据" :image-size="80" />
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[12, 24, 36, 60]"
        @pagination="getServerList"
      />
    </el-card>

    <mediaServerEdit
      ref="mediaServerEditRef"
      :edit-flag="editFlag"
      @getServerList="getServerList"
      @delay="delay"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { Plus, Refresh, Delete, View, Odometer } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import mediaServerEdit from './mediaServer-edit.vue'
import { delmediaServer, listmediaServer } from '@/api/pms/video/mediaServer'
import { parseTime } from '@/utils/dateUtil'
import zlmLogo from '@/assets/imgs/zlm-logo.png'
// 使用组合式API
const { t } = useI18n()

// refs
const mediaServerEditRef = ref(null)

// 数据状态
const loading = ref(true)
const editFlag = ref(false)
const istrue = ref(false)
const mediaServerList = ref([]) //设备列表
const winHeight = ref(window.innerHeight - 200)
const updateLooper = ref(false)
const currentPage = ref(1)
const count = ref(15)
const num = ref(getNumberByWidth())
const total = ref(0)

defineOptions({
  name: 'VideoCenterMediaServer'
})

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

// 生命周期钩子
onMounted(() => {
  initData()
  // updateLooper.value = setInterval(initData, 2000)
})

onUnmounted(() => {
  clearTimeout(updateLooper.value)
})

// 初始化数据
const initData = () => {
  getServerList()
}

// 页码变化
const pageNumChange = (val) => {
  queryParams.pageNo = val
  getServerList()
}

// 页面大小变化
const pageSizeChange = (val) => {
  queryParams.pageSize = val
  getServerList()
}

// 获取服务器列表
const getServerList = () => {
  loading.value = true
  // 获取服务器列表: 实际要用的
  listmediaServer(queryParams).then((response) => {
    mediaServerList.value = response.list
    total.value = response.total
    loading.value = false
  })
}

// 添加
const add = () => {
  mediaServerEditRef.value.openDialog(null, initData, editFlag.value)
  editFlag.value = true
}

// 查看
const view = (row) => {
  mediaServerEditRef.value.openDialog(row, initData, editFlag.value)
  editFlag.value = false
}

// 编辑
const edit = (row) => {
  mediaServerEditRef.value.openDialog(row, initData, editFlag.value)
  editFlag.value = true
}

// 延迟处理
const delay = () => {
  let n = 5
  // 定义定时器time
  const time = setInterval(() => {
    istrue.value = true
    n--
    // 如果n<0，清除定时器，禁用状态取消，文字提示为空（不显示）
    if (n < 0) {
      istrue.value = false
      clearInterval(time)
    }
  }, 1000)
}

// 删除
const del = (row) => {
  const ids = row.id // 这里原代码有问题，应该是row.id而不是this.ids
  ElMessageBox.confirm(t('sip.mediaServer998535-7', [ids]))
    .then(async function () {
      await delmediaServer(ids)
      await getServerList()
    })
    .then(() => {
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

// 根据宽度计算数量（使用函数声明以保证可在初始化时调用）
function getNumberByWidth() {
  let candidateNums = [1, 2, 3, 4, 6, 8, 12, 24]
  let clientWidth = window.innerWidth - 30
  let interval = 20
  let itemWidth = 360
  let num = (clientWidth + interval) / (itemWidth + interval)
  let result = Math.ceil(24 / num)
  let resultVal = 24
  for (let i = 0; i < candidateNums.length; i++) {
    let value = candidateNums[i]
    if (i + 1 >= candidateNums.length) {
      return 24
    }
    if (value <= result && candidateNums[i + 1] > result) {
      return value
    }
  }
  return resultVal
}
</script>

<style lang="scss" scoped>
::v-deep .el-descriptions__body {
  background-color: transparent;
}
.card-item {
  border-radius: 10px;
  padding: 15px 0px;
  background-image: linear-gradient(#e9f1fc, #fefefe);
  border: 0;
}
</style>
