<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> 车辆出入记录 </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div class="table-search">
            <section class="select-box">
              <SelectableInput ref="selectableInputRef" :options="VEHICLE_TABLE_SEARCH_OPTIONS" />
              <div class="select-box--item">
                <span>时间：</span>
                <el-date-picker
                  v-model="searchTime"
                  type="datetimerange"
                  range-separator="至"
                  start-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 #carNum="scope">
            <span>{{ scope.row.carNum ? scope.row.carNum : '--' }}</span>
          </template>
          <template #carOwnerName="scope">
            <span>{{
              scope.row.carOwnerName && scope.row.staffNo ? scope.row.carOwnerName + '-' + scope.row.staffNo : '--'
            }}</span>
          </template>
          <template #deptName="scope">
            <span>{{ scope.row.deptName || '--' }}</span>
          </template>
          <template #entryLocation="scope">
            <span>{{ scope.row.entryLocation || '--' }}</span>
          </template>
          <template #entryTime="scope">
            <span>{{ scope.row.entryTime || '--' }}</span>
          </template>
          <template #images="scope">
            <ImageViewer :file-list="scope.row.images" />
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import SelectableInput from '@/components/formItems/selectableInput/SelectableInput.vue';
  import ImageViewer from '@/views/traffic/violation/act/components/ImageViewer.vue';
  import { downloadFile } from '@/views/disaster/utils';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { ref, reactive, onMounted } from 'vue';
  import { VEHICLE_TABLE_SEARCH_OPTIONS } from './constants';
  import { TABLE_OPTIONS, VEHICLE_TABLE_COLUMNS } from './configs/tables';
  import { getVehicleRecordList, exportVehicleRecordList } from '@/api/security-confidentiality-vehicle';
  import type { VehicleTableData, VehicleTableQuery } from './types';
  import type { QueryPageRequest } from '@/types/basic-query';

  const searchTime = ref<string[]>([
    dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
  ]);
  const selectableInputRef = ref<InstanceType<typeof SelectableInput>>();
  function getQuery() {
    const selectableSearch = selectableInputRef.value?.getValue();
    tableQuery.queryParam = {
      fieldType: selectableSearch?.key as number | null,
      fieldContent: selectableSearch?.value,
    };
    if (searchTime.value) {
      tableQuery.queryParam.startTime = searchTime.value[0];
      tableQuery.queryParam.endTime = searchTime.value[1];
    }
  }
  async function getTableData() {
    tableConfig.loading = true;
    const res = await getVehicleRecordList(tableQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  }
  function handleSearch() {
    getQuery();
    getTableData();
  }

  function handleReset() {
    selectableInputRef.value?.clearValue();
    for (const key in tableQuery.queryParam) {
      if (tableQuery.queryParam.hasOwnProperty(key)) {
        tableQuery.queryParam[key] = undefined;
      }
    }
    searchTime.value = [
      dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    ];
    handleSearch();
  }

  async function handleDownload() {
    getQuery();
    try {
      const res = await exportVehicleRecordList(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);
    }
  }

  // 表格
  const { tableConfig, pagination } = useTableConfig(VEHICLE_TABLE_COLUMNS, TABLE_OPTIONS);
  const tableData = ref<VehicleTableData[]>([]);

  const tableQuery = reactive<QueryPageRequest<VehicleTableQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  });

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

  onMounted(() => {
    handleSearch();
  });
</script>

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

  .table-search {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    width: 100%;
  }
  .select-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
    &--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>
