<template>
  <div class="search-table-container">
    <header>
      <RealtimePush v-if="managementPermission" />
      <div class="table-search">
        <section class="select-box">
          <div class="select-box--item">
            <span>地点：</span>
            <el-input style="width: 300px" v-model="searchData.captureLocation" placeholder="请输入地点" clearable>
            </el-input>
          </div>
          <div class="select-box--item">
            <span>时间：</span>
            <el-date-picker
              v-model="searchTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </section>
        <section class="search-btn">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleDownload">导出</el-button>
        </section>
      </div>
    </header>
    <!-- 表格 -->
    <BasicTable
      ref="basicTableRef"
      :tableData="tableData"
      :tableConfig="tableConfig"
      @update:pageSize="handleSizeChange"
      @update:pageNumber="handleCurrentChange"
    >
      <template #eventType="scope">
        <span>{{ BREAK_EVENT_TYPE_LABEL[scope.row.eventType] || '-' }}</span>
      </template>
      <template #captureLocation="scope">
        <span>{{ scope.row.captureLocation || '-' }}</span>
      </template>
      <template #captureTime="scope">
        <span>{{ scope.row.captureTime || '-' }}</span>
      </template>
      <template #capturePhotos="scope">
        <ImageViewer :file-list="scope.row.capturePhotos" />
      </template>
      <template #dataSource="scope">
        <span>{{ DATA_SOURCE_TYPE_LABEL[scope.row.dataSource] || '-' }}</span>
      </template>
    </BasicTable>
  </div>
</template>

<script setup lang="ts">
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { onMounted, reactive, ref } from 'vue';
  import { QueryPageRequest, QueryPageResponse } from '@/types/basic-query';
  import { BreakTableData, BreakTableQuery } from '../types';
  import { ALARM_PUSH_PROMISSION_CODE, BREAK_EVENT_TYPE_LABEL, DATA_SOURCE_TYPE_LABEL } from '../constants';
  import { OUTER_PERSON_BREAK_TABLE_COLUMNS, TABLE_OPTIONS } from '../configs/table';
  import { exportBreakTableList, getBreakTableList } from '@/api/security-confidentiality-person/outer-person';
  import { ElMessage } from 'element-plus';
  import { downloadFile } from '@/views/disaster/utils';
  import RealtimePush from './RealtimePush.vue';
  import ImageViewer from '@/views/traffic/violation/act/components/ImageViewer.vue';
  import dayjs from 'dayjs';

  import { useUserInfoHook } from '@/hooks/useUserInfoHook';

  const { permissions } = useUserInfoHook();
  const managementPermission = ref<Boolean>(
    Boolean(permissions.find((item: { code: string }) => item.code === ALARM_PUSH_PROMISSION_CODE)),
  );

  const searchData = reactive<BreakTableQuery>({});
  const searchTime = ref<string[]>();

  const { tableConfig, pagination } = useTableConfig(OUTER_PERSON_BREAK_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableData = ref<BreakTableData[]>([]);

  const tableQuery = reactive<QueryPageRequest<BreakTableQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  });
  function getQuery() {
    tableQuery.queryParam = {};
    if (searchData.captureLocation != null) {
      tableQuery.queryParam.captureLocation = searchData.captureLocation;
    }
    if (searchTime.value) {
      tableQuery.queryParam.startTime = searchTime.value[0];
      tableQuery.queryParam.endTime = searchTime.value[1];
    }
  }
  async function getTableData() {
    tableConfig.loading = true;
    const res = await getBreakTableList(tableQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  }

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  function handleSearch() {
    getQuery();
    getTableData();
  }

  function handleReset() {
    for (const key in searchData) {
      if (searchData.hasOwnProperty(key)) {
        searchData[key] = undefined;
      }
    }
    searchTime.value = [];
    handleSearch();
  }

  async function handleDownload() {
    getQuery();
    try {
      const res = await exportBreakTableList(tableQuery.queryParam);
      if (res.size === 0) return;
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      downloadFile(url, '闯入记录.xlsx');
    } catch (e) {
      ElMessage.error('下载失败');
      console.log(e);
    }
  }
  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  .table-search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }
  .select-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 32px;
    &--item {
      @include flex-center;
      white-space: nowrap;
    }
    span {
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
    }
    .el-select {
      width: 200px;
    }
  }
  .search-btn {
    display: flex;
  }
</style>
