<template>
  <div class="tab-content h-full">
    <div class="subtitle"><span></span> <el-button type="primary" v-auth="'add'" size="small" @click="addDevice()">添加监控</el-button></div>
    <el-table :data="tableData" style="width: 100%" v-loading="loading" max-height="calc(100vh - 280px)">
      <el-table-column prop="name" label="设备名称" min-width="130" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="deviceId" label="设备ID" min-width="210" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="name" label="通道名称" min-width="140" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="model" label="型号" width="100" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="manufacturer" label="厂商" width="100" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="liveStatus" label="状态" width="100" align="center" :formatter="formatLiveStatus" show-overflow-tooltip></el-table-column>
      <el-table-column prop="keepAliveTime" label="最后心跳时间" :formatter="formatTime" width="170" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="registerTime" label="注册时间" :formatter="formatTime" width="170" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="updateAt" label="更新时间" :formatter="formatTime" width="170" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template #default="scope">
          <el-button size="small" text type="primary" v-auth="'detail'" @click="view(scope.row)">查看监控</el-button>
          <el-button size="small" text type="warning" v-auth="'del'" @click="onDel(scope.row)">解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="添加监控" v-model="isShowDialog" width="400">
      <el-form v-if="isShowDialog">
        <el-form-item label="监控" style="margin-bottom: 0">
          <el-select v-model="form.resourcesKey" filterable placeholder="选择监控" :clearable="false" style="width: 100%">
            <el-option v-for="item in options" :disabled="item.disabled" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="预览监控" v-model="isShowPreviewDialog" width="90vh">
      <template #header>
        <span class="dialog-footer">
          <el-button type="primary" size="small" @click="openToNewWindow">新窗口预览</el-button>
        </span>
      </template>
      <iframe v-if="isShowPreviewDialog" :src="previewUrl" style="width: 100%; height: 50vh"></iframe>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import api from "/@/api/projects";
import { useRoute } from "vue-router";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { getMediaOrigin } from "/@/utils/origin";
const route = useRoute();

const props = defineProps({ resourcesTypes: Number });
const isShowDialog = ref(false);
const isShowPreviewDialog = ref(false);
const loading = ref(false);
const previewUrl = ref("");
const options = ref<any[]>([]);
const tableData = ref<any[]>([]);
const channels = ref<any[]>([]);
const resourcesTypes = props.resourcesTypes!;
const projectsCode = route.params.id;

const baseForm = {
  resourcesKey: "",
  projectsCode,
  resourcesTypes,
};

const form = reactive({
  ...baseForm,
});

getOptions();

function getSourceList() {
  api.getProjectResourcesByCode({ projectsCode }).then((res: any) => {
    const ids = (res || []).filter((item: any) => item.resourcesTypes === resourcesTypes).map((item: any) => item.resourcesKey);

    const tableDataList: any[] = [];

    ids.forEach((id: string) => {
      const [deviceID, channelID] = id.split("-");
      const channel = channels.value.find((channel: any) => channel.deviceId === deviceID && channel.channelId === channelID);
      if (channel) {
        options.value.find((item: any) => item.value === id).disabled = true;
        tableDataList.push(channel);
      }
    });

    tableData.value = tableDataList;
  });
}

function getOptions() {
  // 获取流媒体设备列表，拼接成通道列表 设备ID-通道ID
  axios.get(getMediaOrigin("/gb28181/api/list?page=1&count=1000&format=json")).then((res: any) => {
    const optionsList: any[] = [];
    const channelsList: any[] = [];
    res.data.data.forEach((item: any) => {
      item.channels.forEach((channel: any) => {
        optionsList.push({ label: item.name + " - " + channel.name, value: item.deviceId + "-" + channel.channelId });
        channelsList.push({
          ...channel,
          name: item.name,
          netAddr: item.netAddr,
          registerTime: item.registerTime,
          updateAt: item.updateAt,
          keepAliveTime: item.keepAliveTime,
          deviceId: channel.deviceId,
        });
      });
    });
    options.value = optionsList;
    channels.value = channelsList;
    getSourceList();
  });
}

function onCancel() {
  Object.assign(form, baseForm);
  isShowDialog.value = false;
}

function onSubmit() {
  if (!form.resourcesKey) return ElMessage("请先选择监控");
  api.bindResources(form).then(() => {
    onCancel();
    getSourceList();
    ElMessage.success("添加成功");
  });
}

function addDevice() {
  isShowDialog.value = true;
}

function view(row: any) {
  previewUrl.value = import.meta.env.VITE_SERVER_ORIGIN + "/plugin/media/index.html?ID=" + row.channelId + "&DeviceID=" + row.deviceId + "#/0/screen-preview";
  isShowPreviewDialog.value = true;
}

function openToNewWindow() {
  window.open(previewUrl.value);
  isShowPreviewDialog.value = false;
}

function onDel(row: any) {
  ElMessageBox.confirm(`确定要解绑该监控？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api
      .unbindResources({
        projectsCode,
        resourcesTypes,
        resourcesKey: row.ID + "-" + row.deviceId,
      })
      .then(() => {
        getSourceList();
        ElMessage.success("解绑成功");
      });
  });
}

function formatTime(row: any, column: any) {
  return dayjs(row[column.property]).format("YYYY-MM-DD HH:mm:ss");
}

function formatLiveStatus(row: any, column: any) {
  // 0 代表空闲，1 代表正在调用 invite，2 代表正在拉流
  return row[column.property] === 0 ? "空闲" : row[column.property] === 1 ? "调用中" : "拉流中";
}
</script>
