<template>
  <div class="invasion-snapshot-container">
    <div class="switch-container" v-if="monitorManagePermission">
      <el-tooltip effect="light" content="开关关闭后，抓拍到的入侵行为将不在此进行记录展示" placement="top">
        <img src="@/assets/icons/help.png" alt="" />
      </el-tooltip>
      <span>抓拍启停</span>
      <el-switch v-model="switchStatus" @change="updateSwitchStatus" />
    </div>
    <div class="search-container">
      <div class="search-location">
        <span>抓拍地点：</span>
        <el-input
          v-model="searchKeyword"
          placeholder="请输入抓拍地点"
          clearable
          @input="handleSearch"
          @keyup.enter="handleSearch"
          style="width: 280px"
        >
          <template #prefix>
            <el-icon color="#1777ff"><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="search-time">
        <span>抓拍时间：</span>
        <el-date-picker
          v-model="queryTimes"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleSearch"
        />
      </div>
      <div class="search-container-btn">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleExport">导出</el-button>
      </div>
    </div>
    <div class="table-container">
      <BasicTable
        ref="basicTableRef"
        :tableData="tableData"
        :tableConfig="tableConfig"
        @update:page-number="handleCurrentPageChange"
        @update:page-size="handlePageSizeChange"
      >
        <template #pictures="scope">
          <ImageViewer :file-list="scope.row.pictures" />
        </template>
      </BasicTable>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Search } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import { downloadByData } from '@/utils/file/download';
  import { msgConfirm } from '@/utils/element-plus/messageBox';
  import { getCurrentDateTimeString } from '@/utils/dateUtil';
  import type { QueryPageRequest } from '@/types/basic-query';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { SECURITY_CONFIDENTIALITY_PERMISSIONS } from '@/views/security-confidentiality/constant';
  import ImageViewer from '@/views/traffic/violation/act/components/ImageViewer.vue';
  import {
    getInvasionSnapshotSwitch,
    updateInvasionSnapshotSwitch,
    getInvasionSnapshotList,
    exportInvasionSnapshot,
    type QueryInvasionSnapshotParams,
    type QueryInvasionSnapshotRes,
  } from '@/api/security-confidentiality-position';
  import {
    INVASION_SNAPSHOT_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    INVASION_SNAPSHOT_LIST_TABLE_MAX_HEIGHT_PERMISSION,
    INVASION_SNAPSHOT_LIST_TABLE_OPTIONS,
    INVASION_SNAPSHOT_LIST_TABLE_COLUMNS,
  } from '../config';

  const { tableConfig, pagination } = useTableConfig(
    INVASION_SNAPSHOT_LIST_TABLE_COLUMNS,
    INVASION_SNAPSHOT_LIST_TABLE_OPTIONS,
  );

  const { permissions } = useUserInfoHook();
  const monitorManagePermission = ref<boolean>(false);

  const switchStatus = ref(true);
  const searchKeyword = ref('');
  const queryTimes = ref(['', '']);

  const invasionSnapshotTableQuery: QueryPageRequest<QueryInvasionSnapshotParams> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };

  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const tableData = ref<QueryInvasionSnapshotRes[]>([]);

  const getSwitchStatus = async () => {
    switchStatus.value = await getInvasionSnapshotSwitch();
  };

  const updateSwitchStatus = async () => {
    await updateInvasionSnapshotSwitch({ switchStatus: switchStatus.value });
  };

  const handleSearch = () => {
    if (!queryTimes.value) queryTimes.value = ['', ''];
    getTableData();
  };

  const handleReset = () => {
    searchKeyword.value = '';
    queryTimes.value = ['', ''];
    getTableData();
  };

  // 导出
  const handleExport = () => {
    msgConfirm('确定导出所查询数据？', '导出', {
      confirmButtonText: '确定',
      showCancelButton: true,
      type: 'warning',
    })
      .then(() => {
        const exportParams: QueryInvasionSnapshotParams = {
          location: searchKeyword.value || undefined,
          startTime: queryTimes.value[0] || undefined,
          endTime: queryTimes.value[1] || undefined,
        };
        exportInvasionSnapshot(exportParams).then(async (response) => {
          if (!response) {
            throw new Error('下载文件失败');
          }
          downloadByData(response, `入侵抓拍记录_${getCurrentDateTimeString()}.xlsx`);
          ElMessage.success('下载文件成功');
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消导出',
        });
      });
  };

  const handleCurrentPageChange = (pageNumber: number) => {
    pagination.pageNumber = pageNumber;
    invasionSnapshotTableQuery.pageNumber = pageNumber;
    getTableData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    invasionSnapshotTableQuery.pageSize = pageSize;
    getTableData();
  };

  const getTableData = () => {
    tableConfig.loading = true;
    invasionSnapshotTableQuery.queryParam = {
      location: searchKeyword.value || undefined,
      startTime: queryTimes.value[0] || undefined,
      endTime: queryTimes.value[1] || undefined,
    };
    getInvasionSnapshotList(invasionSnapshotTableQuery).then((res) => {
      tableData.value = res?.records || [];
      pagination.total = res?.totalRow || 0;
    });
    tableConfig.loading = false;
  };

  onMounted(() => {
    monitorManagePermission.value = Boolean(
      permissions.find(
        (item: { code: string }) =>
          item.code === SECURITY_CONFIDENTIALITY_PERMISSIONS.CONFIDENTIALITY_POSITION_MONITOR_MANAGEMENT,
      ),
    );

    if (monitorManagePermission.value) {
      getSwitchStatus();
    }
    getTableData();
    tableConfig.maxHeight = monitorManagePermission.value
      ? INVASION_SNAPSHOT_LIST_TABLE_MAX_HEIGHT_PERMISSION
      : INVASION_SNAPSHOT_LIST_TABLE_MAX_HEIGHT_DEFAULT;
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;

  .invasion-snapshot-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .switch-container {
    display: flex;
    align-items: center;
    gap: 10px;
    line-height: 32px;
    margin-bottom: 20px;
    font-size: 14px;
  }

  .search-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 20px;

    .search-location,
    .search-time {
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .search-container-btn {
      margin-left: auto;
      display: flex;
      gap: 8px;
    }
  }

  .table-container {
    width: 100%;
    height: 100%;
  }
</style>
