<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备选择" prop="deviceId">
              <el-select v-model="queryParams.deviceId" placeholder="请选择" clearable style="width: 160px">
                <el-option v-for="item in deviceInfo" :key="item.id || item.code" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="报警编号" prop="alarmCode">
              <el-input v-model="queryParams.alarmCode" placeholder="请输入报警编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报警时间" prop="queryTime">
              <el-date-picker
                v-model="queryParams.queryTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <!-- <template #header>
        <el-row :gutter="10" class="flex justify-end mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['demo:demo:add']" type="primary" plain icon="Plus" @click="handleAdd">添加设备</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['demo:demo:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >批量唤醒</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['demo:demo:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
      </template> -->

      <el-table v-loading="loading" border :data="demoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="录像编号" align="center" prop="code" width="180" />
        <el-table-column label="文件名称" align="center" prop="videoName" min-width="170" />
        <el-table-column label="所属设备" align="center" prop="deviceName" min-width="120" show-overflow-tooltip />
        <el-table-column label="报警编号" align="center" prop="alarmCode" min-width="120" show-overflow-tooltip />
        <el-table-column label="录像开始时间" align="center" prop="startTime" min-width="120" show-overflow-tooltip />
        <el-table-column label="录像结束时间" align="center" prop="endTime" min-width="120" show-overflow-tooltip />
        <el-table-column label="录像时长" align="center" prop="durationFormat" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
          <template #default="scope">
            <el-button type="primary" @click="handlePlay(scope.row)">播放</el-button>
            <el-button type="primary" @click="handleDown(scope.row)">下载至本地</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改测试单对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" class="monitor-dialog" fullscreen destroy-on-close>
      <template #header>
        <div class="flex w-full items-center justify-between gap-2 min-w-0 pr-8">
          <span class="truncate">实时监控-北门出入门监控</span>
        </div>
      </template>
      <div class="monitor-video-wrap">
        <div class="monitor-video-stack">
          <video ref="monitorVideoRef" class="monitor-video" controls preload="metadata" :src="monitorVideoUrl">您的浏览器不支持视频播放</video>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Demo" lang="ts">
import { listDemo, getDemo, delDemo, addDemo, updateDemo } from '@/api/fileList/index';
import { download } from '@/utils/request';
import { onBeforeRouteLeave } from 'vue-router';
//import { DemoVO, DemoQuery, DemoForm } from '@/api/demo/demo/types';
import { useDeviceStore } from '@/store/modules/equipmentList';
import { storeToRefs } from 'pinia';
const deviceStore = useDeviceStore();
const { deviceList } = storeToRefs(deviceStore);
const { getdeviceList } = deviceStore;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const demoList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const monitorVideoUrl = ref();
const downloadUrl = ref();

const queryFormRef = ref<ElFormInstance>();
const demoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData = {
  id: undefined,
  deptId: undefined,
  userId: undefined,
  orderNum: undefined,
  testKey: undefined,
  value: undefined
};
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    deviceId: undefined,
    queryTime: undefined
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '部门id不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '排序号不能为空', trigger: 'blur' }],
    testKey: [{ required: true, message: 'key键不能为空', trigger: 'blur' }],
    value: [{ required: true, message: '值不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询测试单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDemo(queryParams.value);
  demoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  demoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加测试单';
};

/** 修改按钮操作 */
const handlePlay = async (row?: any) => {
  // reset();
  // const _id = row?.id || ids.value[0];
  // const res = await getDemo(_id);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = '修改测试单';

  if (!row || !row.videoUrl) {
    proxy?.$modal.msgError('视频地址不存在');
    return;
  }
  monitorVideoUrl.value = row.videoUrl;
  dialog.visible = true;
};
const handleDown = async (row?: any) => {
  if (!row || !row.zipUrl) {
    proxy?.$modal.msgError('下载地址不存在');
    return;
  }
  const fileName = row.videoName || `file_${new Date().getTime()}.zip`;
  //console.log(row, fileName);

  // 1. 创建隐藏的 a 元素
  const link = document.createElement('a');
  link.href = row.zipUrl; // 文件路径
  link.download = fileName; // 指定下载的文件名
  link.style.display = 'none';

  // 2. 挂载到 DOM 并模拟点击
  document.body.appendChild(link);
  link.click();

  // 3. 移除元素，保持页面整洁
  document.body.removeChild(link);
};

/** 提交按钮 */
const submitForm = () => {
  demoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDemo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDemo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除测试单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDemo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'demo/demo/export',
    {
      ...queryParams.value
    },
    `demo_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});

onBeforeRouteLeave(() => {
  dialog.visible = false;
  monitorVideoUrl.value = '';
});

//获取设备名称-搜索_设备选择
const deviceInfo = ref([]);
const getDeviceName = async () => {
  try {
    await getdeviceList();
    deviceInfo.value = deviceList.value;
    console.log('设备列表：', deviceInfo.value);
  } catch (error) {
    proxy?.$modal.msgError('获取设备列表失败');
  }
  // const res = await getdeviceList();
  // deviceInfo.value = res?.rows;
};
onMounted(() => {
  getDeviceName();
});
</script>

<style lang="scss" scoped>
/* 全屏监控弹窗：占满视口、禁止外层滚动，视频在可视区内尽可能放大 */
:deep(.monitor-dialog.el-dialog) {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-height: 100vh;
  margin: 0;
  overflow: hidden;
}

:deep(.monitor-dialog .el-dialog__header) {
  flex-shrink: 0;
  margin-right: 0;
}

:deep(.monitor-dialog .el-dialog__body) {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.monitor-video-wrap {
  flex: 1;
  min-height: 0;
  width: 100%;
  display: flex;
  align-items: stretch;
  justify-content: center;
  background: #000;
}

.monitor-video-stack {
  position: relative;
  flex: 1;
  min-height: 0;
  width: 100%;
}

.monitor-video {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain; //cover裁剪
  background: #000;
}

.monitor-draw-overlay {
  position: absolute;
  inset: 0;
  z-index: 2;
  cursor: crosshair;
  background: transparent;
}
</style>
