<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="INNER_PERSON_TABLE_SEARCH_OPTIONS" />
              <div class="select-box--item">
                <span>部门：</span>
                <el-select
                  style="width: 280px"
                  v-model="searchData.deptName"
                  placeholder="请选择部门"
                  class="select-box--select"
                  clearable
                >
                  <el-option
                    v-for="item in deptNameList"
                    :key="item.value"
                    :value="item.label"
                    :label="item.label"
                    :disabled="item.disabled"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>事件：</span>
                <el-select
                  v-model="searchData.eventType"
                  placeholder="请选择事件类型"
                  class="select-box--select"
                  clearable
                >
                  <el-option
                    v-for="item in OCCURRENCE_TYPE_OPTIONS"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                    :disabled="item.disabled"
                  />
                </el-select>
              </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 #employeeName="scope">
            <span>{{ scope.row.employeeName || '-' }}</span>
          </template>
          <template #staffNo="scope">
            <span>{{ scope.row.staffNo || '-' }}</span>
          </template>
          <template #deptName="scope">
            <span>{{ scope.row.deptName || '-' }}</span>
          </template>
          <template #eventType="scope">
            <span>{{ OCCURRENCE_TYPE_LABEL[scope.row.eventType] || '-' }}</span>
          </template>
          <template #location="scope">
            <span>{{ scope.row.location || '-' }}</span>
          </template>
          <template #entryTime="scope">
            <span>{{ scope.row.entryTime || '-' }}</span>
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import SelectableInput from '@/components/formItems/selectableInput/SelectableInput.vue';
  import { TABLE_OPTIONS, INNER_PERSON_TABLE_COLUMNS } from './configs/table';
  import { onMounted, reactive, ref } from 'vue';
  import { QueryPageRequest, QueryPageResponse } from '@/types/basic-query';
  import type { InnerPersonTableData, InnerPersonTableQuery } from './types';
  import { INNER_PERSON_TABLE_SEARCH_OPTIONS, OCCURRENCE_TYPE_OPTIONS, OCCURRENCE_TYPE_LABEL } from './constants';
  import {
    exportInnerPersonRecordList,
    getDeptNameList,
    getInnerPersonRecordList,
  } from '@/api/security-confidentiality-person/inner-person';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { downloadFile } from '@/views/disaster/utils';

  const searchData = reactive<InnerPersonTableQuery>({});
  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() {
    if (!selectableInputRef.value) return;
    tableQuery.queryParam = {};
    const selectableSearch = selectableInputRef.value.getValue();
    if (selectableSearch) {
      tableQuery.queryParam[selectableSearch.key as string] = selectableSearch.value;
    }
    if (searchData.deptName != null) {
      tableQuery.queryParam.deptName = searchData.deptName;
    }
    if (searchData.eventType != null) {
      tableQuery.queryParam.eventType = searchData.eventType;
    }
    if (searchTime.value) {
      tableQuery.queryParam.startTime = searchTime.value[0];
      tableQuery.queryParam.endTime = searchTime.value[1];
    }
  }
  async function getTableData() {
    tableConfig.loading = true;
    const res = await getInnerPersonRecordList(tableQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  }

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

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

  const tableQuery = reactive<QueryPageRequest<InnerPersonTableQuery>>({
    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();
  };

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

  function handleReset() {
    selectableInputRef.value?.clearValue();
    for (const key in searchData) {
      if (searchData.hasOwnProperty(key)) {
        searchData[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 exportInnerPersonRecordList(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 deptNameList = ref<SelectOption[]>();
  const loadDeptNameData = async () => {
    const result = await getDeptNameList();
    deptNameList.value = result.map((x, index) => {
      return {
        label: x,
        value: index,
        disabled: false,
      };
    });
  };

  onMounted(() => {
    loadDeptNameData();
    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>
