<template>
  <div class="access-records-container">
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        :placeholder="`请输入${curSearchTypeLabel}进行搜索`"
        clearable
        @input="handleSearch"
        @keyup.enter="handleSearch"
        style="width: 400px"
      >
        <template #prefix>
          <el-icon color="#1777ff"><Search /></el-icon>
        </template>
        <template #prepend>
          <el-select
            v-model="searchSelectedType"
            placeholder="选择搜索项"
            @change="handleSelectedTypeChange"
            style="width: 100px"
          >
            <el-option v-for="item in accessQueryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
      </el-input>
      <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"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, 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 {
    getAccessRecordList,
    exportAccessRecord,
    type QueryAccessRecordParams,
    type QueryAccessRecordRes,
  } from '@/api/security-confidentiality-position';
  import {
    ACCESS_RECORD_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    ACCESS_RECORD_LIST_TABLE_OPTIONS,
    ACCESS_RECORD_LIST_TABLE_COLUMNS,
  } from '../config/table';
  import { ACCESS_FIELDTYPE, ACCESS_FIELD_CONTENT, accessQueryOptions } from '../constant';

  const { tableConfig, pagination } = useTableConfig(
    ACCESS_RECORD_LIST_TABLE_COLUMNS,
    ACCESS_RECORD_LIST_TABLE_OPTIONS,
  );

  const searchSelectedType = ref(ACCESS_FIELDTYPE.USERNAME);
  const searchKeyword = ref('');
  const queryTimes = ref(['', '']);
  const curSearchTypeLabel = computed(() => {
    const option = accessQueryOptions.find((item) => item.value === searchSelectedType.value);
    return option ? option.label : ACCESS_FIELD_CONTENT[searchSelectedType.value];
  });

  const accessRecordTableQuery: QueryPageRequest<QueryAccessRecordParams> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };

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

  const handleSelectedTypeChange = () => {
    searchKeyword.value = '';
  };

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

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

  // 导出
  const handleExport = () => {
    msgConfirm('确定导出所查询数据？', '导出', {
      confirmButtonText: '确定',
      showCancelButton: true,
      type: 'warning',
    })
      .then(() => {
        const exportParams: QueryAccessRecordParams = {
          startTime: queryTimes.value[0] || undefined,
          endTime: queryTimes.value[1] || undefined,
        };

        // 根据搜索类型设置对应的参数
        if (searchKeyword.value) {
          switch (searchSelectedType.value) {
            case ACCESS_FIELDTYPE.USERNAME:
              exportParams.username = searchKeyword.value;
              break;
            case ACCESS_FIELDTYPE.CARD_NUM:
              exportParams.cardNum = searchKeyword.value;
              break;
            case ACCESS_FIELDTYPE.DEPT_NAME:
              exportParams.deptName = searchKeyword.value;
              break;
            case ACCESS_FIELDTYPE.LOCATION:
              exportParams.location = searchKeyword.value;
              break;
          }
        }

        exportAccessRecord(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;
    accessRecordTableQuery.pageNumber = pageNumber;
    getTableData();
  };

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

  const getTableData = () => {
    tableConfig.loading = true;
    accessRecordTableQuery.queryParam = {
      startTime: queryTimes.value[0] || undefined,
      endTime: queryTimes.value[1] || undefined,
    };

    // 根据搜索类型设置对应的参数
    if (searchKeyword.value) {
      switch (searchSelectedType.value) {
        case ACCESS_FIELDTYPE.USERNAME:
          accessRecordTableQuery.queryParam.username = searchKeyword.value;
          break;
        case ACCESS_FIELDTYPE.CARD_NUM:
          accessRecordTableQuery.queryParam.cardNum = searchKeyword.value;
          break;
        case ACCESS_FIELDTYPE.DEPT_NAME:
          accessRecordTableQuery.queryParam.deptName = searchKeyword.value;
          break;
        case ACCESS_FIELDTYPE.LOCATION:
          accessRecordTableQuery.queryParam.location = searchKeyword.value;
          break;
      }
    }

    getAccessRecordList(accessRecordTableQuery).then((res) => {
      tableData.value = res?.records || [];
      pagination.total = res?.totalRow || 0;
    });
    tableConfig.loading = false;
  };

  onMounted(() => {
    getTableData();
    tableConfig.maxHeight = ACCESS_RECORD_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 *;

  .access-records-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .search-container {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;

    .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>
