<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="userName">
              <el-select v-model="queryParams.userName" placeholder="请选择" clearable style="width: 160px">
                <el-option label="绑定的设备" :value="0" />
              </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="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 class="monitor-dialog" 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" append-to-body 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 { DemoVO, DemoQuery, DemoForm } from '@/api/demo/demo/types';

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();
});
</script>

<style lang="scss" scoped>
/* 全屏监控弹窗：占满视口、禁止外层滚动，视频在可视区内尽可能放大 */
.monitor-video-stack {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
