<template>
  <div class="search-table-container">
    <header>
      <div class="table-search">
        <section class="select-box">
          <SelectableInput ref="selectableInputRef" :options="VISITOR_TABLE_SEARCH_OPTIONS" />
          <div class="select-box--item">
            <span>是否外籍：</span>
            <el-select
              style="width: 100px"
              v-model="searchData.isForeigner"
              placeholder="请选择"
              class="select-box--select"
              clearable
            >
              <el-option
                v-for="item in IS_FOREIGNER_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-select
              style="width: 100px"
              v-model="searchData.visitState"
              placeholder="请选择"
              class="select-box--select"
              clearable
            >
              <el-option
                v-for="item in VISIT_STATE_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="visitTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
          <div class="select-box--item">
            <span>离开时间：</span>
            <el-date-picker
              v-model="leaveTime"
              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 #visitorName="scope">
        <span>{{ scope.row.visitorName || '--' }}</span>
      </template>

      <template #identityInfor="scope">
        <span>{{ managementPermission ? scope.row.identityInfor || '--' : '******' }}</span>
      </template>
      <template #mobile="scope">
        <span>{{ managementPermission ? scope.row.mobile || '--' : '******' }}</span>
      </template>
      <template #isForeigner="scope">
        <span>{{ IS_FOREIGNER_TYPE_LABEL[scope.row.isForeigner] || '--' }}</span>
      </template>
      <template #company="scope">
        <span>{{ scope.row.company || '--' }}</span>
      </template>
      <template #visitReason="scope">
        <span>{{ scope.row.visitReason || '--' }}</span>
      </template>
      <template #respondentName="scope">
        <span>{{
          scope.row.respondentName && scope.row.respondentNo
            ? scope.row.respondentName + '-' + scope.row.respondentNo
            : '--'
        }}</span>
      </template>
      <!-- <template #visitState="scope">
        <span>{{ VISIT_STATE_TYPE_LABEL[scope.row.visitState] || '--' }}</span>
      </template> -->
      <template #visitTime="scope">
        <span>{{ scope.row.visitTime || '--' }}</span>
      </template>
      <template #leaveTime="scope">
        <span>{{ scope.row.leaveTime || '--' }}</span>
      </template>
    </BasicTable>
  </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 { onMounted, reactive, ref } from 'vue';
  import { QueryPageRequest, QueryPageResponse } from '@/types/basic-query';
  import { VisitorTableData, VisitorTableQuery } from '../types';
  import { OUTER_PERSON_VISITOR_TABLE_COLUMNS, TABLE_OPTIONS } from '../configs/table';
  import {
    VISITOR_TABLE_SEARCH_OPTIONS,
    IS_FOREIGNER_TYPE_OPTIONS,
    IS_FOREIGNER_TYPE_LABEL,
    VISIT_STATE_TYPE_OPTIONS,
    VISIT_STATE_TYPE_LABEL,
    VISITOR_MANAGEMENT_PROMISSION_CODE,
  } from '../constants';
  import dayjs from 'dayjs';
  import { exportVisitorList, getVisitorList } from '@/api/security-confidentiality-person/outer-person';
  import { ElMessage } from 'element-plus';
  import { downloadFile } from '@/views/disaster/utils';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';

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

  const searchData = reactive<VisitorTableQuery>({});

  const visitTime = ref<string[]>([
    dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
  ]);
  const leaveTime = ref<string[]>();

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

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

  const tableQuery = reactive<QueryPageRequest<VisitorTableQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  });
  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.isForeigner != null) {
      tableQuery.queryParam.isForeigner = searchData.isForeigner;
    }
    if (searchData.visitState != null) {
      tableQuery.queryParam.visitState = searchData.visitState;
    }
    if (visitTime.value) {
      tableQuery.queryParam.visitStartTime = visitTime.value[0];
      tableQuery.queryParam.visitEndTime = visitTime.value[1];
    }
    if (leaveTime.value) {
      tableQuery.queryParam.leaveStartTime = leaveTime.value[0];
      tableQuery.queryParam.leaveEndTime = leaveTime.value[1];
    }
  }
  async function getTableData() {
    tableConfig.loading = true;
    const res = await getVisitorList(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() {
    selectableInputRef.value?.clearValue();
    for (const key in searchData) {
      if (searchData.hasOwnProperty(key)) {
        searchData[key] = undefined;
      }
    }
    visitTime.value = [
      dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    ];
    leaveTime.value = [];
    handleSearch();
  }

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

<style scoped lang="scss">
  .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>
